Q:

Unable to start MySQL from XAMPP Control Panel

I am learning SQL with Udemy courses and I am currently doing a course called 'Learning database design using MySQL'.
I have downloaded XAMPP and the course video start MySQL directly from the XAMPP control panel. I however am not able to start MySQL via the control panel. This is the message i get:
*
20:56:08  [mysql]   Attempting to start MySQL app...
20:56:09  [mysql]   Status change detected: running
20:56:12  [mysql]   Status change detected: stopped
20:56:12  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:12  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:12  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:12  [mysql]   Press the Logs button to view error logs and check
20:56:12  [mysql]   the Windows Event Viewer for more clues
20:56:12  [mysql]   If you need more help, copy and post this
20:56:12  [mysql]   entire log window on the forums
20:56:29  [mysql]   Problem detected!
20:56:29  [mysql]   Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57"!
20:56:29  [mysql]   MySQL WILL NOT start without the configured ports free!
20:56:29  [mysql]   You need to uninstall/disable/reconfigure the blocking application
20:56:29  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
20:56:29  [mysql]   Attempting to start MySQL app...
20:56:30  [mysql]   Status change detected: running
20:56:33  [mysql]   Status change detected: stopped
20:56:33  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:33  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:33  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:33  [mysql]   Press the Logs button to view error logs and check
20:56:33  [mysql]   the Windows Event Viewer for more clues
20:56:33  [mysql]   If you need more help, copy and post this
20:56:33  [mysql]   entire log window on the forums

*
I have logs that i can add if required. Also, i have downloaded sql community edition already and have used the command line functionality, however it is not running when trying to launch via the control panel.
I really want to learn so would really appreciate anyone who can help me overcome this issue.
Thanks
Graham

A:

You are trying to start XAMPP (which comes with mysql) but already have MySQL Server 5.7 installed and running on your computer.


Q:

Create class name in Rails for existing table name present in SQL server

I want to use SQL server table in rails.
Suppose I already have one table T_SDF in SQL server and I want to fetch all data from this table.
How can I create a model or class in Rails?
I am using Rails version 3.2.9 and Ruby version 1.9.3.

A:

I believe you are looking for self.table_name =
Documentation: http://apidock.com/rails/v3.2.8/ActiveRecord/ModelSchema/ClassMethods/table_name%3D
Example:
class SomeModel
  self.table_name = 'T_SDF'
end

Update
To generate a model for an existing table.
Run rails g model t_sdf. We don't want to pass any parameters to this since the table already exists.
Preparing the Migration
The previous command should have generated a file such as: db/migrate/20150415071801_create_t_sdfs.rb.
We will want to update it to create the table exactly as it already exists.
In MySQL I tend to execute the command show create table {{table_name}}
In SQL Server you should be able to follow the instructions here: show create table tablename (how do i do this in sql server)?
Once you have the string to create the table, paste the string into the execute statement in the example below.
class CreateTSdfs < ActiveRecord::Migration
  def up
    # We wrap the command in an unless statement because we
    # don't want to run it on production. However, it is important for
    # the table to be created for developers working on local databases.
    unless table_exists?('T_SDF')
      execute "paste the create table sql statement here"
    end
  end

  def down
    remove_table 'T_SDF'
  end
end

Preparing the Model
You should just need to set the table name of model file.
app/models/t_sdf.rb
class TSdf
  self.table_name = 'T_SDF'
end


Q:

Vue draggable works for whole group but not for each item

The code below allows dragging the groups in toListFetchRouteA1:
<draggable id="first" data-source="juju" :list="toListFetchRouteA1" class="list-group" draggable=".item" group="a">

         {{personame.Player.Person.first_name}}

</draggable>

I am trying to allow dragging each person name rather than by group, so I changed :list="toListFetchRouteA1" into :list="teamfetch.Team_player_sessions" (shown below), but it throws an error: Cannot read property 'Team_player_sessions' of undefined".
<draggable id="first" data-source="juju" :list="teamfetch.Team_player_sessions" class="list-group" draggable=".item" group="a">

         {{personame.Player.Person.first_name}}

</draggable>

It does not drag as well. Is there a way to make div v-for="personame in teamfetch.Team_player_sessions draggable for personname?

A:

The error occurs because teamfetch is out of scope. It was declared on the inner v-for but used in the outer element.
You could make the person names draggable by wrapping them in a second draggable (assuming you want the groups themselves and the names within the groups to be draggable):
<draggable :list="toListFetchRouteA1" class="list-group" draggable=".item" group="a">

    <draggable :list="teamfetch.Team_player_sessions" draggable=".person">

        {{personame.Player.Person.first_name}}

    </draggable>

</draggable>

new Vue({
  el: '#app',
  data: () => ({
    toListFetchRouteA1: [
      {
        id: 1,
        Team_player_sessions: [
          {
            id: 100,
            Player: {
              Person: {
                first_name: 'john'
              }
            }
          }
        ]
      },
      {
        id: 2,
        Team_player_sessions: [
          {
            id: 200,
            Player: {
              Person: {
                first_name: 'adam'
              }
            }
          },
          {
            id: 201,
            Player: {
              Person: {
                first_name: 'allen'
              }
            }
          }
        ]
      },
      {
        id: 3,
        Team_player_sessions: [
          {
            id: 300,
            Player: {
              Person: {
                first_name: 'dave'
              }
            }
          },
          {
            id: 301,
            Player: {
              Person: {
                first_name: 'dylan'
              }
            }
          }
        ]
      },
    ]
  }),
})
.item {
  background: #eee;
  margin: 2px;
  padding: 10px;
}

.person {
  background: #ccc;
  margin: 2px;
}

  <draggable :list="toListFetchRouteA1" class="list-group" draggable=".item" group="a">

        <draggable :list="teamfetch.Team_player_sessions" draggable=".person">

            {{personame.Player.Person.first_name}}

        </draggable>

  </draggable>

{{toListFetchRouteA1}}


Q:

While loop wont end

I am running a text based game and trying to get a function to repeat itself using a while loop but when the condition is met it wont stop.
<?php
/****************************************************************/
/*********************** Created By Seker ***********************/
/**** Feel free to modify in any way, but keep this section. ****/
/****************************************************************/
session_start();
require "global_func.php";
if ($_SESSION['loggedin'] == 0)
{
header("Location: login.php");
exit;
}
$userid = $_SESSION['userid'];
require "header.php";
$h = new headers;
$h->startheaders();
include "mysql.php";
global $c;
$is =
    mysql_query(
            "SELECT u.*,us.* FROM users u LEFT JOIN userstats us ON u.userid=us.userid WHERE u.userid=$userid",
            $c) or die(mysql_error());
$ir = mysql_fetch_array($is);
check_level();
$fm = money_formatter($ir['money']);
$cm = money_formatter($ir['crystals'], '');
$lv = date('F j, Y, g:i a', $ir['laston']);
$h->userdata($ir, $lv, $fm, $cm);
$h->menuarea();

switch ($_GET['action'])
{
case 'walk':
walk();
break;

case 'walk2':
 walk();
 break;

default:
home();
break;
}

function home()
{

global $ir,$h,$c,$userid;

$q=mysql_query("SELECT u.*,c.* FROM users u LEFT JOIN cities c ON u.location=c.cityid WHERE u.userid=$userid");
$r=mysql_fetch_array($q);

$city = $r['cityname'];
$trav = $ir['steps'];

echo "

                The $city Streets

                Take your chances with a walk through the $city streets!

                Each day, you get 10 steps! 25 if you are a donator!

                While traveling, you can find crystals, cash, or even gain experience!

                But, be careful! There are dangers in the streets!

";

echo "

                What would you like to do?

                You can travel {$trav} more times today!

                [Go For A Walk]

                [Change Your Mind]

";
}

function walk()
{
do
{

global $ir,$h,$c,$userid;

$q=mysql_query("SELECT u.*,c.* FROM users u LEFT JOIN cities c ON u.location=c.cityid WHERE u.userid=$userid");
$r=mysql_fetch_array($q);

$chance = mt_rand(1,100);
$city = $r['cityname'];
$trav = $ir['steps'];

if ($ir['steps'] <= 0)
{
    echo "
        You have traveled enough for today! Come back tomorrow!
        Home";
        exit($h->endpage());
}

if ($ir['hospital'])
{
    echo "
        You cannot travel while in the hospital!
        Home";
        exit($h->endpage());
}

if ($ir['jail'])
{
    echo "
        You cannot travel while in jail!
        Home";
        exit($h->endpage());
}

echo "

                You start your journey through the $city streets!

                You can travel up to {$trav} more times today!

";

if ($chance <= 10)
{
    $rewardtok = mt_rand(5,15);

    mysql_query("UPDATE users SET crystals=crystals+$rewardtok,steps=steps-1 WHERE userid=$userid");

    echo "

                    Congratulations! You found $rewardtok crystals while walking through the streets!

                    [Continue Traveling]

                    [Back]

";
}

if (($chance >= 15) && ($chance <= 30))
{
    $rewardg = mt_rand(100,5000);
    $reward = money_formatter($rewardg);

    mysql_query("UPDATE users SET money=money+$rewardg,steps=steps-1 WHERE userid=$userid");

    echo "

                    Congratulations! You found $reward while walking through the streets!

                    [Continue Traveling]

                    [Back]

";
}

if (($chance >= 40) && ($chance <= 50))
{
    $rewardexp = mt_rand(5,50) * ($ir['level'] /2);

    mysql_query("UPDATE users SET exp=exp+$rewardexp,steps=steps-1 WHERE userid=$userid");

    echo "

                    Congratulations! You gained $rewardexp experience while walking through the streets!

                    [Continue Traveling]

                    [Back]

";
}

if (($chance >= 55) && ($chance <= 65))
{
    $rewardexp = mt_rand(5,50);

    mysql_query("UPDATE users SET exp=exp+$rewardexp,steps=steps-1 WHERE userid=$userid");

    echo "

                    Congratulations! You gained $rewardexp experience while walking through the streets!

                    [Continue Traveling]

                    [Back]

";
        }

 if (($chance >= 75) && ($chance <= 85))
    {
     $rewardtok = mt_rand(5,15);

    mysql_query("UPDATE users SET crystals=crystals+$rewardtok,steps=steps-1 WHERE userid=$userid");

    echo "

                    Congratulations! You found $rewardtok crystals while walking through the streets!

                    [Continue Traveling]

                    [Back]

";
 }
if ((($chance > 10) && ($chance < 15)) || (($chance > 30) && ($chance < 40)) || (($chance > 50) && ($chance < 55)) || (($chance > 65) && ($chance < 75)) || ($chance > 85))
{
     $rewardtok = mt_rand(5,15);
      mysql_query("UPDATE users SET steps=steps-1 WHERE userid=$userid");

    echo "

                    You found nothing while walking through the streets

                    [Continue Traveling]

                    [Back]

";

  }

 }
while ($ir['steps'] > 0);
}
$h->endpage();

The function is supposed to run until the steps value is 0 which when the function runs once it subtracts from the total. yet it doesnt stop when it hits 0 and i get something like this "Steps: -15535"
i believe this is the "relivent code"
function walk()
{
do
{

global $ir,$h,$c,$userid;

$q=mysql_query("SELECT u.*,c.* FROM users u LEFT JOIN cities c ON u.location=c.cityid WHERE u.userid=$userid");
$r=mysql_fetch_array($q);

$chance = mt_rand(1,100);
$city = $r['cityname'];
$trav = $ir['steps'];

if ($ir['steps'] <= 0)
{
echo "
    You have traveled enough for today! Come back tomorrow!
    Home";
    exit($h->endpage());
}

if ($ir['hospital'])
{
echo "
    You cannot travel while in the hospital!
    Home";
    exit($h->endpage());
}

if ($ir['jail'])
{
echo "
    You cannot travel while in jail!
    Home";
    exit($h->endpage());
}

echo "

            You start your journey through the $city streets!

            You can travel up to {$trav} more times today!

";

if ($chance <= 10)
{
$rewardtok = mt_rand(5,15);

mysql_query("UPDATE users SET crystals=crystals+$rewardtok,steps=steps-1 WHERE userid=$userid");

echo "

                Congratulations! You found $rewardtok crystals while walking through the streets!

                [Continue Traveling]

                [Back]

";
}

if (($chance >= 15) && ($chance <= 30))
{
$rewardg = mt_rand(100,5000);
$reward = money_formatter($rewardg);

mysql_query("UPDATE users SET money=money+$rewardg,steps=steps-1 WHERE userid=$userid");

echo "

                Congratulations! You found $reward while walking through the streets!

                [Continue Traveling]

                [Back]

";
}

if (($chance >= 40) && ($chance <= 50))
{
$rewardexp = mt_rand(5,50) * ($ir['level'] /2);

mysql_query("UPDATE users SET exp=exp+$rewardexp,steps=steps-1 WHERE userid=$userid");

echo "

                Congratulations! You gained $rewardexp experience while walking through the streets!

                [Continue Traveling]

                [Back]

";
}

if (($chance >= 55) && ($chance <= 65))
{
$rewardexp = mt_rand(5,50);

mysql_query("UPDATE users SET exp=exp+$rewardexp,steps=steps-1 WHERE userid=$userid");

echo "

                Congratulations! You gained $rewardexp experience while walking through the streets!

                [Continue Traveling]

                [Back]

";
    }

 if (($chance >= 75) && ($chance <= 85))
{
 $rewardtok = mt_rand(5,15);

mysql_query("UPDATE users SET crystals=crystals+$rewardtok,steps=steps-1 WHERE userid=$userid");

echo "

                Congratulations! You found $rewardtok crystals while walking through the streets!

                [Continue Traveling]

                [Back]

";
 }
if ((($chance > 10) && ($chance < 15)) || (($chance > 30) && ($chance < 40)) || (($chance > 50) && ($chance < 55)) || (($chance > 65) && ($chance < 75)) || ($chance > 85))
{
 $rewardtok = mt_rand(5,15);
  mysql_query("UPDATE users SET steps=steps-1 WHERE userid=$userid");

echo "

                You found nothing while walking through the streets

                [Continue Traveling]

                [Back]

";

  }

 }
while ($ir['steps'] > 0);
}
$h->endpage();

A:

$ir['steps']

is not changed/decremented anywhere.
Decrement it before at the end of the loop:
$ir['steps'] -= 1;

Just before the closing bracket of the loop.


Q:

Complexity of natural language processing problems

Which natural language processing problems are NP-Complete or NP-Hard?
I've searched the natural-lang-processing and complexity-theory tags (and related complexity tags), but have not turned up any results.
None of the NLP questions that are recommended are helpful, the closest are the following:

https://cs.stackexchange.com/questions/25925/why-is-natural-language-processing-such-a-difficult-problem
https://cs.stackexchange.com/questions/9920/how-is-natural-language-processing-related-to-artificial-intelligence
What aspects of linguistics are necessary or good for natural language processing?

The Wikipedia list of NP-complete problems does not list any complexity results for NLP.
The only lead I've found is the paper Theoretical and Effective Complexity in Natural Language Processing by J. Morin (1995).
Any help or pointers is appreciated!

A:

Maybe one should first define what is a natural language processing (NLP)
problem.
For example, Context-Free (CF) grammars and languages were introduced
by linguists (Chomsky type 2 language, work of Bar-Hillel and others).
Ambiguity is a major problem in Linguistics for real sentence
analysis, and in the formal study of CF grammars (ambiguity) and
languages (inherent ambiguity). Ambiguity of a grammar is only semi-decidable.
So I guess the problem of ambiguity should be an answer to your
question. Does it classify as a NLP problem?
Now if you take some modern formalizations of syntax, such as a CF
backbone with feature structures (i.e. structured attributes), you
quickly get Turing power (cf LFG which have been proved NP hard, or
even Turing complete, depending on variants). So , if you are not careful, you
have all the complexity problems you might dream about.
For more, you can also look at this question from SE-Linguistics:
"Does the P versus NP conjecture in computer science have any direct
relevance to linguistics?"
In my own answer, I actually criticize the meaningfulness of the
question, or at least of some of its interpretations. Many of the
problems that are considered in linguistics, regarding analysis of
sentences, for translation or other purposes, are small problem, to be
solved in a very short time. Some linguists might even dispute that
there is real recursion in language structure, since whatever
recursion there is is rarely very deep. Hence one might wonder about
the linguistic relevance of complexity analysis which is defined
asymptotically. The first question should be whether we ever get close
enough to the asymptote for asymptotic analysis to be meaningful.
However, this remark does not apply to some aspect of NLP, when
massive amount of data have to be processed. I know of at least two
cases:

data mining in large corpora.
the inverse problem of linguistics: analysis of large corpora to
mechanically extract the data characterizing a language, both
structurally and to produce extensive lists of constituents, such
as phonemes, vocabulary for various parts of speech (aka
preterminals), prefixes and suffixes, or inflection mechanisms, to
give a few examples.

I am no expert in data mining, and thus do not know whether it
actually raises complexity problems related to the size of the corpora
being processed. In that case, asymptotic complexity would indeed be
an issue. But if it is mostly composed of a large number of small
additive tasks, then it is more doubtful that asymptotic complexity
matters much. However, I would imagine that some data mining
techniques will work with correlations between independent documents,
and that should raise corpus dependent complexity issues.
In the case of the inverse problem of linguistics, the identification
of a language (which, I guess, could be considered a data mining
problem), we are indeed trying to extract information by correlating
all parts of large corpora. Then asymptotic complexity becomes
extremely relevant. I have unfortunately no specific problem in mind,
probably because such systems have a pragmatic aim, and people
developing them will tend to simply avoid any form of higher
complexity, quadratic being probably already beyond the available
resources. But a search of the literature would probably raise some
complexity issues.
Another point is that linguistics does not have clearcut laws like
physics. It is more a matter of being close enough to what might be
considered current linguistic consensus, since no two people speak
exactly the same language. Hence, good approximations are usually
sufficient when the aim is so elusive. The techniques I have seen were
mainly fix-point techniques to identify parameters by iterative
recomputation of some function based on the corpus structure, until
it no longer makes much difference (plus user input to weed out
remaining pathological cases).
Analysing properties of grammars and other formalized linguistic
structures may also be a source of high complexity problems, as
mentioned above for ambiguity, since natural language descriptions are usually large enough for asymptotic analysis to be meaningful.

A:

LFG (Lexical-Functional Grammar) recognition is NP-Complete.
Edit per request: Lexical-Functional Grammar (LFG) [1] is a theory of natural language syntax, developed as an alternative to Chomsky's theories of transformational syntax. Some versions of Chomsky's theories are computationally equivalent to Unrestricted Grammars. LFG by contrast provides a grammar formalism which consists of a context-free grammar augmented by a feature system.
It's the feature system that's NP-complete. The proof works basically by noticing first that the feature system is at least as powerful as propositional logic, and second that grammaticality rests on satisfying all the propositional constraints governing the sentence. So it's the Satisfiability Problem hiding under another guise.
[1] "Lexical-Functional Grammar: A Formal System for Grammatical Representation" by
Ronald M Kaplan and Joan Bresnan. The paper originally appeared in The Mental Representation of Grammatical Relations, ed. Joan Bresnan (Cambridge, MA: The MIT Press, 1982).


Q:

Cannot download anything from Google Play store via mobile data

I have an LG G2 with Android 4.4.2. All of a sudden I cannot download apps or updates on the Google Play store: no error messages, it just spins its wheels. On the Google Play Store, it just says "Downloading..." with the loading bar running infinitely, and in my phone drop-down screen, the same thing. No progress bar, completion %, est. time, anything.
In my Settings › Mobile data menu, the "limit mobile data usage" option is NOT checked, and the problem persists on both 3G and 4G/LTE. My data limit has not been reached (I don't even think I have one).
In the Settings › Mobile data › Google Play Store menu, the "restrict background data" option is NOT checked either. In the Google Play app settings menu, the "Auto-update apps" is set to wifi-only, but that's how I want it. The problem is when I manually try to download/update, so that shouldn't be the problem.
My Google Play build version is 5.4.12, if that helps...
Wi-fi downloads are just peachy though.
Just checked my network signal strength and it's -116 dBm and 26 asu, whatever those mean.

A:

Open downloads app or download manager.  Change the setting of the max size of file you can download using mobile data.

A:

Ok I let an update attempt to download then came back to my phone about 10-15 min later, to see an error code 495, saying the update cannot download. So I Googled that error code and found this page: http://techknowzone.com/how-to-solve-fix-error-code-495-in-google-play-store/. I went down the list and followed each suggestion step by step.
The one that worked was disconnecting and reconnecting my Google acct from my phone. I had to reboot my device because it seems like whenever I clear the cache/data from Google Play Store and Google Framework Service and then open up Google Play store again, it says "unable to connect" no matter how many times I click "retry."
So I don't know exactly what was wrong- it seems like it's just a bug buried deep somewhere. But it works now. Network icons are still white.


Q:

Datatables generate column and get row id Server-side

I have got a datatable using Datatables server-side. I have created and filled the table as shown below. Now I need to generate column with button but i need to have the id of the row ..
My data returned :
{"data":[{"id":"13","name":"gerrard","adress":"new york"}, .... }

I want something like if i click in this button it show me the id of the row ..
There is my code :

                name
                adress

$(document).ready(function() {
    var oTable = $('#example').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "server-side-process",
            },

        "columns": [
                    { "data": "name" },
                    { "data": "adress" },
                ]
    } );

} );

I found this example in the documentation but i cant get the id from the data returned .. it is possible to do it please ? thank you ..

A:

You need to use the render property:
"render": function ( data, type, full) {
            return "<button type='button' class='btn btn-success' data-id=" + full[3] + ">PAY</button>";
    }

The full parameter is the full datasource for the data row, so you can access it by index.  In your case you would use full[0] as it's in the first position.
Here is a working example which uses different data, but you should be able to see how it works.


Q:

Gembox Spreadsheet C#: It is a way to detect if a cell has border?

As we know, in Gembox Spreadsheet, you can set a border (with C# language) for a cell like:
worksheet.Cells[row, 2].Style.Borders.SetBorders(MultipleBorders.All, Color.FromArgb(252, 1, 1), LineStyle.Thin);

It is a way to check if a cell contains border (bottom or top border) ?
Update
I found the solution with Gembox support:
var hasLeftBorder = cell.Style.Borders[IndividualBorder.Left].LineStyle != LineStyle.None;

A:

Have a look on the Gembox Spreadsheet documentation page for the CellBorder class. There are 2 properties on the CellBorder class: LineColor & LineStyle -  use the getter property of the LineStyle and compare it to a LineStyle enumeration


Q:

Avoid Cartesian Product in SQL when using Where in clause

My query goes below
 select a.col1,a.col2,b.col1,b.col2 from table1 a, table2 b
 where a.col3=value and b.col2 in (select col from table1 where col3=val)

This is giving be repeated values
Eg.
Result obtained
-----------------------
S.No| Name| Value| Code
------------------------
1| Delhi| capital| 100
------------------------
2 |Mumbai| city | 101
------------------------
1 |Delhi| city| 101
------------------------
2 |Mumbai| capital |100
------------------------

Expected Result
 -----------------------
S.No| Name| Value| Code
------------------------
1 |Delhi| capital |100
----------------------
2 |Mumbai| city |101
----------------------

I tried Group by it is not working. How could this be solved?
Sample Data
Table 1
------------------------
S.NO| Name |Type |Value

1| Delhi |BIGCITY| Capital
-------------------------
2| Mumbai| BIGCITY| City
------------------------

Table 2
---------------
Value |Code
---------------
Capital |100
---------------
City |101
--------------

  select a.sno,a.name,b.value,b.code from table1 a, table2 b
    where a.type=BIGCITY and b.col2 in (select value from table1 where col3=BIGCITY)

A:

Try this basic join query:
SELECT a.sno,
       a.name,
       COALESCE(b.value, 'NA') AS value,
       COALESCE(b.code, 'NA') AS code
FROM table1 a
LEFT JOIN table2 b
    ON a.value = b.value
WHERE a.type = 'BIGCITY'

Demo here:
SQLFiddle


Q:

Map Support in Shell Scripting

I am new in Shell Scripting, however i am friendly with Java Maps. I Just wanted to know that how can i use Map facility in Shell Scripting. Below is the facility i need to use in shell-
    HashMap<String, ArrayList<String>> users = new HashMap<String, ArrayList<String>>();

    String username = "test_user1";
    String address = "test_user1_address";
    String emailId = "test_user1_emailId";

    ArrayList<String> values = new ArrayList<String>();
    values.add(address);
    values.add(emailId);

    users.put(username, values);

    String anotherUser = "test_user2";

    if (users.containsKey(anotherUser)) {
        System.out.println("Do some stuff here");
    }

In short, i want to use a Map, which has String as key, either Vector or ArrayList as value (otherwise i have live with Arrays instead of ArrayList and manually take care of indexes) , put method to insert and one more method to check the presence of the key in the existing Map.
The above code is a sample code.
Thank you in advance.

A:

bash does not support nested structures like this. Either use separate variables for each array, or use something more capable such as Python.


Q:

Convert unix timestamp to normal Date in Json

I am using laravel 5.0. I am getting data from controller as json. I am having value like this.
{"timstamp_date":"1434360957"},

I need to convert this unix timestamp value as Normal Date Like (15-06-2015) or (15-March-2015).
I have used Date(timstamp_date) but it is showing current time only. Not my timstamp date

A:

You could use:
date("d-m-Y H:i:s", 1434360957);

EDIT
You could try;
var dateTime = new Date(1434360957*1000);
var formatted = dateTime.toGMTString();

https://jsfiddle.net/sp57Lnpf/


Q:

Manage domain name purchased through azure

I purchased a custom domain name through Azure, and it was correctly pointing to my Web App, and it was working. I subsequently deleted and recreated the Web app, and the underlying IP has changed. In order to associate the same domain name with the replacement app, Azure requires the CNAME to be set by the DNS provider. However, Azure is the DNS provider, and I can find no way to do this. I see lots of articles discussing how to manage the domain name once it is associated with the app, but not how do to manage it the gap between creation and association, which is the gap where I need to add the CNAME.

A:

The problem occurs because the subscription was changed from a pay-as-you-go subscription to developer benefits subscription. The purchase of the domain name is tied to the subscription with it was purchased. Creating the App under the original subscription enables the management blade.


Q:

Performance on denormalized field vs. use of separate collection

I'm looking at keeping track of scores/points per user. From examples I've seen, it seems normal to just keep track of a total count of something in a field. However, I'm concerned about being able to backtrack or keep track of the scores/points given to the user in case of cheating. Here's what I've got in mind:
Meteor.User Collection:
Meteor.user.profile: {
    ...
    totalScore: 0
    ...
}

Scenario 1:
Just add total score and keep track of it per user:
updateScore() {
       var currentUser = Meteor.user();

       currentUser.profile.update({ _id: this._id }{$inc: { totalScore: 1} });
}

Scenario 1:
Put score into separate Collection first to log it, before adding to total score of user:
Scores Collection:
Scores: {
    playerId: ,
    score: ,
    ...
}

updateScore() {
       var currentUser = Meteor.user();
       Scores.insert({ playerId: this._id, score: 1, ...});
       currentUser.profile.update({ _id: this._id }{$inc: { totalScore: 1} });

       //if not the above, then thisor this

       var currentUserScore = Calculate total score count from Scores collection of current user here
       Meteor.user.profile.update({ _id: this._id }{$set: { totalScore: currentUserScore} });

}

So what I'd like to know is, does Scenario 2 make sense vs. Scenario 1? And if Scenario 2 makes sense, if I calculate for the total score via the variable currentUserScore then use that to update the user's totalScore profile field (this runs every time the score needs to be updated), will this be detrimental to the app's performance?

A:

Based on our discussion, Scenario 2 makes the most sense to me, especially given that the score history may have value outside of auditing the total. Keep in mind it's always easier to remove data than it is to create it, so even if the history doesn't prove useful there is no harm in removing the collection sometime later.
I would implement an addScore method like this:
Meteor.methods({
  addScore: function(score) {
    check(score, Number);

    Meteor.users.update(this.userId, {
      $inc: {'profile.totalScore': score}
    });

    Scores.insert({
      playerId: this.userId,
      score: score,
      createdAt: new Date()
    });
  }
});

Unless you can think of a compelling reason to do so, I suspect the db/computation overhead of aggregating the totalScore each time would not be worthwile. Doing so only fixes the case where a user cheated by updating her profile directly. You can solve that by adding the following:
Meteor.users.deny({
  update: function() {
    return true;
  }
});

I'd recommend adding the above regardless of the solution you go with as user profiles can be updated directly by the user even if insecure has been removed. See this section of the docs for more details.
Finally, if you want to audit the totalScore for each user you can aggregate the totals as part of a nightly process rather than each time a new score is added. You can do this on the server by fetching the Scores documents, or directly in mongodb with aggregation. Note the latter would require you to use a process outside of meteor (my understanding is that the aggregation packages for meteor don't currently work but you may want to research that yourself).


Q:

How to find the difference between 3 lists that may have duplicate numbers

I have 3 lists and I want to find the difference between the 1st/2nd and 2nd/3rd
and print them.
Here is my code:
n1 = [1,1,1,2,3]
n2 = [1,1,1,2] # Here the 3 is not found ("3" is not present in n1 at all)
n3 = [1,1,2]   # here 1 is not found (there are fewer "1"s in n3 than in n2)
for x in n1:
   if x not in n2:
      print x
for m in n2:
   if m not in n3:
      print m

but i get only 3 as output.
How to make it output 1 and 3? I tried using sets as well, but it only printed 3 again.

A:

Since you seem to care about the number of times an item is found in both lists, you need to either remove matched items from the list you're comparing with:
comp = n2[:]  # make a copy
for x in n1:
    if x not in comp:
        print x
    else:
        comp.remove(x)
# output: 3

or use a collections.Counter
from collections import Counter
print Counter(n1) - Counter(n2)
# output: Counter({3: 1})

which tells you which items in n1 are not in n2 or can be found more often in n1 than in n2.
So, for example:
>>> Counter([1,2,2,2,3]) - Counter([1,2])
Counter({2: 2, 3: 1})


Q:

Python flask upload base64 image

I'm trying to create crop and resize tool in JS (use cropit) and Python(Flask)
Cropit returned base64 of cropped image, i sending it via AJAX to server, but can't save it.
Ajax:
$.ajax({
                type: 'GET',
                url: '/api/saver',
                data: 'file=' + imageData,
                enctype: 'multipart/form-data',
                processData: false,  // Important!
                contentType: 'application/json;charset=UTF-8',
                cache: false,
                success: function(msg){
                    console.log('Done')
                }
            });

On the server side
@app.route('/api/saver/', methods=['GET', 'POST'])
def api_save_base64_image():
    if request.method == 'GET':
        file = request.args.get('file')
        starter = file.find(',')
        image_data = file[starter+1:]
        image_data = bytes(image_data, encoding="ascii")
        with open('.../image.jpg', 'wb') as fh:
            fh.write(base64.decodebytes(image_data))
        return 'ok'
    return 'error

Returned without exceptions, but image.jpg is broken (empty).
How i can save images from client side via Flask?

A:

It's kind of tricky :) but cropit export image as png

data:image/png

So if you change your code to this, It's works :)
with open('image.png', 'wb') as fh:
    fh.write(base64.decodebytes(image_data))

For change format you can do this:
import base64
from io import BytesIO
from PIL import Image

...

        image_data = bytes(image_data, encoding="ascii")
        im = Image.open(BytesIO(base64.b64decode(image_data)))
        im.save('image.jpg')

...

You can find this code with data in image_stof.py


Q:

What exactly is Excel's Auto Fill algorithm?

What is the algorithm used by Auto Fill in Excel?
For example, when I enter the numbers 3,4,5,7,8 into a column and then use Auto Fill, I get the following result:
 3
 4
 5
 7
 8
 9.3
10.6
11.9
13.2
14.5
15.8
17.1
18.4

A:

Excel uses its Linear Trend approach when you auto-fill. This employs the least-squares method algorithm.
This is the same algorithm used by the TREND() function as seen demonstrated below:

Enter the following formula in C6 and ctrl-enter/copy-paste/fill-down into the rest of the column:
=TREND($C$1:$C$5,$B$1:$B$5,B6)

Below is a chart showing the trend line that the new values fall on.
The least-squares method creates a "best fit" line for the original data points. The new data points are essentially extracted from this line.


Q:

xcode project-/target-settings-syntax for linker flag force_load on iPhone

I am confronted with the double bind. On the one hand, for one of the 3rd party static libraries my iPhone application uses, the linker flag -all_load has to be set in the application project or target settings. Otherwise, the app crashes at run-time not finding some symbols called internally from the lib. On the other hand, for another 3rd party static lib, -all_load must not be set on application level, or the app won't build thanks to a "duplicate symbols" linker error.
To solve this issue, I now want to use force_load instead of load_all, as it due to documentation it does the same like all_load, but only for the passed path or lib-file, instead of all libs.
The problem with force_load is, I do not have a clue how to pass a path or file as parameter with it, when passing it via XCode project- or target-settings. All syntax-possibilities I tried either lead xcode to thinking it's another linker flag instead of a parameter to the previous one, or the linker throwing syntax related errors, or the flag simply does nothing at all.
I also opened the .pbxproj-file in a text-editor to edit it to the correct command line syntax manually. But when reloading the project with XCode, it auto-changes the syntax into interpreting the parameter to force_load as a separate flag.
Anyone have an idea on this issue?

A:

I just tried this.  I've compiled a static armv6, armv7, and i386 fat binary of PCRE for use in my iPhone project.  My project normally just has my library added to the project and that links fine.  So I unchecked the target membership box for libpcre.a and rebuilt.  As expected, I get a bunch of missing symbol linker errors for the pcre symbols.  Then I opened the target settings window and edited the "Other Linker Flags" section.  I added:
-force_load lib/pcre/libpcre.a

The lib directory is in the same directory as my project.xcodeproj file.
It linked fine so I know the force_load command worked (and I can see it added to the build flags when xcode builds the file).
Hope that helps.
Update:
I also tried adding a system library to the "Other Linker Flags" line like so:
-force_load src/pcre/libpcre.a -force_load ${SDKROOT}/usr/lib/libz.dylib

That worked too.


Q:

Use custom route upon model validation failure

I've just added a contact form to my Rails application so that site visitors can send me a message. The application has a Message resource and I've defined this custom route to make the URL nicer and more obvious:
map.contact '/contact', :controller => 'messages', :action => 'new'

How can I keep the URL as /contact when the model fails validation? At the moment the URL changes to /messages upon validation failure.
This is the create method in my messages_controller:
def create
  @message = Message.new(params[:message])

  if @message.save
    flash[:notice] = 'Thanks for your message etc...'
    redirect_to contact_path
  else
    render 'new', :layout => 'contact'
  end
end

Thanks in advance.

A:

One solution would be to make two conditional routes with the following code:
map.contact 'contact', :controller => 'messages', :action => 'new', :conditions => { :method => :get }
map.connect 'contact', :controller => 'messages', :action => 'create', :conditions => { :method => :post } # Notice we are using 'connect' here, not 'contact'! See bottom of answer for explanation

This will make all get request (direct requests etc.) use the 'new' action, and the post request the 'create' action. (There are two other types of requests: put and delete, but these are irrelevant here.)
Now, in the form where you are creating the message object change
<%= form_for @message do |f| %>

to
<%= form_for @message, :url => contact_url do |f| %>

(The form helper will automatically choose the post request type, because that is default when creating new objects.)
Should solve your troubles.
(This also won't cause the addressbar to flicker the other address. It never uses another address.)
.

Explanation why using connect is not a problem here
The map.name_of_route references JUST THE PATH. Therefore you don't need a new named route for the second route. You can use the original one, because the paths are the same. All the other options are used only when a new request reaches rails and it needs to know where to send it.

.
EDIT
If you think the extra routes make a bit of a mess (especially when you use it more often) you could create a special method to create them. This method isn't very beautiful (terrible variable names), but it should do the job.
def map.connect_different_actions_to_same_path(path, controller, request_types_with_actions) # Should really change the name...
  first = true # There first route should be a named route
  request_types_with_actions.each do |request, action|
    route_name = first ? path : 'connect'
    eval("map.#{route_name} '#{path}', :controller => '#{controller}', :action => '#{action}', :conditions => { :method => :#{request.to_s} }")
    first = false
  end
end

And then use it like this
map.connect_different_actions_to_same_path('contact', 'messages', {:get => 'new', :post => 'create'})

I prefer the original method though...


Q:

AJAX Response Text Empty

I'm creating a system that interacts with Minecraft server using AJAX. My JavaScript code is as follows:
function doMessage(name, message)
    {
        var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
document.getElementById("response").innerHTML=xmlhttp.responseText;
}

My PHP code is as follows:
<?php
header('content-type: text/plain');

echo "OmniCraft/Api/RequestHTTP";

if($_GET['message'] == "" or ctype_space($_GET['message']) or $_GET['user'] == "" or ctype_space($_GET['user']))
{

    echo "\nOmniCraft/Api/Request/Failed";
    echo "\nRequest invalid: No message specified";
    exit;
}

include_once '../MinecraftQuery.class.php';

    $Query = new MinecraftQuery( );

    try
    {
        $Query->Connect( 'localhost', 25565 );

    $info = $Query->GetInfo( );

    }
    catch( MinecraftQueryException $e )
    {
        echo "\nOmniCraft/Api/Request/Failed";
    echo "\nServer not online";
    exit;
    }

include_once("rcon.class.php"); //Include this file
$r = new rcon("127.0.0.1",25575,"notRealPasswordHere"); //create rcon object for server on the rcon port with a specific password
if($r->Auth()) //Connect and attempt to authenticate
{
$message = $_GET['message'];
$user = $_GET['user'];
$r->rconCommand("/tellraw @a {'text':'<$user using OmniMessage> $message','color':'white'}"); //send a command
echo "\nOmniCraft/Api/Request/Success";
echo "\nMessage sent successfully!";
}
else
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nUnable to authenticate to RCON";
exit;
}

?>

My form is as follows:
<form >

    <input type="text" placeholder="Message" style="padding: 20px 28px;font-size: 25px;" required="true" name="message">

    <input type="text" placeholder="Name" style="padding: 20px 28px;font-size: 25px;" required="true" name="name">

    <button class="btn btn-large btn-success" type="button" onclick="doMessage(this.form.name.value, this.form.message.value)">Send</button>

< using OmniMessage>

The AJAX query executes well, except for the fact that the responseText variable seems to not contain the response text (i.e. the DIV with the id 'response' remains empty after the query is complete).
The correct contents of the response DIV should be:
OmniCraft/Api/RequestHTTP
OmniCraft/Api/Request/Success
Message sent successfully!

However, this is not the case. What am I doing wrong?
EDIT: More Info:
I get the following error:
[20:14:21.855] NS_ERROR_FAILURE: Failure @ http://omnicraft.duncan.usr.sh/omnimessage/:154
Line 154 is: xmlhttp.send();
(or maybe document.getElementById("response").innerHTML=xmlhttp.responseText;

A:

Try this
You haven't handled  onreadystatechange
function doMessage(name, message) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
 xmlhttp.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("response").innerHTML=xmlhttp.responseText;
    }
  }
}


Q:

Nulling out final variable

Why is the following code possible? (Just an example I just came up with while working on other code)
public String getLogIdentifierFromFile(final File file) {
    //this.file = null; //Gives compiler error as obviously expected
    nullify(file);
    return "";
}

public void nullify(Object object) {
    object = null;
}

And how can I ensure that the final from the top function actually has an effect? This time it is me making the nullify method, but it can also be anyone's code that my method needs to call.

A:

The code doesn't do what you think it does.
final applies to the reference. Your code nulls out a non-final copy of the original final reference. The copy is taken when you call nullify().
If you examine file after calling nullify(), you will observe that it remains unchanged.
Thus, this isn't a loophole in how final works.


Q:

Using Chrome with `--headless` switch to measure user page load times

I'm trying to improve the performances of my web server and would like to get an accurate measure on how long it takes the user to load the page. The way I imagined this would be to simulate concurrent requests from users and track how page load times change as I fine-tune various settings to get optimal results.
I'd like to use the latest snapshot of Chromium with the --headless switch to measure how long it would take the user to load the page, but since this is a relatively new feature and I'm not familar with all the possible switches, I'd appreciate if someone can share what they would run to get accurate results.
The only limitation I have is that I can't inject scripts or modify the response content in some other way that would be helpful for such a test.

A:

This seems to be ok-ish. Taking a screenshot shows the page seems to be loaded and getting similar results between the first and subsequent requests, so I'm assuming caching is indeed disabled.
time chromium \
  --headless \
  --disk-cache-dir=/dev/null \
  --disable-gpu \
  --download-whole-document \
  --deterministic-fetch \
  https://www.stackoverflow.com

Notes

this doesn't warm up the DNS entries on the initial request, so it'd probably be best to discard the first result
the --disable-gpu flag isn't necessary, but there is a reported error with the current build
opening up a remote debugging port could probably be useful to remove references to 3rd party sources that skew results or to have more control over what's considered a fully loaded page, say wait for some scripts to fetch additional resources, but it's a bit way over my head


Q:

how to rewrite media folders using htaccess

I'm trying to redirect
/media/subfolder/filename to index
the subfolders are named like 12345 or 54321 and i'd like NOT to redirect subfolders that does not have this name structure.
how could i do this?

A:

So something like this?
RedirectMatch ^/media/[0-9]+/.+ /index.html

Assuming by "index" you mean "/index.html"


Q:

Failed to insert the data using python.mysql connector

I'm new to using MySQL connector for python and I have the below-given data to be inserted into a table called "region_based_billings". I tried all possible ways to insert this data and it seems I missing a syntax not sure exactly where and for which data type? .
   date  = '2016-06-29'
   region = 'Asia Pacific'
   account_type = 'PRODUCTION ACCOUNT'
   product_type  = 'AmazonEC2'
   total= 10.58383305
   count = 21

   cursor = self.testdb.cursor()
   cursor.execute('INSERT INTO iaas.region_based_billing (date, region, account type, product type, total amount, no of products) VALUES (%s, %s, %s, %s, %s, %s)',(date, region, account_type,product_type,total,count) )

    self.testdb.commit()
    self.testdb.close()

My table objects are :
 desc  iaas.region_based_billing;

    date                   date   NO           PRI
    region                 varchar(50)  NO
    account type           varchar(65)  NO
    product type           varchar(65)  NO
    total amount           float    NO
    no of products         int(255) NO

I know it's pretty basic, not sure what exactly causing the problem. I tried keeping single quotes for date type '%s', but still it didn't work.
Also here is the error
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type, product type, total amount, no of products) VALUES ('2016-06-29', 'Asia Pa' at line 1

A:

Remove space between column names. column name should be a single word or words seprated by _.
In your case column name have gap. So these column should be:-
account type = account_type
product type = product_type

and so on...


Q:

How to make navigation bar transparent optimize press

i am working with wordpress, using optimize press plugin. i am trying to make my the bar at the top where the navigation is white become transparent.
What i tried initially was to change the colour of the bar to transparent using
 .banner {
        padding: 2px 0;
    background-color: transparent;

}

it works but not completely, as the bar falls back to the colour of the background which is white so its not yet 100% transparent.
i am thinking of detaching the bar and placing it on the background image below its o it will be transparent over the background image.
but no idea on how to do this, can some one help.
i jst neeed to get the bar at the top to be transparent
the site in question for reference
Ref site

A:

i think you are looking for this
.banner {
    padding: 2px 0;
    background: transparent;
    position: absolute;
    left: 0;
    right: 0;
}


Q:

Add the Autoincrement _id column

Hey i made a whole app without adding an autoincrement column but now i need this column to specify the max id so i created my database in my mainactivity like this.How can i modify this to add the autoincrement _id column ?
 db = getActivity().openOrCreateDatabase("testDB2", Context.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS test2(mac VARCHAR,mdp VARCHAR,obj VARCHAR);");

I don't want to create a seonc java classs only for the database because i did all the code like this.

A:

db.execSQL("CREATE TABLE IF NOT EXISTS test2(autoincrement_id INTERGER PRIMARY KEY AUTOINCREMENT,mac VARCHAR,mdp VARCHAR,obj VARCHAR);");
only primary key can be autoincrement


Q:

What is this Font?

I ran the below image through What the Font without any luck. Can someone help me identify what font this is, or a very close substitute? Note: The effect on the font may be the font or may be styling. I can replicate the styling if I can get the font correct.

A:

I was finally able to speak to the graphic artist who created the text.
The font is VTKS Desgaste


Q:

Draw randomly from array without laying back

I would like to draw from an array randomly without having the drawn value in my initial array. So basically after each iteration the array shrinks um 1 value.
I have implemented the random draw part. However I struggle with the "laying back part".

const arr = [{
    name: 'Company1',
    symbol: 'C1',
  },
  {
    name: 'Company2',
    symbol: 'C2',
  },
  {
    name: 'Company3',
    symbol: 'C3',
  },
  {
    name: 'Company4',
    symbol: 'C4',
  },
]

for (let i = 0; i < arr.length; i++) {
  const value = arr[Math.floor(Math.random() * arr.length)]
  console.log(`${i} draw: ${JSON.stringify(value)}`)
}

Any suggestions how to implement the without laying back part.

A:

Javascript's Splice is a great function to achieve this.
Since you've already done the "random" part, we just need to extract the element from the array, instead of just printing it.
We can use splice to say: companies.splice(randomPosition, 1)[0], which is basically:

Remove one element after randomPosition from companies.
This will return an array with removed elements, so we use [0] to get the first one from splice return.

This would result on something like this:

const companies = [
  { name: 'Company 1', symbol: 'C1' },
  { name: 'Company 2', symbol: 'C2' },
  { name: 'Company 3', symbol: 'C3' },
  { name: 'Company 4', symbol: 'C4' },
]

while (companies.length > 0) {
  const randomPosition = Math.floor(Math.random() * companies.length)
  const removedElement = companies.splice(randomPosition, 1)[0]

  console.log(removedElement)
}

console.log('companies is empty: ', companies)

PS: It's a bad practice to modify an array inside a for that is evaluating its length each iteration, so I changed it for a simplified loop.


Q:

Format the LaTeX code of an array

Is there any editor that can nicely format the LaTeX code for an array? By nicely format I mostly have in mind aligning the &, as in the examples below:

Example 1:
\begin{array}{lcl}
z & = & a \\
& = & a \\
f(x,y,z) & = & x + y + z
\end{array}

could be formatted to:
\begin{array}{lcl}
z        & = & a         \\
         & = & a         \\
f(x,y,z) & = & x + y + z
\end{array}

Example 2:
\begin{bmatrix*}[r]
  {1}&{ 2}  &{ \mathbf M}  \\
  {48941} & {-3} &  { \mathbf M}  \\
  {11} & { 6}  & {-\mathbf M}
\end{bmatrix*}

could be formatted to:
\begin{bmatrix*}[r]
  {1} & { 2}  & { \mathbf M}  \\
  {1} & {-3}  & { \mathbf M}  \\
  {1} & { 6}  & {-\mathbf M}
\end{bmatrix*}

A:

Independent of the editor being used, we have latexindent by Chris (cmhughes). This should do a good job in beautifying the latex code by indenting everything.
On the other hand there is a Align Columns option in texstudio (which a cousin of texmaker) where you select
1 &  2  &  \mathbf M  \\
1 & -3  &  \mathbf M  \\
1 &  6  & -\mathbf M

and then click the tab to align them.

Aside there is no need to enclose the entries within braces since the entries are already inside a group here.


Q:

Sending data to different tables according to variable value

I have a table called "wifi" and another table called "bluetooth" on my mysql database
 I have a $string from a form
if the string contains "wifi" I want to set the $tbl_name= to "wifi" ,
else set it to "bluetooth"
then send the data to the appropriate table
I havent found any example, am I doing the right thing ? Yes, I'm new :)
I'm doing this:
$xplatform=$_POST['platform'];
echo "made_variables ok";
// Insert data into mysql
//ifstatement decides which table to insert into
if(preg_match('/wifi/',$xplatform))
{
$tbl_name='wifi';
}
else
{
$tbl_name='bluetooth';
};
$sql="INSERT INTO $tbl_name`(`field1`,`field2`,`f3`)
VALUES('$_POST[numberlat]','$_POST[numberlng]','$_POST[name]','$_POST[website]','$_POST
[message]','$_POST[radius]','$_POST[email]','$_POST[platform]')";
$result=mysql_query($sql);

A:

Use this:
if($_POST['string'] == 'wifi') {
  $tbl_name = 'wifi';
} else {
  $tbl_name = 'bluetooth';
}

Use that instead of preg_match() because the preg functions in PHP are very expensive.


Q:

Restar días a fecha datetime (SQL y PHP)

Quiero que me muestre una serie de solicitudes de la base de datos y el usuario tiene que introducir de hace cuántos días quiere el informe (X días).
El problema que tengo es que me resta bien las fechas, pero si no coinciden las horas no saca resultados. Me gustaría que descarte las horas y solo se quede con la fecha, pero no sé cómo modificar lo que ya tengo...
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND s.fecha = DATE_SUB(CURDATE(), INTERVAL '".$numDias."' DAY))");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}

¿Cómo resto X días a una fecha de la base de datos y que solo tenga en cuenta la fecha pero no las horas?

A:

El Problema es que estas comparando una fecha con marca de tiempo y otra sin marca de tiempo para poder realizar tu cunsulta correctamente debes eliminar la marca de tiempo de ambas fechas, ya que DATE_SUB(CURDATE() es '2017-10-19' s.fecha debe tener el mismo formato.
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND DATE(s.fecha) = DATE_SUB(CURDATE(), INTERVAL '".$numDias."' DAY))");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}

También puedes usar la funcion DATEDIFF() que solo compara las dos fecha y devuelve el resultado en días.
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND DATEDIFF(s.fecha ,CURDATE()) = 1)");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}


Q:

How to scan tokens only within context using Flex?

I want to create a parser of template engine using Flex & Bison. The thing is that I would like to parse only expressions within {{..}} and ${..}.
The template can be any arbitrary text with embedded tokens with code like this:
        </table:table-row>
        {{$(/report/row.xml).embed()}}
        {{$(//Accreditation/AccreditationDocument/Report).each(fragment(row) """
            <table:row>
                <table:table-cell office:value-type="string" office:string-value="${row["name"]}" />
            </table:row>
        """)}}
        <table:table-row table:number-rows-repeated="1048574" table:style-name="ro1">
            <table:table-cell table:number-columns-repeated="16384"/>
        </table:table-row>
    </table:table>

A:

I have found the solution myself. Flex has a feature called Start Conditions.
Below is the lexer.l code which returns tokens only from {{ }}. Other text is returned as GENERAL_BODY.
%{
#include "bisondef.h"
%}

%option reentrant noyywrap never-interactive nounistd
%option bison-bridge

WS [ \t\n]+
ID [A-z_][[:alnum:]]*

%x stmt

%%
    int stmt_level = 0;

"{{"    { stmt_level = 0; BEGIN(stmt); }

<stmt>{
    "{{"    { stmt_level++; printf("stmt {{\n"); }
    "}}"    {
        if (0 == stmt_level) BEGIN(INITIAL);
        else stmt_level--;
    }
    {WS}    {}
    [0-9]+  { yylval->num = atoi(yytext); return NUM; }
    "+"|"-"|"*"|"/"|"("|")" { return *yytext; }
    ";"     { return SEMICOLON; }
    {ID}    { yylval->str = strdup(yytext); return ID; }
}

.  {
    yylval->str = strdup(yytext);
    return GENERAL_BODY;
}

%%

int yyerror(const char *msg) { fprintf(stderr,"Error: %s\n",msg); return 0; }


Q:

How to make all the files in a folder non-executable in Windows 7?

I'm developing an application that deals with viruses. All these viruses are in a folder, it should be possible to read them and add new ones to the folder, however I'd like to make sure that none of them can be executed.
At the moment, I've already removed the file extension but if I could make them non-executable that would be even better.
Is it possible to do this with Windows 7?

A:

Open an elevated command prompt and run:
icacls C:\myViruses /deny "Everyone:(OI)(IO)(X)"

This will deny everybody the permission to execute files while users can add and delete files.
You should test this in your environment.
If you have an active virus on the system with sufficient privileges, it can undo this change, but in this case all is lost anyways.


Q:

How to group objects from MongoDB collection

I have document collections like these
{ "owner": "550511223", "file_name": "55234OT01", "file_type": "other", "comment": "Just fix it"},
{ "owner": "550510584", "file_name": "55584RS01", "file_type": "resume", "comment": "Good enough"},
{ "owner": "550511223", "file_name": "55234AP01", "file_type": "applicant", "comment": "This will do"}

I need a result as an object like this
{
 [{
  "owner" : "550510584",
  "files" : [{"file_name": "55584RS01","file_type": "resume","comment": "Good enough"}],
 },{
  "owner" : "550511234",
  "files" : [{"file_name": "55234AP01","file_type": "applicant","comment": "This will do"},
             {"file_name": "55234OT01","file_type": "other","comment": "Just fix it"}]
 }]
}

I'm finding a way to do this. I've try group and aggregate but I can only push file_name field in because I mess up with syntax

A:

You need to $group your document by "owner" then use the $push accumulator operator to return array of files.
db.collection.aggregate([
    { "$group": {
        "_id": "$owner",
        "files": {
            "$push": {
                "file_name": "$file_name",
                "file_type": "$file_type",
                "comment": "$comment"
            }
         }
    } }
])

Which returns:
{
  "_id" : "550510584",
  "files" : [
          {
                  "file_name" : "55584RS01",
                  "file_type" : "resume",
                  "comment" : "Good enough"
          }
  ]
},

{
  "_id" : "550511223",
  "files" : [
          {
                  "file_name" : "55234OT01",
                  "file_type" : "other",
                  "comment" : "Just fix it"
          },
          {
                  "file_name" : "55234AP01",
                  "file_type" : "applicant",
                  "comment" : "This will do"
          }
  ]
}


Q:

Installing Sql server 2016 doesn't add sql services

I install sql server 2016, sql server 2016 sp1 and it's ssms. but I cant to connect local server. I check services.msc but it contains no sql services like sql server agent , ...

A:

It solved by three steps :
1.Update Visual Studio Installer
2.Update Visual Studio(from VS 2017 build 15.0.0 to build 15.3.0)
3.Repair SQL Server again.
Services added correctly, every thing is fine now.


Q:

WP7: Is it possible to get a referrer from the installation page/link?

This question involves both programming and architectural subjects.
Firstly, sorry if it was asked previously, with other words or in another way. I just haven't found anything that matches with my issue.

Here we go. Supose that you have developed a WP app and uploaded it to Windows Store. Now supose you have a webpage named "any_dynamic_name_that_can_change.php" with a button that redirects you to your Windows Store app's page. And now, FROM THE APP (after you install it on your device), you want to know the page's name from where the Windows Store was accessed.

I've checked WP docummentations and I'm fully aware that WP SDK don't have any features that allow us to implement this behavior. In android SDK, one can make use of Referrer/BroadcastReceiver features to pass arguments through your page and Google Play. I've sussccesfuly made it in my Android's app version.

My question is: is there a solution to implement this "know-from" behavior? I don't care if it involves using third systems or saving arguments somewhere, or even if the solution is a "hard-to-do" task. I'm just looking for it, if it exists...
Any hints, comments and answers will be very welcome!
And sorry if my question wasn't well explained, or if it is too broad!

A:

Unfortunately the Windows Phone Store does not provide this and has no way of providing the information that would be needed to implement this either.
The nearest thing you could do would be to look at the IP address of requests to the pages with the links and the first request from the app. Obviously there are lots of reasons why this wouldn't be a perfect solution but it may be better than nothing.
The only other solution would involve the person viewing the page(s) and the app to provide a unique identifier such as their credentials.
An alternative approach would be to track clicks on the individual pages. It wouldn't be able to tell you conversions once the person gets to the store but it could tell you which pages were the greatest drivers of people to your apps in the store.


Q:

Erro ao invocar metodo Setter PHP com Interface!

Fala galera, tudo beleza?
Eu estou estudando Interfaces em PHP e estou tendo um erro ao invocar o método setter nos meus atributos.

<?php
session_start();
interface User {

public function userName($uName);
public function userEmail($uMail);
public function userPasswd($uPass);

}

class Cliente implements User{
private $userName;
private $userEmail;
private $userPasswd;

/**
 * Get the value of userName
 */
public function getUserName()
{
    return $this->userName;
}

/**
 * Set the value of userName
 *
 * @return  self
 */
public function setUserName($userName)
{
    $this->userName = $userName;

    return $this;
}

/**
 * Get the value of userEmail
 */
public function getUserEmail()
{
    return $this->userEmail;
}

/**
 * Set the value of userEmail
 *
 * @return  self
 */
public function setUserEmail($userEmail)
{
    $this->userEmail = $userEmail;

    return $this;
}

/**
 * Get the value of userPasswd
 */
public function getUserPasswd()
{
    return $this->userPasswd;
}

/**
 * Set the value of userPasswd
 *
 * @return  self
 */
public function setUserPasswd($userPasswd)
{
    $this->userPasswd = $userPasswd;

    return $this;
}

public function userName($uName)
{
    $this.setUserName($uName);
    echo    "
".
            "
Nome:".getUserName()."
";

}

public function userEmail($uMail)
{
    $this.setUserEmail($uMail);
    echo    "
".
            "
Email:".getUserEmail()."
";

}

public function userPasswd($uPass)
{

    $this.setUserPasswd($uPass);
    echo    "
".
            "
Email:".getUserPasswd()."
";

}

}

$usuario = new Cliente();

if(isset($_POST["name"])){
    $usuario->userName($_POST["name"]);
}

if(isset($_POST["email"])){
    $usuario->userEmail($_POST["email"]);
}

if(isset($_POST["passwd"])){
    $usuario->userPasswd($_POST["passwd"]);
}

?>

E o Erro:
Fatal error: Uncaught Error: Call to undefined function setUserName() in D:\Programacao\Xampp\htdocs\PHP7\interface\exe02.php:79 Stack trace: #0
D:\Programacao\Xampp\htdocs\PHP7\interface\exe02.php(109): Cliente->userName('Vitor') #1 {main} thrown in D:\Programacao\Xampp\htdocs\PHP7\interface\exe02.php on line 79

Não acho que o erro esteja relacionado com a Interface, mas não entendo ele retornar Undefined em um método existente e Public.
Os dados estão vindo de um form em outra pagina, acredito que seja irrelevante para o problema.
Desde já agradeço a atenção

A:

Seu script esta cheio de erros, primeiro:
$this.setUserEmail($uMail);

O $this em PHP usa -> e não ponto, deveria ser:
$this->setUserEmail($uMail);

Segundo, métodos da classe devem ser sempre acessadas via $this em caso de objetos e se forem estáticos com self:: (ou parent:: que neste caso seria equivalente ao super() em Java), isto:
"
Email:".getUserEmail()."
";

Deveria ser isto:
"
Email:".$this->getUserEmail()."
";

Em mais de um lugar do script tem estes 2 problemas, corrija todos eles e provavelmente vai funcionar.

Outro problema (que talvez seja um problema ou não, se você estiver usando buffer), session_start usa o header em HTTP para declarar os cookies, todo header de uma resposta HTTP (todo site é HTTP) envia os headers antes do corpo, mas no momento que você adicionou

Antes do session_start você estará forçando o PHP a enviar o corpo e o session_start não vai funcionar porque será impossivel enviar o header
Leia mais em:

Erro - "Cannot modify header information - headers already sent"


Q:

Python - Any way to avoid several if-statements inside each other in a for-loop?

I need a better way to do this. I'm  new with programming but I know that this is a very inefficient way of doing it and that I need a function for this, I just don't know how to do it exactly. any suggestions? I'm VERY grateful for any help!
for H in range(0,len(a_list)):
    if a_list[H] > list4[0]:
        list5 = [number_list[i]]
        if function(list1,list5) == list1[1]:
            if function(list2,list5)== list2[1]:
                if function(list3,list5)== list3[1]:
                    if function(list4,list5)== list4[1]:
                        list5.append(input('some input from the user'))
                        other_function(list5)
                        if list5[1]== 40:
                            print ('something something')
                            break out of EVERY loop
                         else:
                            for H in range(0,len(a_list)):
                                if a_list[H] > list5[0]:
                                    list6 = [number_list[i]]
                                    if function(list1,list6) == list1[1]:
                                        if function(list2,list6)== list2[1]:
                                            if function(list3,list6)== list3[1]:
                                               if function(list4,list6)== list4[1]:
                                                  if function(list5,list6)== list5[1]:
                                                     list6.append(input('some input from theuser'))
                                                     other_function(list6)
                                                         if list6[1]== 40:
                                                             print ('something something')
                                                                 break out of EVERY loop
                                                         else:
                                                            etc. (one extra comparison every time)

A:

Use the all() function to test multiple related conditions:
if all(function(lst, list5) == lst[1] for lst in (list1, list2, list3, list4)):

and
if all(function(lst, list6) == lst[1] for lst in (list1, list2, list3, list4, list5)):

Like the nested if statements, all() will short-circuit; return False as soon as any of the tests fails.
In addition, loop over lists directly, instead of generating a range of indices. If you are using break, you don't need to use else either, removing another level of indentation.
You can remove another level by filtering a_list:
for H in filter(lambda H: H > list4[0], a_list):

Together, this reduces your nesting to:
for H in filter(lambda H: H > list4[0], a_list):
    list5 = [number_list[i]]
    if all(function(lst, list5) == lst[1] for lst in (list1, list2, list3, list4)):
        list5.append(input('some input from the user'))
        other_function(list5)
        if list5[1]== 40:
            print ('something something')
            break # out of EVERY loop

        for J in filter(lambda J: J >list5[0], a_list):
            if all(function(lst, list6) == lst[1] for lst in (list1, list2, list3, list4, list5)):
            list6.append(input('some input from theuser'))
            other_function(list6)
            if list6[1]== 40:
                print ('something something')
                break # out of EVERY loop

            # continue here

Presumably your break statements actual use exceptions (raise CustomException() and try:, except CustomException:  # break out of all the loops fast), as a regular break would only stop the current loop.
If you are continuously adding further lists and nesting, you probably want use a list to hold all those nested lists, then simply add to the outer list:
class EndLoops(Exception): pass

stack = [[number_list[0]]]
try:
    for i in number_list[1:]:
        for H in filter(lambda H: H > stack[-1][0], a_list):
            stack.append([i])
            if all(function(lst, stack[-1]) == lst[1] for lst in stack[:-1]):
                stack[-1].append(input('some input from the user'))
                other_function(stack[-1])
                if stack[-1][1] == 40:
                    print ('something something')
                    raise EndLoops
except EndLoops:
    pass # broken out of outer loop

and suddenly all the nesting has gone; instead you moved the nesting to a stack list of lists.
Note that I don't know what the outer-most loop looks like in your code, I just took an educated stab in the dark at it, but the idea should be roughly correct.

A:

When you have three or more numbered and similarly-used variables, think lists.
With that in mind, we first change list1, list2, list3, ... into a list of lists (indexed 0,1,2,3 instead of 1,2,3,4). Except don't call it list, because that's a useful name for something that's already useful. lst is pretty popular in Python. I'm also going to change list5 into lstA and list6 into lstB because 5 and 6 no longer make sense.
Now we have this:
for H in range(0,len(a_list)):
    if a_list[H] > lst[3][0]:
        lstA = [number_list[i]]
        if function(lst[0],lstA) == lst[0][1]:
            if function(lst[1],lstA)== lst[1][1]:
                if function(lst[2],lstA)== lst[2][1]:
                    if function(lst[3],lstA)== lst[3][1]:
                        lstA.append(input('some input from the user'))
                        other_function(lstA)
                        if lstA[1]== 40:
                            print ('something something')
                            break out of EVERY loop
                         else:
                            for H in range(0,len(a_list)):
                                if a_list[H] > lstA[0]:
                                    lstB = [number_list[i]]
                                    if function(lst[0],lstB) == lst[0][1]:
                                        if function(lst[1],lstB)== lst[1][1]:
                                            if function(lst[2],lstB)== lst[2][1]:
                                               if function(lst[3],lstB)== lst[3][1]:
                                                  if function(lstA,lstB)== lstA[1]:
                                                     lstB.append(input('some input from theuser'))
                                                     other_function(lstB)
                                                         if lstB[1]== 40:
                                                             print ('something something')
                                                                 break out of EVERY loop
                                                         else:
                                                            etc. (one extra comparison every time)

Now it's more obvious that we're basically doing the same thing four times.

When you have to do the same thing a bunch of times, think loops.
We'll change the blocks into loops. We'll also use a flag variable to keep track of whether something failed while testing our logic, and use the logic "if it does not work, skip stuff" rather than "if it works, do stuff"
for H in range(0,len(a_list)):
    if a_list[H] > lst[3][0]:
        continue #reducing indent levels by negating the check:
                 #quit on failure instead of work on success

    lstA = [number_list[i]]

    quit = False

    for j in range(4):
        if function(lst[j],lstA) != lst[j][1]: #testing FALSEHOOD
            quit = True
            break #the j loop only

    if quit:
        continue #reducing indent levels by negating the check

    lstA.append(input('some input from the user'))
    other_function(lstA)
    if lstA[1]== 40:
        print ('something something')
        break #out of EVERY loop
    #else: #don't need the else because we broke

    for H in range(0,len(a_list)):
        if not a_list[H] > lstA[0]:
            continue #reducing indent levels by negating the check

        lstB = [number_list[i]]

        for j in range(4):
            if function(lst[j],lstB) != lst[j][1]: #testing FALSEHOOD
                quit = True;
                break #to the H loop
        if not quit and  function(lstA,lstB)== lstA[1]: #combining two checks
            lstB.append(input('some input from theuser'))
            other_function(lstB)
            if lstB[1]== 40:
                print ('something something')
                break #out of EVERY loop
            else: #at this point I'm lost and can't refactor
                etc. (one extra comparison every time)

When you have to break out of multiple loops at once, think functions and returning instead of breaking. Or exceptions and try blocks, but some might find that distasteful.
The failure flag works, but isn't very elegant. There's an exaggerated saying: "... if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." Read this as: If you have a lot of levels of indentation (and some languages require more than others), you should think about whether you can move some of the logic into a function.
We'll also move some repeated logic into a checker function.
(Finally, I think it's a bug that your second for-loop is nested in your first. Since they have the same iterator variable H, I think that would cause an infinite loop. So I fixed that.)
#returns FALSE if a check fails, unlike the `quit` variable
def checker(lst, lstA):
    for i in range(4):
        if function(lst[i],lstA) != lst[i][1]: #testing FALSEHOOD
            return False;
    return True;

def main(???):
    for H in range(0,len(a_list)):
        if a_list[H] > lst[3][0]:
            continue

        lstA = [number_list[i]]

        if not checker(lst,lstA):
            continue

        lstA.append(input('some input from the user'))
        other_function(lstA)
        if lstA[1]== 40:
            print ('something something')
            return #break out of EVERY loop

    for H in range(0,len(a_list)):
        if not a_list[H] > lstA[0]:
            continue

        lstB = [number_list[i]]

        if checker(lst,lstB) and  function(lstA,lstB) == lstA[1]:
            lstB.append(input('some input from theuser'))
            other_function(lstB)
            if lstB[1]== 40:
                print ('something something')
                return # break out of EVERY loop
            else: #at this point I'm lost and can't refactor
                etc. (one extra comparison every time)


Q:

How to bind a dynamic list of fields in a JSP

I am building a JSP page for entering football game results. I get a list of unsettled games and I want to list them like this:
team1 vs team4
    [hidden field: game id]
    [input field for home goals]
    [input field for away goals]

team2 vs team5
    [hidden field: game id]
    [input field for home goals]
    [input field for away goals]

I never know how many games will be listed. I am trying to figure out how to set up the binding so that the controller can access these fields after the form is submitted.
Can someone please guide me in the right direction. I am using Spring MVC 3.1

A:

Spring can bind indexed properties, so you need to create a list of game info objects on your command, like:
public class Command {
   private List<Game> games = new ArrayList<Game>();
   // setter, getter
}

public class Game {
   private int id;
   private int awayGoals;
   private int homeGoals;
   // setters, getters
}

In your controller:
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@ModelAttribute Command cmd) {
   // cmd.getGames() ....
   return "...";
}

In your JSP you will have to set the paths for the inputs like:
games[0].id
games[0].awayGoals
games[0].homeGoals

games[1].id
games[1].awayGoals
games[1].homeGoals

games[2].id
games[2].awayGoals
games[2].homeGoals
....

If I'm not mistaken, in Spring 3 the auto-growing collections is now the default behavior for binding lists, but for lower versions you had to use an AutoPopulatingList instead of just an ArrayList (just as a reference: Spring MVC and handling dynamic form data: The AutoPopulatingList).


Q:

How does “space weather” cause reaction wheel failure?

Failure of reaction wheels often causes premature mission ending or failure to achieve the goal because spacecrafts are no longer able to maintain orientation and have to rely on chemical propellants. The Hubble telescope, Hayabusa spacecraft, Kepler telescope, Dawn spacecraft etc. all faced reaction wheel failure.
Recently there was a study that “space weather” induces electrostatic discharge between steel ball bearings and causes surface defects which eventually compromise the whole mechanism. But for me it’s hard to believe that this is the only reason, because I doubt that spacecraft only use steel ball bearings when ceramic, especially silicon nitride, are superior and can even survive lubricant starvation. What about contactless magnetic bearings?
Can “space weather” have other effects on flywheels like damaging permanent magnets (demagnetization), electronics, lubrication instead of steel ball bearings?

A:

Ceramic bearings are a relatively new concept. They were a hot research topic in the late 1970s and didn't become commercially available until the mid 1990s.
The Far Ultraviolet Spectroscopic Explorer (FUSE), the first spacecraft on which these anomalous bearing failures were seen, was launched in 1999. It takes several years to multiple decades to design and build and test a satellite. That means FUSE not only was designed before ceramic bearings became commercially available, it means that construction on FUSE started before ceramic bearings became commercially available. There was zero chance that either NASA or its contractor would have wanted to switch from a very well known product (steel ball bearings) to an unknown product (ceramic ball bearings) at that time.
Even a decade later, which was when the Kepler Space Telescope was launched, there remained zero chance that either NASA or its contractor would have wanted to switch from steel ball bearings to ceramic ball bearings. The problems with steel ball bearings would not be known and attributed to the use of steel for another seven years after the launch of Kepler.
The space industry is inherently conservative. For items related to space exploration, one does not switch from a known quantity to something new just because the new thing is shinier. A very good reason is needed, and shininess doesn't count. Drastically reducing costs, markedly improving lifespan, or markedly approving mission success -- those are factors that do count.
Now there are solid signs that the problems experienced with reaction wheels on FUSE, Kepler, and other satellites were a result of the use of steel ball bearings. This known knowledge is now driving a switch away from steel ball bearings. That knowledge was not known until a few years ago.

A:

The study was specifically of ITHACO reaction-wheel assemblies that proved to be highly prone to failure in the space environment. These assemblies used steel bearings.
Interference with electronics is certainly possible, but would not be limited to reaction wheels. Demagnetization of permanent magnets would require such extreme conditions that it would be surprising if any of the electronics were left functional afterward, and would also affect things other than reaction wheels. I see no plausible way for the lubricant to be affected more directly than the mechanism proposed, and again, there are other mechanical components that depend on lubrication.
Reaction wheels are unique in that they spend much of their life running at relatively high speeds, and so can rapidly accumulate damage from the proposed mechanism, while slow and/or intermittently-moving mechanisms using similar bearings might avoid damage altogether or just not accumulate noticeable levels. Pretty much everything else about them...electronics, permanent magnets, lubrication, etc...is similar to other spacecraft components.
Finally, a lack of similar problems with a newer version that used ceramic bearings was specifically cited in the paper.


Q:

Pergola on flat roof: Can it be done safely?

I want to put a pergola on my flat roof but am not sure if it's possible to construct one safely. My roof is a wide open flat surface built to be  enjoyed as a rooftop deck with tufflex deck layer. I want to attach the posts directly to the roof (that seems the most secure) but I don't think that is possible due to compromising the integrity of the roofing layer (I assume it would require redoing the entire roof to create brackets that would be more properly sealed from leaking). On the other hand I'm not sure how to calculate if concrete blocks are enough to prevent it from flying away which would be catastrophic as it would fall 3 stories. Unfortunately there is no structure I can attach it to other than the ~4ft walls around the roof that are capped with a metal sheet.
Has anyone done this or do you have ideas on if it can be done safely? I was originally planning to just attach the pergola to concrete blocks but I'm worried about gusts of wind and have no insight on if this is safe or what amount of weight is needed to secure it. For the pergola frame I plan to use bamboo due to its light weight and strength: my idea is that the center of mass would be much lower using bamboo vs a traditional hardwood or even an aluminum frame. It would also put less load on the roof itself, but I sacrifice potential stability as cedar pergolas are 5x the weight I believe.
The roof looks like this:

In summary, is it possible to construct a pergola on a flat roof safely given my constraints (roofing material, no obvious part of the house to attach it to, etc)?
Edit: The roofing material is actually tufflex
Edit2: Added a more representative picture due to commentary

A:

Yes, I’ve done this, but it was designed into the roof. That is to say, we tied into roof beams with round steel pipes. The pipes were bolted into the roof beams and extended up through the roof about 12” or so. We caped the pipes so they didn’t leak and then used “plumbing jacks” (like ones made for plumbing vents,) to keep the roof from leaking. We then bolted cross beams to the pipes for the gazebo floor and kept the floor off the roof about 6” or so for drainage and cleaning. We then installed posts and a roof. (The structural system used bolts not just nails.)
Also, the roof beams were designed to hold the gazebo up, but it was also designed to hold it down (I live in a high wind area.) That means the beams need to be secured to posts and the posts need to be secured to the foundation adequately.
If you use your concrete block idea, be sure that the roof is designed to support that much additional weight. Remember, roofs are usually designed to just support snow loads not live loads with all your drunken friends celebrating your 30th birthday.
Wind factor increases the higher you go up. The effect of putting your gazebo on a three story structure means you’ll have significantly higher effects (lateral loads and uplift) of wind than one sitting on the ground.
BTW, if you’re creating a roof top gathering place, you’d better install a guardrail to keep your friends from wandering over to the edge and falling off. (Blood is difficult to get out of sidewalks.)


Q:

Get Image Height according to width in .load()

I need to get Image height and width before loading the Image itself. So I am using jquery .load() method.
$('<img />').attr('src',someURL).load(function(){
  console.log(this.width);
  console.log(this.height);
})

But problem is that I need the height according to the fix width. Suppose Image is of size 400*417, I need the height according to 200 not 400. For that I add
$('<img />').attr({
'src':someURL,
'width':200}).load(function(){
  //Get height and width
})

But Above code is again giving me height 417 not according to width of 200. I am looking for js/jquery/angualrjs. Please help.
Thanks In Advance :)

A:

A bit of math will do the trick. Once you get the actual image dimensions, apply your ratio to get the height you want.
For instance :
$('<img />').attr('src',someURL).load(function(){
  console.log(this.width); // prints out 400
  console.log(this.height); // prints out 417

  var widthIWant = 200;

  var heightIWant = this.height * widthIWant / this.width; // Gives you 208.5

})


Q:

Will cut and pasting from pdf to sublime text generate dirty code?

I'm studying css/html via a pdf workbook, and I'm wondering if it's ok to cut and paste code from this into my text editor (Sublime Text) or will this result in "dirty code"?

A:

You won't have 'dirty' code in the sense that you would if you pasted something into an editor that has a design view and was generating code. Sublime Text is only a text/code editor.
However, when cutting and pasting from PDFs you have to be especially careful about line breaks, columns, dashes at the end of lines etc. Especially true if your language cares about line breaks and indentations. (HTML/CSS is far more forgiving that others.)
But, you should be fine. Just pay attention to what the code looks like when you paste it, and clean up a bit if necessary.


Q:

Anyone tried to brush mud/snow in rear-wheel while on ride?

I ride my bike in the snow. And I think my bike can be a lot cleaner if I had a snow catcher in my rear-wheel.
There is possibility because the rear wheel fork comes with extra holes in it. I think we can hook a fork there to hold a brush at the back of the tire.
I think it will keep the gear and derailleur cleaner. I guess it will also reduce the skidding.

A:

I prefer not using anything in the snow to block the snow. You risk the snow packing in the snow blocker (e.g. fenders) and freezing, which can be dangerous. A brush against the tire (depending on the stiffness of the bristles) could also damage your tire.
If you want to use something, a seatpost fender and a downtube mudguard are probalby the safest options.
If you want to keep your bike clean in winter, good luck (especially if you ride on salted roads). The best course of action is to bring it in when you have time (e.g. 24 hours), clean the bike indoors, let it be completely dry then take it back out. Or, if theres a warm day, do a quick (light) wipe down and dry the bike off as you go. You could also try a stiff brush which may get rid of some of the salt.  Or just deal with a dirty bike, and clean it in the spring.

A:

I thought I've seen something like this before... so I googled a bit and found traces of this design, apparently deceased.

While it looks clever, I have some doubts that it will work efficiently for any real rain. As soon as the brush is "saturated" with water, incoming drops will cause some of already collected water to detach and continue its way up.
It will definitely not work for snow, the reason being the snow is hard not liquid. I had my rear wheel fully blocked many times when a build-up of snow formed in the chainstay-seattube-bottom bracket area of my bikes. Even a rear fender placed too low once caused such snow accumulation resulting in inability to rotate the rear wheel. Placing another hinder somewhere can only shift the position of such build-up or even provoke it.
Maybe some oil on tires might help to repel snow sticking to the tire, but obviously the same oil will hurt your braking capabilities to the extent that it will be safer to leave the bike home. However, you may try to use some bike  polish on the frame and on the drivetrain parts. It is told to help with preventing mud sticking to the frame; however, I used it and did not notice any measurable effects.
Solutions that I consider to work are:

having another bicycle with a different braking system, preferably internal (say, drum) or even disk will work better;
wider clearance between tires and the frame — if you can move your rear wheel in the dropouts further back;
gnarlier tires, possibly spiked if you need to deal with plenty of ice; if not, just go with regular non-completely slick tires.
just dealing with the fact that riding in the winter has to be done more carefully and slowly;
just dealing with the fact that you will not be able to pass on your bike to your descendants; or maybe you actually will — bikes are survival tools and may last surprisingly long.


Q:

How to make a single combobox sortable?

I'm trying to make a single combobox sortable. Jquery UI documentation about sortables mentions, that sortable should be setup like this:
$( ".selector" ).sortable();

When I've put in the selector it made all my Select2 elements sortable:
$("ul.select2-selection__rendered").sortable()

I want to make it so only one element in specific div is sortable. I've tried copying CSS Selector path from my browser and got an error:
var outpatient = document.querySelectorAll('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)')[0];
outpatient.sortable({
  // ...
});

TypeError: outpatient.sortable is not a function

A:

The outpatient variable will hold an Element object as you use querySelectorAll() to retrieve it. sortable() relies on jQuery, and so needs to be called on a jQuery object. Therefore to fix this you can create a jQuery object from outpatient and then call sortable() on it:
var outpatient = document.querySelectorAll('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)')[0];
$(outpatient).sortable({
  // ...
});

Taking this a step further, use jQuery itself to select the element. Also note that I'm sure that you can simplify that selector. It seems far too specific.
var $outpatient = $('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)');
$outpatient.sortable({
  // ...
});


Q:

django-nvd3 does not show any graph

I'm still newbie to python 3.4 and django 1.7. I tried to draw a chart using django-nvd3. I tried to run something like:
class Report(TemplateView):
    def report_page(request):
        extra_serie = {}
        xdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        ydata = [3, 5, 7, 8, 3, 5, 3, 5, 7, 6, 3, 1]
        chartdata = {
            'x': xdata,
            'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie,
        }
        charttype = "lineChart"
        chartcontainer = 'linechart_container' # container name
        data = {
            'charttype': charttype,
            'chartdata': chartdata,
            'chartcontainer': chartcontainer,
            'extra': {
                'x_is_date': False,
                'x_axis_format': '',
                'tag_script_js': True,
                'jquery_on_ready': False,
            }
        }
        return render_to_response('Report.html', data)

where Report.html is as follows:

     {% load nvd3_tags %}

        {% include_container chartcontainer 400 600 %}

but no chart does appear. I read somewhere from areski that: "We use include the Javascript and CSS code for D3/NVD3." So I added these statements to my template:
<link href="{% static "nvd3-master/build/nv.d3.css" %}" rel="stylesheet" type="text/css" media="screen" />

but still no chart is drawn on my web page!
Here is the output HTML:

    <link href="/static/nvd3-master/build/nv.d3.css" rel="stylesheet" type="text/css" media="screen" />

    </script>

<svg style="width:600px;height:400px;"></svg>

A:

Thanks a lot from Areski Belaid (@areski) that helped me to find the issue. I changed:

to:
    {% load_chart charttype chartdata chartcontainer extra %}

And now it works. :))


Q:

trying to scan in to a 2-d malloc'd array c programming

i've looked through quite a few questions of 2-d malloc'd arrays already but bascially for whatever reason i cannot find a solution.... my google fu sux sorry =(. been using the site all day for syntactual help though thanks to everyone who helps here! =)
anyways i cant seem to get this fscanf to work =/ if someone could help me it would be much appreciated because i cant see any error at all but i know there is one because it is at this point that my program crashes.
    array1 = (int**)malloc((c)*sizeof(int*));
        int a = 0, i = 0;
        for (a = 0; a < c; a++){
            array1[a] = (int*)malloc((c+1)*sizeof(int));

        }
    a=0;

    for(a = 0; a < c; a++){
                for(i = 0; i < c; i++){
                fscanf(ifp, "%d", array1[a][i]);

    }
    }

where c is the maximum size of the array needed. in this case it is set to 3 but i do need it as a variable

A:

When using the scanf family of function to read a value, the destination needs to be a pointer. array1[a][i] is not a pointer, it an actual value (which scanf will treat as a pointer and you now entered the territory of undefined behavior).
What you want is &array1[a][i].
PS.
You should not cast the returned value of malloc.