text:
Q: Should I worry about PHP injection if I don't use MySQL? I use a simple PHP script to run an online comic which basically uses a GET to take an integer value n and insert an img tag for n.jpg. It doesn't do any sanitizing or error checking beyond making sure that n.jpg exists. The only user interaction with the script is through this GET, and another that does the same thing with a string to manually display a different template for testing.
My question is, should I even be worrying about injection? And if so, what should I do to prevent it? Everything I've found so far only concerns MySQL injection, which doesn't apply in this case.

A: If you're not using a database, then obviously SQL injection is not a concern for your. Similarly, if you don't store any user-submitted data to display to other users, Cross-site-scripting is not a concern. That leaves stuff like eval() or running external processes, which an attacker could subvert, but it doesn't sound like you do anything like that either.
So you're probably safe. Still, it would be good to have a minimum amount of error checking, just to get into the habit. For example, you say that you have an integer GET parameter. There's no such thing - all HTTP parameters are implicity strings. PHP blurs the distinction, but you definitely should cast it to int explicitly to make sure it's not some string intended to exploit an XSS, SQL injection or eval vulnerability (even if none such exist).

A: You should always worry about security. Not every security hole is made up by the wrong usage of mysql :-)

A: The SQL injection is not applicable in your case because you are not using a database for your site. But you should consider other security issues for your site too such as cross site scripting.
If you are using a variable from GET, consider below url:
 index.php?myvar=<script>alert(document.cookie);</script>

The hackers are able to provide above url in a number ways hex, utf, etc.
A bad guy can modify your GET variables to perform XSS attacks. XSS is the root of many security holes. You need to consider that too.
If you are expecting a numeric type from your GET var then consider below code:
$myvar = (int) $_GET['your_var'];

You should use htmlentities function to prevent the XSS attacks.

A: If get is supposed to only contain an integer use
$n = intval($_GET['n'])

A: If you're expecting a number, don't sanitize bad input, deny it.
if ( !ctype_digit($user_input) ) {
    header('Location: error.php'); // or whatever page
    exit;
}

A: Allways check user input and $_GET and $_POST data for malicious content. Addslashes, ereg_match and intval are your friend...
If you can get away with it, set the
allow_url_fopen = Off

directive in php.ini

A: I'd also requests hit your desired images directory too, as you don't want people browsing your file server with requests like example.com/?q=../../.htaccess
I'm not sure how that would affect the output, but it can't be good.

A: You don't have to worry about SQL injection. But you should check your input as it is used in the html you generate.
Imagine I give this link http://www.example.com/viewComic.php?id="/><script type="text/javascript>alert("XSS");</script><img src="22 to someone. This person will have a little pop-up coming from your website. And a lot of bad things can be done with javascript.
For more infos, you can start reading the wikipedia page about XSS.
So, you should check that the number you expect is a number. For example with is_numeric.


text:
Q: output to more than one canvas texture in processing with shader opengl as the question suggests im looking to output to more than one canvas element in processing to speed up the calculations and limit shader draw calls. It has to be as simple as possible to be transferable to android as well.
This is the shader call. Is there a way to do this using layout, if I was to provide another sampler texture?

#ifdef GL_ES

precision mediump float;
precision mediump int;
#endif
#define PROCESSING_TEXTURE_SHADER
uniform float v[10];
uniform sampler2D texture;
uniform sampler2D va0;
uniform sampler2D vb0;
uniform sampler2D va1;
uniform sampler2D vb1;
uniform sampler2D va2;
uniform sampler2D vb2;
uniform sampler2D va3;
uniform sampler2D vb3;
uniform float mult = 1.0;
uniform float type;
uniform float thresh;
uniform vec2 texOffset;
varying vec4 vertColor;
varying vec4 vertTexCoord;
uniform vec2 resolution;
uniform float w;
uniform int [1000]s;
uniform float [10]ops;
uniform float [1000]vars;
void main(void) {
float x = 1.0 / resolution.x;
float y = 1.0 / resolution.y;
vec2 tx = vertTexCoord.st;
vec4 via0 = texture2D(va0 , vertTexCoord.st);
vec4 vib0 = texture2D(vb0 , vertTexCoord.st);
vec4 via1 = texture2D(va1 , vertTexCoord.st);
vec4 vib1 = texture2D(vb1 , vertTexCoord.st);
vec4 via2 = texture2D(va2 , vertTexCoord.st);
vec4 vib2 = texture2D(vb2 , vertTexCoord.st);
vec4 via3 = texture2D(va3 , vertTexCoord.st);
vec4 vib3 = texture2D(vb3 , vertTexCoord.st);
float base = 256;
float b1 = base*base*255;
float b2 = base*255;
float b3 = 255;
float tva0 = (via0.r*b1 + via0.g*b2 + via0.b*b3);
float tva1 = (via1.r*b1 + via1.g*b2 + via1.b*b3);
float tva2 = (via2.r*b1 + via2.g*b2 + via2.b*b3);
float tva3 = (via3.r*b1 + via3.g*b2 + via3.b*b3);
float tvb0 = (vib0.r*b1 + vib0.g*b2 + vib0.b*b3 )/100000;
float tvb1 = (vib1.r*b1 + vib1.g*b2 + vib1.b*b3 )/100000;
float tvb2 = (vib2.r*b1 + vib2.g*b2 + vib2.b*b3 )/100000;
float tvb3 = (vib3.r*b1 + vib3.g*b2 + vib3.b*b3 )/100000;
float tvf0 = (tvb0+tva0);
float tvf1 = (tvb1+tva1);
float tvf2 = (tvb2+tva2);
float tvf3 = (tvb3+tva3);
if(via0.a<1.0)tvf0= (tvb0+(-(tva0)*0.0));
if(via1.a<1.0)tvf1= (tvb1+(-(tva1)*0.0));
if(via2.a<1.0)tvf2= (tvb2+(-(tva2)*0.0));
if(via3.a<1.0)tvf3= (tvb3+(-(tva3)*0.0));
float num = ((tvf0)/(tvf1)*(tvf2)/(tvf3))*1.0;
float numf = 0.0;
if(num<0.0) numf = int(-num);
else numf = int(num);
float rni = round(mod (numf/(base*base), base))/255;
float gni = round(mod ((numf/base), base))/255;
float bni = round(mod (numf, base))/255;
if(numf>0.0)gl_FragColor = vec4(rni, gni, bni, 1.0);
else  gl_FragColor = vec4(rni, gni, bni, 0.5);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: SGE qsub define variable using bach? I am trying to automatically set up several variables for SGE system but get no luck.
#!/bin/bash

myname="test"
totaltask=10

#$ -N $myname
#$ -cwd
#$ -t 1-$totaltask

apparently $myname will not be recognized. any solution?
thanks a lot

A: Consider making a wrapper function
qsub_file.sh
#!/bin/bash
#$ -V
#$ -cwd

wrapper_script.sh
#!/bin/bash
myname="test"
totaltask=10
qsub qsub_script.sh -N ${myname} -t 1-${totaltask}


text:
Q: Why does Spring 3.x ignore certain placeholderPrefixes for PropertyPlaceholderConfigurer? I have the bean definitions below. If I change the placeholderPrefix for the "exposeSystemProperties" bean to "${" and use that in the properties path of the second bean, it works. If I change it to anything but "%{" it doesn't work. I can't use any other string (e.g. "$sys{", "#[", etc.). I'm currently on 3.0.5.RELEASE.
Any thoughts as to why this is? To compound it all, I have a 3rd PropertyPlaceHolderConfigure, so only having two prefixes does not work.
  <bean id="exposeSystemProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="placeholderPrefix"><value>$sys{</value></property>
    <property name="order" value="10" />
  </bean>

  <bean id="localFileProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_NEVER" />
    <property name="placeholderPrefix" value="%{" />
    <property name="placeholderSuffix" value="}" />
    <property name="order" value="20" />
    <property name="locations">
      <array>
        <bean class="java.lang.String">
            <constructor-arg><value>classpath:properties/$sys{deploy.env}/client.properties</value></constructor-arg>
        </bean>
      </array>
    </property>
  </bean>

A: Since what you need the prefix for is to control environment specific properties, this can be done by using system variables ( instead of a deploy.env property in your example ):
 <value>classpath:properties/${ENV_SYSTEM:dev}/client.properties</value>

In this case it will always look under:
 <value>classpath:properties/dev/client.properties</value>

by default, unless a ENV_SYSTEM system variable is set. If it is set to "qa", for example, it will automatically look under:
 <value>classpath:properties/qa/client.properties</value>

Another approach, in case you are open to "look into the future" a bit, is to use Spring 3.1's PROFILE feature, where beans can be profile specific. For example:
<beans profile="dev">
    <jdbc:embedded-database id="dataSource">
        <jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
        <jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
    </jdbc:embedded-database>
</beans>

This dataSource will only be loaded in case a profile is set to dev:
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles( "dev" );
ctx.load( "classpath:/org/boom/bang/config/xml/*-config.xml" );
ctx.refresh();


text:
Q: How do I add XSS protection on my OpenCart 2.3 online store We have an OpenCart 2.3 hosted in Amazon Web Services. We have taken steps to protect against XSS, i.e. we activated XSS protection on AWS set-up. On Google Chrome, you will see our header:
X-XSS-Protection:1; mode=block

One test I did was to enter the following on the checkout comment:
<html>
<script>Alert('hello world')</script>
</html>

On checkout, no alert was displayed, meaning the script did not execute? I checked the database and saw that the tags were encoded, e.g  is stored as <html> This should mean that our site is protected against XSS?
What other steps can we take to fully protect against XSS

A: The X-XSS-Protection header doesn't do what you think it does. See What is the http-header "X-XSS-Protection" for a nice SO overview of it. But the tl;dr is that it enables some behaviour on IE8+.

Speaking more broadly, XSS, by it's nature, isn't something you can protect against with a single action. Every time you take in some user input, you have to be extra careful to validate that it respects the format you want it to be in. Whenever you present that input to a user, you have to properly handle it, so that a malicious script doesn't execute in the context of that user, and does bad things.
The OWASP has a nice XSS prevention cheatsheet which is a very nice resource.
But, in principle, always escape the user-supplied input according to the area where it is going to be displayed. If, for example, a user has supplied some text for the title of a shopping item, then that should be just text, and used in an HTML element that expects just text (one of the inline elements for example), and HTML-escaped etc. On the other hand, if a user has supplied an URL, then that should be used in a context where an URL is valid (as the source of an image, for example), and URL-escaped. Avoid allowing users to supply their own HTML, CSS or scripts. And avoid putting user-supplied values in scripts, CSS etc.

Finally, since you're using OpenCart, you're benefiting from loads of work other people have done already. So, unless you're doing something extra-custom and playing around with the inner bits of the framework, you're probably not going to run into deep waters. And follow the conventions inside the framework, of course.


text:
Q: Using Map() method in TypeScript Angular, returning array of Observable in a function I have this method in my service :
getPriceRules(): Observable<PriceRule[]> {
   return this.http.get<PriceRule[]>(this.url)
   .map(response => PriceRule.fromJson(response));
}

My error :
Type 'Observable<PriceRule>' is not assignable to type 'Observable<PriceRule[]>'.
Type 'PriceRule' is missing the following properties from type 'PriceRule[]': length, pop, push, concat, and 26 more.

What I want in my getPricesRules() method is get all PriceRule that the http.get returns me and to apply my function fromJson in each PriceRule
export class PriceRule {
  public static fromJson(json: Object): PriceRule {
    return new PriceRule(
       json['id'],
       json['activity'],
       json['duration'],
       json['is_indoor'],
       json['surface'],
       json['hour_start'],
       json['hour_end'],
       json['price'],
       json['currency'],
       json['weekdays']
    );
  }

  constructor(
        public id: string,
        public activity: string,
        public duration: number,
        public is_indoor: boolean,
        public surface: string,
        public hour_start: string,
        public hour_end: string,
        public price: number,
        public currency: string,
        public weekdays: number[]
    ) {}
}

A: You are confusing the Observable map with the array map:
.map(response => response.map((line) => PriceRule.fromJson(line));

The rxjs map, maps your response to another value, from there you need to take your array, and map it to the PriceRule.
Another way of doing this, which does not require your fromJson method is:
.map(response => response.map((line) => Object.assign(new PriceRule(), line));

Another way, is to make the PriceRule an interface, if you do that, you don't need any mapping:
return this.http.get<PriceRule[]>(this.url);

note: you should try to update to the latest rxjs >= 6 though. With that you have to use the .pipe function with operators

A: Remove the map
.map(response => PriceRule.fromJson(response));

Angular HttpClient will handle that for you

A: When you say getPriceRules(): Observable<PriceRule[]>, what it means is the method getPriceRules returns Observable that will return PricesRule[] (price rule array). When you call map on that Observable, it tries to apply the map function to PriceRule array (PriceRule[]) and not to each PriceRule object. Also, JSON to object conversion is done by Angular automatically. So, remove the map function.


text:
Q: Convert image points of interest to coordinates I have some images with a given height and width and a list of POIs as a list of integer values.
I want to convert this POIs to list of (x, y) coordinates. I'm aware this can be done by a builtin for loop. I'm looking for a more efficient way using np, Pillow, opencv2 or friends.
Here is an example:
Image WxH: 1024x1024
POIs: [10, 1025, ...]

Result: [(10, 0), (1, 1), ...]

A: This can be accomplished succinctly with a list comprehension:
WIDTH = 1024
pois = [10, 1025, ...]

coordinates = [(p % WIDTH, p // WIDTH) for p in pois]

Alternatively, you may use the divmod builtin to perform the division and remainder computations simultaneously. This will, however, produce pairs in the revere order from what you expect, so you will need to add an additional call to reverse:
coordinates = [reverse(divmod(p, WIDTH)) for p in pois]

While perhaps being more efficient, this may the composition of the resulting list less clear.

A: There is a specific function for this:
np.unravel_index(pois, (ysize, xsize), order='C')
>>> (array([0, 1]), array([10,  1]))

which are the expected y,x coordinates (first array for y, second array for x).
There is also the opposite function, np.ravel_multi_index().


text:
Q: Quotes printing text from MySQL When I display a text from the mysql commentaries field I use the following function in php:
nl2br(html_entity_decode($comment['message']))

and when inserted in the database in the query I use:
htmlentities($_POST['message'])

The question is that when I write a sentence like: "Hello" and displayed it shows: \"Hello\"
How can I avoid this?
Thanks in advance.
UPDATE:
Here is the insert:
$query = "INSERT INTO db.tablon (pID, userID, message, date_inserted, answer)
                VALUES (:proyectoID, :userID, :mensaje, NOW(), :respuesta_mensaje_id)";
    $stmt  = $pdo->prepare($query);
    $stmt->bindParam(':userID',     $userID,                    PDO::PARAM_STR);
    $stmt->bindParam(':proyectoID', $_POST['pID'],              PDO::PARAM_STR);
    $stmt->bindParam(':mensaje',    htmlentities($_POST['respuesta_tablon']), PDO::PARAM_STR);
    $stmt->bindParam(':respuesta_mensaje_id',   $_POST['mID'],  PDO::PARAM_STR);
    $res = $stmt->execute();

A: Escape them for mysql
$mysqli->real_escape_string($_POST['message']);

mysqli_real_escape_string($link,$_POST['message']);


text:
Q: Make Matlab issue a warning when converting a double to a uint8 and vice versa? Typically in Matlab colours are represented by three element vectors of RGB intensity values, with precision uint8 (range 0 - 255) or double (range 0 - 1). Matlabs functions such as imshow work with either representation making both easy to use in a program.
It is equally easy however to introduce a bug when assigning colour values from a matrix of one type, to that of another (because the value is converted silently, but not re-scaled to the new range). Having just spent a number of hours finding such a bug, I would like to make sure it is never introduced again.
How do I make Matlab display a warning when type conversion takes place?
Ideally it would only be when the conversion is between double and uint8. It should also be difficult to deactivate (i.e. the option is not reset when loading a workspace, or when matlab crashes).

A: A possible solution is to define your own uint8 function that casts to uint8 and issues a warning if some value has been truncated.
You should place this function in a folder where it shadows the builtin uint8 funciton. For example, your user folder is a good choice, as it usually appears the first in path.
Or, as noted by Sam Roberts, if you want this function to be called only when converting from double into uint8 (not when converting from any other type into uint8), put it in a folder named @double within your path.
function y = uint8(x)
y = builtin('uint8', x);
if any(x(:)>255) || any(x(:)<0)
    warning('MATLAB:castTruncation', 'Values truncated during conversion to uint8')
end

The warning is on by default. You can switch it on or off with the commands warning('on','MATLAB:castTruncation') and warning('off','MATLAB:castTruncation') (thanks to CitizenInsane for the suggestion).


text:
Q: How to add custom js file before body tag in magento 2?
But script moving to inside body tag how to fixes this issue? Anyone
can help me for this

<referenceContainer name="head.additional">
   <block class="Magento\Framework\View\Element\Template" name="custom_js" template="Magento_Theme::html/mycustomjs.phtml" before="-"/>
</referenceContainer>

A: app/code/Vendorename/Modulename/view/frontend/layout
default_head_blocks.xml
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Vendorename_Modulename::css/customcss.css" />
    </head>
    <body>
    </body>
</page>

Place your css at app/code/Vendorename/Modulenaee/view/frontend/web/css/customcss.css


text:
Q: Is there a way to prove the next inequality without using the binomial series? I have $\forall a\ge 1, x>0$ and I want to show that:
$$(x^a+1)^{1/a} \le (1+x)$$
The only way I see is through the binomial series.
Can you suggest other approaches?

A: Let $f(x)=(1+x)^{a}-x^{a}$ for $x \geq 0$. Then $f'(x)=a(1+x)^{a-1}-ax^{a-1} \geq 0$. Also $f(0)=1$. Hence $f(x) \geq 1$ for all $x>0$. This gives $(1+x)^{a}-x^{a}\geq 1$ which is equivalent to the given inequality.

A: Let $f(x)=x^a$.
Thus, $f$ is a convex function.
Thus, since $(x+1,0)\succ(x,1)$ or $(x+1,0)\succ(1,x)$,    by Karamata we obtain: $$f(x+1)+f(0)\geq f(x)+f(1)
$$ or
$$(x+1)^a+0\geq x^a+1$$ and we are done!


text:
Q: Firebase database count number of child I want to get first the number of children (if any). Then I want to add 1 to number of children, so the added children will be +1 from the existing.

So when I add new question, II want to add number 3. But I get it added as number 1 and it updates the existing number.
    int count = 0;
 public void addQuestion(View view) {
     mDatabase = FirebaseDatabase.getInstance();
     mRef = FirebaseDatabase.getInstance().getReference("Questions");
       count = count + 1;
        String nr = String.valueOf(count);
        GetData getdata = new GetData(qs, A, B, C, correct);
        mRef.child(nr).setValue(getdata);
        Toast.makeText(AdminPanel.this, "Adding question...", Toast.LENGTH_SHORT).show();
                    }

A: You can use the push function and it will generate a unique key, so you don't have to worry about giving then unique numbers.
mRef.push();
you can also get the key that was generated if you need it,
https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push
or just retrieve all the children (your questions) when needed.
I suggest you read the documentation, I found there all the information I needed.
https://firebase.google.com/docs/database/


text:
Q: In AngularJS $scope.data is updated for first time click the button Its workind second time clicked Here i am passing 6 inputs and getting 6 output fields when i click the button first time $scope.data is not binding or updated the data in UI if i click button second time the $scope.data is binding or updated the  data in UI.Please any help me on this issue.

Input:

    <form class="form-horizontal">

            SalesService

                <input type="text" placeholder="SalesService" ng-model="SalesService" id="SalesService">

            PlatForm

                <input type="text" placeholder="PlatForm" ng-model="PlatForm" id="PlatForm">

            SegMent:

                <input type="text" placeholder="SegMent" ng-model="SegMent" id="SegMent">

            Path:

                <input type="text" placeholder="Path" ng-model="Path">

            UserId:

                <input type="text" placeholder="UserId" ng-model="UserId">

            CardNo:

                <input type="text" placeholder="CardNo" ng-model="CardNo">

    </form>

        <button class="btn btn-success" id="Submit" ng-click="getBinLookUp()">
              Submit
        </button>

Output:

    <form class="form-horizontal">

            ReturnCode

                <input type="text" ng-disabled="true" ng-model="data.ReturnCode" placeholder="ReturnCode" id="ReturnCode">

            Return Message

                <input type="text" ng-disabled="true"  ng-model="data.ReturnMessage" placeholder="ReturnMsg" id="ReturnMsg">

            Card Company:

                <input type="text" ng-disabled="true" ng-model="data.Company" placeholder="CardCompany" id="CardCompany">

            Charge Type:

                <input type="text" ng-disabled="true" ng-model="data.ChargeType" placeholder="ChargeType">

            GEICO Card IND:

                <input type="text" ng-disabled="true" ng-model="data.GEICOCardInd" placeholder="GEICOCardIND">

    </form>

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

A: Try with $scope.$apply(); after $scope.data = result[0];

A: Don't use jquery's $ajax to fetch the data. Angularjs is not aware of any changes from non-angular http calls. Use angularjs' $http.get to fetch the data. Another solution would be to wrap the $ajax call with $timeout or $apply.


text:
Q: Dynamically create HTML table rows based on php array I am seriously struggling to grasp my head around the following. I want to build a 3 data cell per row table based on an PHP array. So in other words, if there is 3 values in the array, there should be a structure like:
<?php
$arr = array("value1","value2","value3");
?>

// Expected outcome:

           value1
           value2
           value3

but should a 4th value be added to the array, it must dynamically create another row so in other words:
<?php
$arr = array("value1","value2","value3","value4");
?>

// Expected outcome:

           value1
           value2
           value3

           value4

I really don't mind which solution, even a mix between php and jQuery, but just something I can use to achieve the above.

A: Use modulo. Like so:

<?php
    $i = 1;
    foreach ($arr as $val){
        $i++;
        print ''.$i.'	';
        if ($i % 3 == 0){
            print '

'^;
        }

    }
?>

You will need to add some more stuff for correct html output, but the "hard" part is done.
Don't just copy and paste, I didn't test the code and it's ugly.

A: Use array_chunk function to split the array into groups and then just do a couple of loops e.g.
<?php
$arr = array("value1","value2","value3","value4");
echo "
";
$rows = array_chunk($arr,3);
foreach($rows as $row) {
  echo "
";
  foreach($row as $cell) {
    echo "".$cell."	";
  }
  echo "
";
}
echo "
";
?>

A: Here is a logic implementation :
<?php
$input_array = array('a', 'b', 'c', 'd', 'e','f','g');
$new_array = array_chunk($input_array, 3);

$table = '
';
foreach($new_array as $value){
$table .= '
'.$value[0].'	'.$value[1].'	'.$value[2].'
';
}
$table.='
';

echo $table;
?>

A:

<?php
$arr = array("value1","value2","value3","value4","value5","value6","value7");

for($i=0;$i<count($arr)%3;$i++)
  $arr[] = null;

foreach($arr as $key => $val){

  if(($key)%3==0)
    echo '

';

  echo ''.$val.'	';

}
?>

A:

        <?php
        $x = 0;
        foreach($arr as $v){
            if ($x % 3 == 0 && $x != 0){
                echo '

';
            }

            echo ''.$v.'	';
            $x++;
        }
        ?>

A: Here is my suggestion which will produce will formatted html

    <?php
    $i = 0;
    $items_per_row = 3;

    foreach ($arr as $elm) {
        echo ''.$elm.'	';

        if (++$i % $items_per_row == 0 && $i < count($arr) - 1)
            echo '

';
    }
    ?>


text:
Q: When to use ON keyword in SQL Join When exactly can I use ON keyword while using joins in SQL be cause I'm confused.
Also, could any one please help me understand different types of joins with an example.
Thanks.

A: you'd want to do something like this:
select
  tbl_items.item_name,
  tbl_category.category_name
from
  tbl_items INNER JOIN tbl_categories
    ON tbl_items.category_id = tbl_categories.category_id

this would join your table named tbl_items to your table tbl_categories based on the primary key tbl_categories.category_id, which is linked to the foreign key tbl_items.category_id.
think of it as telling the db that you want to join two tables ON two matching fields.
different join types:

*INNER JOIN returns only rows where the two fields compared in the ON statement match

*LEFT OUTER JOIN (or just OUTER JOIN) returns all rows from the leftmost table in the join statement, and any rows from the rightmost table where the fields compared in the ON statement match.

*RIGHT OUTER JOIN returns all rows from the rightmost table in the join statement and any rows from the leftmost table where the fields compared in the ON statement match.

A: ON is required to match fields on joined tables.
check the http://en.wikipedia.org/wiki/Join_%28SQL%29

A: Creating Joins with the ON Clause:
The ON Clause is used with Natural Join to specify the join condition, here is a more details written in form of bullet list:

*

*The join condition for the natural join is basically an equijoin of all columns with the same name.

*To specify arbitrary conditions or specify columns to join, the ON clause is used.

*The join condition is separated from other search conditions.

*The ON clause makes code easy to understand

Example:
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id
FROM employees e
JOIN departments d
ON (e.department_id = d.department_id);

The Output:

EMPLOYEE_ID
LAST_NAME
DEPARTMENT_ID
DEPARTMENT_ID
LOCATION_ID

200
Whalen
10
10
1700

201
Hartstein
20
20
1800

202
Fay
20
20
1800

124
Mourgos
50
50
1500

141
Rajs
50
50
1500

142
Davies
50
50
1500

143
Matos
50
50
1500

Different Types of SQL Join:
Here is a good Visual Explanation of SQL Joins that would clarify the differences.
Thanks @mihai for this article.


text:
Q: How can I detect the press of three switches by an interrupt service routine connected to just one interrupt pin Lately, I tried to use my Arduino Uno (AtMega328) board to detect the press of a series of three switches by an interrupt service routine.
If have three switches for called R, G and B. Whenever,at least one of these switches is pressed once a RGB-Led should toggle its state for red, green or blue.
Now, it was no problem for just two switches R and G, as the Arduino Uno board has two interrupt capable pins (2 and 3).
But, for the switch B I'm lacking another interrupt pin to detect the press of at least one of the three switches.
Is there a possible circuit, that easily allows one to detect the press of at least one of the three switches, so that I can just use one interrupt capable pin to detect the press of any switch?
The code for two leds using the Arduino IDE was super easy for just two switches:
const int buttonRed = 2;     // the number of the pushbutton pin
const int ledRed =  13;      // the number of the LED pin

const int buttonGreen= 3;
const int ledGreen=12;

// variables will change due to ISR
volatile int redState = 0;
volatile int greenState=0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledRed, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonRed, INPUT);

  pinMode(ledGreen, OUTPUT);
  pinMode(buttonGreen, INPUT);

  // Attach an interrupt to the ISR vector
  attachInterrupt(digitalPinToInterrupt(buttonRed), redButton_ISR, CHANGE);
  attachInterrupt(digitalPinToInterrupt(buttonGreen), greenButton_ISR, CHANGE);
}

void loop() {
  // Nothing to do here
}

void greenButton_ISR() {
  greenState=digitalRead(buttonGreen);
  digitalWrite(ledGreen, greenState);
}

void redButton_ISR() {
  redState = digitalRead(buttonRed);
  digitalWrite(ledRed, redState);
}

A: As stated in the comments you can use pin change interrupts.
See https://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/
 or
https://arduino.stackexchange.com/questions/1784/how-many-interrupt-pins-can-an-uno-handle
Alternatively you can connect all buttons to the same interrupt and each one to another input. Then in the ISR check which of the three buttons is pressed.
Or you connect all three buttons with three different resisitors to an analog input. The measured voltage tells you which of the buttons are pressed.
If your code doesn't do anyhting but this, there is actually no need for interrupts so you can just frequently poll the button states in a loop.


text:
Q: Window Leaked During Orientation Change on AlertDialog From another class instantiated inside the main activity contains this method that displays an alertdialog. I am still getting the window leaked  during orientation changed. I also checked out several questions, they are getting similar answers.
Main Class:
AlertDialog aler;
classB(aler);

Class B:
AlertDialog aler2;
classB(AlertDialog a){
this.aler2 = a;
}

private void showWifiDialog(AlertDialog aler2) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this.context)
            .setTitle("Device")
            .setMessage("Press OK")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    aler2 = builder.create();

    aler2.show();

}

Experiments:
    @Override
    public void onPause() {
            if(aler!=null && aler.isShowing())
         {
             aler.cancel();
         }
      super.onPause();
    }

   @Override
    public void onStop(){
        if(aler!= null && aler.isShowing()) {

            aler.dismiss();

          }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
     // TODO Auto-generated method stub

        if(aler!=null)
         {
             aler.dismiss();
         }
    }

A: Try this just put this in manifest and try
<activity
            android:name="ActivityWhcichCallingDialog"
            android:configChanges="keyboardHidden|orientation|screenSize"
/>


text:
Q: (CS50/pset5/speller) I have a memory leak issue, according to check50 and valgrind. I think I'm using a variable that doesn't have a value I have a memory leak issue, according to check50 and valgrind. It looks like I'm trying to use a variable that might not have a value. Everything else works correctly, according to check50, the only issue is with memory. Here is valgrind's error message:

==3243== Conditional jump or move depends on uninitialised value(s)
==3243==    at 0x520A60F: tolower (ctype.c:46)
==3243==    by 0x4010CD: check (dictionary.c:36)
==3243==    by 0x400CD9: main (speller.c:112)
==3243==  Uninitialised value was created by a stack allocation
==3243==    at 0x4008E4: main (speller.c:21)
==3243==
==3243== Use of uninitialised value of size 8
==3243==    at 0x520A623: tolower (ctype.c:46)
==3243==    by 0x4010CD: check (dictionary.c:36)
==3243==    by 0x400CD9: main (speller.c:112)
==3243==  Uninitialised value was created by a stack allocation
==3243==    at 0x4008E4: main (speller.c:21)
==3243==

WORDS MISSPELLED:     0
WORDS IN DICTIONARY:  143091
WORDS IN TEXT:        6
TIME IN load:         1.46
TIME IN check:        0.00
TIME IN size:         0.00
TIME IN unload:       0.21
TIME IN TOTAL:        1.67

==3243==
==3243== HEAP SUMMARY:
==3243==     in use at exit: 0 bytes in 0 blocks
==3243==   total heap usage: 143,097 allocs, 143,097 frees, 8,023,462 bytes allocated
==3243==
==3243== All heap blocks were freed -- no leaks are possible
==3243==
==3243== For counts of detected and suppressed errors, rerun with: -v
==3243== ERROR SUMMARY: 492 errors from 2 contexts (suppressed: 0 from 0)

Asking for help...

==3243== Conditional jump or move depends on uninitialised value(s)

Looks like you're trying to use a variable that might not have a value? Take a closer look at line 36 of dictionary.c.

Here is my code (I would love if you could help ;))
// Implements a dictionary's functionality

#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>

#include "dictionary.h"

#define HASHTABLE_SIZE 65536

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of buckets in hash table
const unsigned int N = HASHTABLE_SIZE;

// Hash table
node *table[N];
unsigned int totalWords = 0;

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    //Initialize lower case word
    char lcword[LENGTH + 1];

    for (int i = 0; i < LENGTH + 1; i++)
        lcword[i] = tolower(word[i]);

    node *cursor = table[hash(lcword)];

    while (cursor != NULL)
    {
        if (strcasecmp(word, cursor->word) == 0)
        {
            return true;
        }

        cursor = cursor->next;
    }

    return false;
}

// Hashes word to a number
unsigned int hash(const char *word)
{
    //https://www.reddit.com/r/cs50/comments/1x6vc8/pset6_trie_vs_hashtable/cf9nlkn/
    unsigned int hash_value = 0;

    for (int i = 0, n = strlen(word); i < n; i++)
        hash_value = (hash_value << 2) ^ word[i];

    return hash_value % HASHTABLE_SIZE;
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{

    FILE *dicfile = fopen(dictionary, "r");
    char *word = malloc(LENGTH + 1);

    //Check if word is null
    if (word == NULL)
        return false;

    //Check if the fopen function opened a not NULL file
    if (dicfile == NULL)
       return false;

    //Iterate over dictionary until fscanf return EOF (meaning it's the end of the file)
    while (fscanf(dicfile, "%s", word) != EOF)
    {
        //Create a node to store the current word
        node *new_node = malloc(sizeof(node));

        if (new_node == NULL)
            return false;

        //Copy the new_node's word into the current word
        strcpy(new_node->word, word);

        //Get the index (hash the current word and store it in n)
        int n = hash(new_node->word);

        //Insert the new_node into the linked list
        new_node->next = table[n];
        table[n] = new_node;

        //Add to the total number of words in the text file
        totalWords++;
    }

    fclose(dicfile);
    free(word);
    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
    return totalWords;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{

    for (int i = 0; i < HASHTABLE_SIZE; i++)
    {
        node* cursor = table[i];
        node* tmp;

        while (cursor != NULL)
        {
            tmp = cursor;
            cursor = cursor->next;
            free(tmp);
        }
        free(cursor);
    }
    return true;
}

And if you want to know, line 36 of my code is this one: lcword[i] = tolower(word[i]);
Thank you!!!

A: regarding:
for (int i = 0; i < LENGTH + 1; i++)

in C, the valid range of indexes into an array are 0...(number of elements in array-1 )  Note the -1
Note: the macro: LENGTH is not defined anywhere in the posted code.
the function:  check() is implemented in the posted code, but never called.
regarding:
for ( int i = 0, n = strlen(word); i < n; i++)

The function: strlen() returns a size_t, so the statement should be:
for ( size_t i = 0, n = strlen(word); i < n; i++ )

The function: size() is implemented but never called.
it is a very poor programming practice to include header files those contents are not used.  for instance:
#include <strings.h>

regarding;
if (dicfile == NULL)
   return false;

This should be immediately after;
FILE *dicfile = fopen(dictionary, "r");

and should include the statement:
perror( "fopen to read dictionary file failed" );

regarding:
while (fscanf(dicfile, "%s", word) != EOF)

there are other reasons that a call to fscanf() can fail.  Should be checking for success.
the %s input format conversion specifier can input more characters than there are in the array word().  Also, that specifier always appends a NUL byte to the input.  To avoid any buffer overflow problems, always use a modifier that 1 less than the length of the buffer.  Suggest:
while (fscanf(dicfile, "%" LENGTH "s", word) == 1)
regarding your question about a memory leak:
The posted code modifies pointers (by overlaying them) in table[] without first checking of there is already an active entry there.  If there is an active entry already at the 'hashed' index into the table, then the new entry must be linked after (could be linked before) the current entry, at the same index into table[]
Of course, when an active entry is overlayed, the result is a memory leak.


text:
Q: facebook application: how to put html code like 'a href' inside news feed content? (After the newest api update) After the newest Facebook update for publishing news feed, it seems that it doesn't support html code (like a href) inside the new feed content anymore
But I still see feeds with click-able link inside the content, how to do that?
below are the images of the feeds that have link inside the feed content

(source: dchammer.com)

A: Use the properties property of the stream attachment object. This takes a dictionary of key/value pairs, where the values can themselves be an object consisting of text and href properties. E.g. attach something like the following onto your stream attachment object in JavaScript:
var properties = {
    "Rating" : {
        "text" : "1797 points",
        "href":"http://apps.facebook.com/yourappurl/"
        },
    "Leaderboard position":{
        "text":"192nd",
        "href":"http://apps.facebook.com/yourappurl/"
    }
}

Will display the text "Rating: 1797 points" and "Leaderboard position : 192nd" on separate lines, with the "Rating" and Leaderboard position" text in light grey and the "1792 points" and "192nd" both as blue hyperlinks.
There are character of 50 characters max for the "key" part (i.e. the "Leaderboard position" segment) and 70 characters for the "value" part.

A: So I tried a href and instead of the usual html, I did some trial and error and found out it will work if written like this:
a href=facebook.com facebook

the key is the space between the link and the actual text you want to display. Without the space this won't work properly.

A: I believe this is specified by the meta tags of the page being linked to.  For more information, check out http://wiki.developers.facebook.com/index.php/Facebook_Share/Specifying_Meta_Tags
Basically, when the user posts a link to an outside site, facebook fetches that page, and looks at certain meta tags to come up with a preview of the site, including some text and a small image, if these are specified by the linked site.
So, I think you should be able to just include your href tags in your meta description, and you should be all set.  I haven't tried this with links, but that is definitely how you get the description and image to show up.


text:
Q: how move constructor/semantics works and what is used for? And I faced a concept called move constructor.
What I got from that concept we will use it to increase performance and reduce memory duplication by not copying the objects all over the place.
But I don't know how this work and I'm confused about this. What I understood it's like shallow copy constructor but it nulls out the source pointer of original object and copy the address.
Are objects passed by value? Is that why it needs to use copy constructor?
If I want to not copy object and work with the object itself, can I use & with object?
I know move constructors work with r-value which are temp parameters/objects.
class Move{
private:
    int* data;
public:
    void set_data_value(int d) {*data = d;}
    int  get_data_value() {return *data;}
    //constructor
    Move (int d);
    //copy constructor
    Move(const Move &source);
    //Move constructor
    Move(Move &&source) noexcept
    //destructor
    ~Move();
};

Move::Move(int d) {
    data = new int;
    *data = d;
    }

//copy constructor
Move::Move(const Move &source)

//Move constructor
Move::Move(Move &&source) noexcept
    : data(source.data) {
        source.data = nullptr;
        }

Move::~Move {
    delete data;
    }

void display_move(Move s)   {           //this will use copy constructor to copy object to work with copied object
    cout << s.get_data_value << endl;
    }

void display_move(Move &s)  {           //can i use this to work with the actual object???
    cout << s.get_data_value << endl;
    }

int main() {
    vector<Move> vec;
    Move object1{10};               //l-value reference
    display_move(object1);
    vec.push_back(Move{10});        //r-value reference so it will use move constructor
    vec.push_back(std::move(object1));  //casting l-value to r-value so it will use move constructor instead of copy constructor


text:
Q: Skyrim just doesn't want some NPCs to be killable I've been trying to use the setessential command to mark NPCs as not essential (thus killable) but certain NPCs remain essential after using the command. These NPCs are: Jarl Balgruuf, Farengar Secret-Fire (or whatever his name is), Jorleif (Ulfric's steward), all of the leaders of the Companions, Sibbi Black-Briar, members of the Theives Guild, and maybe more, but I don't know at the moment. But why isn't the command working? I have the correct BaseID and everything.

A: So you want to kill Jarl Balgruuf...why? He is like a major part of the story too! But, as ChaseC said, you need a MOD if you are on PC version. I am pretty sure Nexus has one, and the steam store probably does too.
Although, if you want to kill Ulfric Stormcloak, (Spoiler)

 you can do the Imperial Legion questline (It takes about an hour) and kill him in the end

A: Some story-based NPC's essential code cannot be changed. You must download a mod to over-ride these commands.

A: Just out of curiosity, have you tried console-killing them?  (bring up the console, select them with your mouse, and type "kill?").  I'm guessing they will just fall over, be unconscious for a bit, and then get up again, but I've never really been curious enough to try.
FWIW, I agree with Aceofgods; if you kill essential characters that are central to the storyline, it will break the main quest, and they (Bethesda) probably put some safeguards in place to prevent that.

A: Whether or not you've completed a quest with them, you can't kill an essential character.

A: I'm not sure what you're trying to accomplish by killing them (e.g. do you just want to remove them from the game, or do you want to loot their items etc). However, if you want to do it purely to remove them from existence, you can do that very easily by opening the console (` or ~), clicking on them, typing in 'disable' (without quotes) and hitting enter. They will be removed from existence. And then if you ever want to bring them back, you can do so with 'enable'.


text:
Q: How to use istream with strings I would like to read an file into a string. I am looking for different ways for how to do it efficiently.
Using a fixed size *char buffer
I have received an answer from Tony what creates a 16 kb buffer and reads into that buffer and appends the buffer till there is nothing more to read. I understand how it works and I found it very fast. What I don't understand is that in the comments of that answer it is said that this way copies everything twice. But as I understand it, it only happens in the memory, not from the disk, so it is almost unnoticable. Is it a problem that it copies from the buffer to the string in the memory?
Using istreambuf_iterator
The other answer I received uses istreambuf_iterator. The code looks beautiful and minimal, but it is extremely slow. I don't know why does it happen. Why are those iterators so slow?
Using memcpy()
For this question I received comments that I should use memcpy() as it is the fastest native method. But how can I use memcpy() with a string and an ifstream object? Isn't ifstream supposed to work with its own read function? Why does using memcpy() ruin portability? I am looking for a solution which is compatible with VS2010 as well as GCC. Why would memcpy() not work with those?
+ Any other efficient way possible?
What do you recommend, what shell I use, for small < 10 MB binary files?
(I did not want to split this question in parts, as I am more interested in the comparison between the different way how can I read an ifstream into a string)

A: The most general way would be probably be the response using the
istreambuf_iterator:
std::string s( (std::istreambuf_iterator<char>( source )),
               (std::istreambuf_iterator<char>()) );

Although exact performance is very dependent on the implementation, it's
highly unlikely that this is the fastest solution.
An interesting alternative would be:
std::istringstream tmp;
tmp << source.rdbuf();
std::string s( tmp.str() );

This could be very rapid, if the implementation has do a good job on
the operator<< you're using, and in how it grows the string within the
istringstream.  Some earlier implementations (and maybe sone more
recent ones as well) were very bad at this, however.
In general, performance using an std::string will depend on how
efficient the implementation is in growing a string; the implementation
cannot determine how large to make it initially.  You might want to
compare the first algorithm using the same code with std::vector<char>
instead of std::string, or if you can make a good estimate of the
maximum size, using reserve, or something like:
std::string s( expectedSize, '\0' );
std::copy( std::istreambuf_iterator<char>( source ),
           std::istreambuf_iterator<char>(),
           s.begin() );

memcpy cannot read from a file, and with a good compiler, will not be
as fast as using std::copy (with the same data types).
I tend to use the second solution, above, with the << on the
rdbuf(), but that's partially for historical reasons; I got used to
doing this (using istrstream) before the STL was added to the standard
library.  For that matter, you might want to experiment with
istrstream and a pre-allocated buffer (supposing you can find an
appropriate size for the buffer).

A:
it only happens in the memory, not from the disk, so it is almost unnoticable

That is indeed correct. Still, a solution that doesn't do that may be faster.

Why are those iterators so slow?

The code is slow not because of the iterators but because the string doesn't know how much memory to allocate: the istreambuf_iterators can only be traversed once so the string is essentially forced to perform repeated concatenations with resulting memory reallocations, which are very slow.
My favourite one-liner, from another answer is streaming directly from the underlying buffer:
string str(static_cast<stringstream const&>(stringstream() << in.rdbuf()).str());

On recent platforms this will indeed pre-allocate the buffer. It will however still result in a redundant copy (from the stringstream to the final string).


text:
Q: How to exit a blocking recv() call? Based on this question, when you call closesocket() on a socket that recv() is already using, then an RST packet will be sent to the other side instead of performing  a graceful disconnection (4-way handshake).
But I wish to perform a graceful disconnection, so I need to exit recv() before calling closesocket().
Is there a way to do that?

A: You can shutdown() the socket for input. The recv() will unblock and return zero and everybody will be happy.

A: The real issue here is that a sure kill, terminatethread(), has all kinds of warnings on it about bad effects of its use. I have been using this method to exit an recv(). The windows docs says "you must know what the thread is doing before applying terminatethread", well, we know what it is doing, its in recv(). The question is not what the THREAD is doing, its what windows kernel is doing.
In the embedded system RTOSes I have done killthread() is doable. Its not EASY, you have to find every single lock and resource owned by the thread and back it out. Only the OS has that kind of information (and power).


text:
Q: avconv: remove audio stream, keep audio and video synchronized I have an AVI file with one video and three audio streams. I would like to discard two of the audio streams, keeping only one.
I tried to do so using avconv (v11.3-6):
avconv -i in.avi -map 0:0 -map 0:2 -vcodec copy -acodec copy out.avi

The problem is that in the resulting file the remaining audio stream is no longer correctly synced to the video stream, though they are synced in the original.
I also tried these variants:
avconv -i in.avi -map 0:0 -map 0:2,0:0 -vcodec copy -acodec copy out.avi

avconv -i in.avi -map 0:0 -map 0:2,0:0 -vcodec copy -acodec copy -vsync passthrough out.avi

with the same result.
What am I missing?


text:
Q: Select2 select options not being displayed when label is clicked When the label associated to my select2 select element is clicked, it doesn't display the options associated with that select element.
On IOS it shows the no options popup although there are definitely options set for the select tag

Whereas on android it just places the | character in the select element similarly to what it does for an input field


text:
Q: Prove $\left\lfloor n\right\rfloor = n + O(1)$ Can someone show me why $\left\lfloor n\right\rfloor = n + O(1)$.
Using the same logic, can anyone derive a similar proposition for $\left\lceil n\right\rceil$?

A: The reason we use the notation $O(1)$ is that the error associated with performing this operation is constant (i.e. doesn't depend on our value of $n$).
We know that
$\left\lfloor n \right\rfloor = n - m$
where $0\leq m < 1$. For instance,
$\left\lfloor 6.5 \right\rfloor = 6 = 6.5 - 0.5$
The error, $m$ in this case is bound between $0$ and $1$.
If we were too look at much larger numbers, that error bound would be the same. For instance
$\left\lfloor 999234.712 \right\rfloor = 999234 = 999234.712 - 0.712$
Our error is still constant in that it doesn't increase as the number we put in the function increases.
Using this exact same logic and the expression
$\left\lceil n \right\rceil = n + m$
where $0< m \le 1$.
the exact same argument holds.


text:
Q: How to prove that certain points relating to a trapezoid are collinear? Can you help me to prove that in any trapezoid, which is not a parallelogram, the following points are collinear?

*

*The midpoints of its bases.

*The point of intersection of diagonals.

*The point of intersection of the extended sides of trapezoid that are not parallel.

Thank you very much!

A: These form a triangle:

*

*A: The point of intersection of the extended sides of trapezoid that are not parallel.

*B & C The endponts of the longest base.

And all the points are on the on the median from the point A.
So that is enough hint
GOOD LUCK

A: Without loss of generality you may assume the corners to have the following coordinates:
$$(a, 0)\qquad (b, 0)\qquad (c, h)\qquad (d, h)$$
Then the points you mention have coordinates
$$
\begin{array}{ccc}
\left(\frac{a+b}2, 0\right) &\qquad&
\left(\frac{c+d}2, h\right) \\
\left(\frac{ad-bc}{a-b-c+d}, \frac{(a-b)h}{a-b-c+d}\right)
&\qquad&
\left(\frac{ac-bd}{a-b+c-d}, \frac{(a-b)h}{a-b+c-d}\right)
\end{array}
$$
All of them are incident to the line
$$2h\,x + (a+b-c-d)y=(a+b)h$$
I actually computed these coordinates and the corresponding line using projective geometry, where both operations (joining points and intersecting lines) can be expressed easily using the cross product.


text:
Q: zigbee control application with android on IMX6 board I am dealing with a project in that my IMX6 processor on which android is ported is used  to interface with TI CC2530 zigbee module. I want to control zigbee nodes using the application on android board.The module is communicated via uart with the board.What all things i should do for creating Zigbee app which can control the zigbee homeautomation device?

A: Get TI's Z-Stack Linux Gateway software running on the IMX6.  From that webpage:

Z-Stack Linux Gateway is TI's ZigBee Home Gateway solution for Linux
  systems.
Z-Stack Linux Gateway notables include:

*

*Ease of ZigBee integration into the IP (Internet Protocol) world, with
  simplified APIs over socket

*ZigBee middleware, abstracting a variety
  of Home and Building Automation use cases

*

*Lighting control

*Alarm and security

*Energy management

*Network management and Over-The-Air firmware upgrade

*Fast prototyping on BeagleBone Black platform,
  powered by TI's leading Sitara AM335x Cortex-A8 processor

*Ability to run on most Linux or Android-based platforms

*Based on Z-Stack, ZigBee
  Pro 2012 protocol stack with ZCP (Zigbee Compliant Platform)
  certification and 802.15.4 MAC certification

*Leveraging TI's ZNP
  (ZigBee Network Processor) firmware

*

*Based on Z-Stack and ZigBee PRO
  2012 protocol stack with ZCP (ZigBee Compliant Platform) certification

*Available low-power devices: low cost SimpleLink™ ZigBee CC2530 and
  high performance SimpleLink ZigBee CC2538

*Incorporated support for the
  SimpleLink Range Extenders CC2591 and CC2590. These RF front ends
  support +22dBm and +14dBm transmit power respectively and provide
  improved receive sensitivity (3-dB typical Improved RX sensitivity on
  CC253X devices).


text:
Q: Simple If Else Statement. Trying to get this to work.. I don't understand the If else Statement. Basically if the Field Photo has a value I would like it to display if it has a value of Null Obviously the Else Statement woudl display.
$row = photo

$id = $_GET['id'];
$sql = "SELECT * FROM menu_category WHERE id  = '$id' order by sort";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {

echo "
".$row['category_field']."
 ";
echo "
  ".$row['description']."
 ";

$row = photo("*");

if ($photo = "*") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}

A: use !empty to check if the photo exist or not, not *
   $row = photo

$id = $_GET['id'];
$sql = "SELECT * FROM menu_category WHERE id  = '$id' order by sort";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$photo_exist = $row['photo'];

echo "
".$row['category_field']."
 ";
echo "
  ".$row['description']."
 ";

if (!empty($photo_exist)) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}


text:
Q: Is it possible to avoid call to sotring within the partiton during the usage of Dataframe.write.partitionBy() Is it possible to avoid the call to internal sorting within the partitonBy function during the usage of Dataframe.write.partitionBy().parquet(path: String) because this df is already in sorted order.
Explanation:
At run 1: we are reading all the base data and storing it into partitioned folders on top of s3
step1) BaseData -> sparkJob ->  s3(partitioned data)

At run 2:
step1) we are reading the delta data then re-partitioning and sorting it up.
step2) union the delta with basedata and saving it to the s3 location(partitioned).
step 1) DeltaData -> Sparkjob(repartition(by same partition number) + sortByPartition(<partition col>) )

step 2) BaseData(s3 partitioned) -> spark( BaseData union refined delta df(step 1)) ->  s3(partition data)

Now, I am using DF.write.partitionBy(part col).parquet(path: String) function to write the data to s3 which is calling the sort stage internally. I need to avoid this sorting, is there a way?


text:
Q: JavaScript accessing vriable i have this javascript code for accessing a JSON. There is a variable v1 that i declared global, but i can't access it outside this function.

    $.ajax({
            type: 'GET',
            url: url,
            async: true,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
                //console.log("good");
                v1 = [];
                $.each(json, function(key, val) {
                   // $('ul').append('
' + val.dir + ' ' + val.nr  + '
');
                   if(val.dir === "IESIRE"){
                      // console.log(val.data);
                       v1.push(val.data);
                   }
                });
            },
            error: function(e) {
                console.log(e.message);
            }
        });

    console.log(v1);

Please help to understand this.

A: You can get the data by a function call. You can read more about this here. An  example fiddle http://jsfiddle.net/y4vv6t8y/
$.ajax({
            type: 'GET',
            url: 'http://echo.jsontest.com/key/value/one/two',
            async: true,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
                //console.log("good");
                v1 = [];
                $.each(json, function(key, val) {

                       v1.push(val);

                });
                _callback(v1);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
function _callback(data){
    console.log(data);
}

A: Simply declare your variable var v1 = []; outside $.ajax call first. It will the be accessible from within the scope of the anonymous function you pass to $.each.


text:
Q: Prove the function is continuous, exercise from Conway's "Functions of One Complex Variable I" For the first proof of Cauchy's integral formula, Conway in his book "Functions of One Complex Variable" (Chapter IV, section 5.4) uses the following claim:

Let $G$ be an open subset of $\mathbb C$ and $f : G \to \mathbb C$ an analytic function. Then define $\varphi : G \times G \to \mathbb C$ as
  $$
\varphi(z,w) = \begin{cases}
\dfrac{f(z)-f(w)}{z-w}, && z\neq w \\
  f'(z) && z=w \end{cases}. $$
  Then $\varphi$ is continuous on $G \times G$.

Unfortunately, he does not give a proof, leaving it as an exercise (Exercise 1).
I tried to make a direct proof by taking $|z-z_0| + |w-w_0| < \delta$ as a neighbourhood of $(z_0,w_0)$, but it lead to nowhere. I understand, that $z \mapsto \varphi(z,w)$ and $w \mapsto \varphi(z,w)$ are both holomorphic and continuous, but I do not see how one could use it.
I also saw this claim in several lecture notes but it goes unproven there either.
I would appreciate a hint, we have this problem as a homework.

A: Hint: The only troublesome case is when $(z,w) \to (a,a)$  for some $a\in G.$ Here note
$$f(z) - f(w) = \int_0^1 f'(w +t(z-w))(z-w)\ dt$$
for $z,w$ in any $D(a,r)\subset G.$

Added the following details later: If $z,w \in D(a,r)\subset G,$ then $\varphi(z,w) = \int_0^1f'(w+t(z-w))\  dt,$ including the case where $z=w.$ Note that $|w+t(z-w) - a| \le |z-a|+|w-a|$ for $t\in [0,1].$ Thus as $(z,w) \to (a,a),$ $f'(w+t(z-w)) \to f'(a)$ uniformly on $[0,1].$ That gives the desired convergence of the integral to $f'(a),$ which is what we want.


text:
Q: Oracle Transaction Update Amount From One Table to Another I'm creating a database that contains four different tables:
CUSTOMER (PK CUST_ID, CUST_NAME, CUST_ADDRESS)

INVOICE (PK INVOICE_ID, FK CUST_ID, INVOICE_AMOUNT)

PRODUCT (PK PRODUCT_ID, PRODUCT_NAME, PRODUCT_COST)

INVOICE_ITEM (PK FK INVOICE_ID, PK FK PRODUCT_ID,
INVOICE_ITEM_QUANTITY, INVOICE_ITEM_PRICE)

I need to create a transaction that 1). inserts data into a new CUSTOMER, 2). inserts data into a new INVOICE (invoice amount set to 0), 3). inserts data of two new INVOICE_ITEM (one row has INVOICE_ITEM_QUANTITY set to 2 and INVOICE_ITEM_PRICE to 5.00, the other to 1 and 10.00).
I can do all of this without any issue using insert commands, but the next step is tripping me up:
'Update the INVOICE_AMOUNT to add the line items added in step 3 to the INVOICE_ITEM_PRICE field. You must do this with a query that would work regardless if there were existing INVOICE_ITEM rows for this INVOICE.  Your query cannot hard code the amount.'
I can't figure out how I would go about doing this. I've been researching solutions, but haven't found anything that describes this problem, only ones that work if the column name is the same.
I could just insert the values directly into the INVOICE_AMOUNT, but then it would be considered hard coding the answer, correct? So I've been trying to do something along the lines of
UPDATE INVOICE
SET INVOICE_ITEM.INVOICE_ITEM_PRICE = INVOICE.INVOICE_AMOUNT
WHERE INVOICE.INVOICE_ID = INVOICE_ITEM.INVOICE_ID but I can't get any variation of this code to work. I'm sure there is some really simple answer that will make me feel stupid, but if anyone can help, I'd greatly appreciate it.

A: This might be a bit clunky but given what you have and no indication that PL/SQL is used then;
UPDATE invoice i
SET    i.invoice_amount = (SELECT SUM(ii.invoice_item_quantity * ii.invoice_item_price)
                           FROM   invoice_item ii
                           WHERE  ii.fk_invoice_id = 1.invoice_id)
WHERE  i.invoice_id = (SELECT MAX(invoice_id)
                       FROM   invoice
                       WHERE  fk_cust_id = (SELECT MAX(cust_id)
                                            FROM   customer) )

So . . .set the invoice amount to the sum of the qty * price for invoice items for the invoice. Just update the invoice records that have the latest invoice ID and that latest invoice is for the latest customer.
This assumes you are creating the PK values using a sequence (the invoice SHOULD be taking the latest invoice number and adding 1 to it). The others could be simple Oracle sequences.
                                            Sorry for the clunkiness but its a virtual Friday here and I'm about to go home.

A: You could just make a trigger that will be update invoice_ammount. Something like this:
CREATE OR REPLACE TRIGGER tg_invoice_item_amt
  AFTER
    DELETE OR
    INSERT OR
    UPDATE OF invoice_item_quantity, invoice_item_price
  ON invoice_item
  FOR EACH ROW
DECLARE
  l_change_amt NUMBER;
BEGIN
  CASE
    WHEN INSERTING THEN
      l_change_amt := COALESCE(:NEW.invoice_item_quantity * :NEW.invoice_item_price, 0);
    WHEN UPDATING THEN
      l_change_amt := COALESCE(:NEW.invoice_item_quantity * :NEW.invoice_item_price, 0)
                      - COALESCE(:OLD.invoice_item_quantity * :OLD.invoice_item_price, 0);
    WHEN DELETING THEN
      l_change_amt := 0 - COALESCE(:OLD.invoice_item_quantity * :OLD.invoice_item_price, 0);
  END CASE;
  IF l_change_amt != 0 THEN
    UPDATE invoice SET invoice_amount = invoice_amount + l_change_amt;
END;
/


text:
Q: How to use authentication on custom model in Laravel I'm making new custom model for user in laravel. I'm using the default User laravel model for one type of users that I will have, and new Merchant model for other type of users.
I make select option in the register view for chosing which type of user will be registered for better control in the controller.
<select id="user_type" name="user_type">
  <option value="user">User</option>
  <option value="merchant">Merchant</option>
</select>

This is my modified the default RegisterController for both type of users:
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Merchant;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function register(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        //Add custom code here
        $new_user = $this->create($request->all());
        //Add custom code here

        Auth::guard($this->getGuard())->login($new_user);

        return redirect($this->redirectPath());
    }

    protected function validator(array $data)
    {
        if($data['user_type']=='user'){
            return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'user_type' =>'required'
        ]);
        }else{
            return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'user_type' =>'required'
           ]);
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        if($data['user_type']=='user'){
            return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
       }else{
           return Merchant::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
       }

    }

}

To mention that register function is not by default in register controller, so I put that function because I already view that solution How to register more than one type of users and how to make multi auth in laravel 5.3 but I don't know how to modify that.
But the problem now is with the authentication after I submit the registration form. If I register new user it's working fine, but if I register merchant it saved the user in database and after that it doesn't log in the merchant if it doesn't exist any user in the users table. But if it already exist any user in the users after I register the merchant it log in the last user which is created in users table.
So my question is how to modify the authentication for merchant user.
Thank you!
UPDATE:
Register function
public function register(Request $request)
    {
         if($request->user_type =='user'){
                $auth = auth()->guard();
            } else{
                $auth = auth()->guard('merchant');
            }

            $user = $this->create($request->all());
            auth()->login($user);

            return redirect($this->redirectPath());

    }

A: *

*Go to /config/auth.php

*Find guards element of an array
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

*Add a guard merchant to this array with provider value of merchants
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'merchant' => [
        'driver' => 'session',
        'provider' => 'merchants',
    ],
],

*Now find providers element of this configuration
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
],

*Add merchants provider with model value of your Merchant model
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'merchants' => [
        'driver' => 'eloquent',
        'model' => App\Merchant::class,
    ],
],

*Now you can simply authenticate normal users via guard('web') and merchant users via guard('merchant')
And for you register function
public function register(Request $request)
{
    $guard = $request->user_type == 'user' ? 'web' : 'merchant';
    $user  = $this->create($request->all());

    auth()->guard($guard)->login($user);

    return redirect($this->redirectPath());
}

You can use packages too...
For example there's an awesome package: https://github.com/Sarav-S/Laravel-Multiauth
It will help you to handle all that hard stuff.

A: First You need to set new guard at auth.php. And when login using merchant change the guard method so Laravel will look into merchant instead of users.
    if($request->user_type =='user'){
        $auth = auth()->guard();
    } else{
        $auth = auth()->guard('merchant');
    }

    $auth()->login($user);

    return redirect($this->redirectPath());

https://laravel.com/docs/5.3/authentication


text:
Q: Does this converge: $\int_{3}^{\infty}\frac{\sin x \cdot \ln x\ \mathrm dx}{x^2\sqrt{x^2-4}}$ Can I use Dirichlet's test?
I know that$\displaystyle\int_{a}^{b}\sin x\le 1$.
Also,  $\displaystyle\frac{\ln x}{x^2\sqrt{x^2-4}}$ is monotonic.
Also, $\displaystyle\lim_{x\to \infty} \frac{\ln x}{x^2\sqrt{x^2-4}} =0$
Can then conclude that the series converges?

A: Yes, you can apply the Dirichlet test, since $
x \mapsto \dfrac{\ln x}{x^2\sqrt{x^2-4}}$is monotonic decreasing to $0$ over $[3, \infty)$ and
$
\left|\int_3^b \sin x \:dx\right|<2.
$

A: For large enough $x$, the integrand behaves like $\dfrac{\sin x\log x}{x^3}$.
Show that the integral of the modulus of this quantity, converges. You are done.

A: Actually , you do not need the Dirichlet test, because the integral is absolutely convergent: for $x\geq 3$,
$$0\leq\frac{|\sin x| \cdot \ln x}{x^2\sqrt{x^2-4}}\leq \frac{1\cdot x}{x^2\sqrt{x^2-4}}\sim\frac{1}{x^2}$$
and $\int_3^{+\infty} \frac{dx}{x^2}$ is convergent.

A: For $x\geq3$, you have $\ln (x)/\sqrt {x^2-4}<1$, so
$$
\int_3^\infty\left|\frac {\sin x\ \ln x}{x^2\,\sqrt {x^2-4 }}\right|\,dx
= \int_3^\infty\frac {|\sin x|\ \ln x}{x^2\,\sqrt {x^2-4 }}\,dx
\leq\int_3^\infty\frac  {1}{x^2}\,dx <\infty
$$
and the integral converges absolutely.


text:
Q: Double Encoded UTF-8 String - MySql, Hibernate We are saving a string in MySQL DB after encoding it using Base64 using hibernate.
Following is the code that does this:
    @Basic
    @Column(name = "name", nullable = false)
    @ColumnTransformer(read = "FROM_BASE64(name) ", write ="TO_BASE64(?)")
    public String getName()

Now, when I am saving rotebühlstr, this is getting saved in DB as cm90ZWLDvGhsc3Ry. When I print it on terminal, this is shown as rotebühlstr where as it should be rotebühlstr
This is a dropwizard project and config.yaml for mysql connection is as follow:
      properties:
      charSet: UTF-8
      characterEncoding: UTF-8
      useUnicode: true
      hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect
      hibernate.jdbc.batch_size: 100
      hibernate.envers.audit_table_suffix: "_aud"
      hibernate.id.new_generator_mappings: false

MySQL column description : name varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
    mysql> show variables like 'character_set_%';
    +--------------------------+---------------------------------------
    --------------------+
    | Variable_name            | Value
    |
    +--------------------------+---------------------------------------
    --------------------+
    | character_set_client     | utf8mb4
    |
    | character_set_connection | utf8mb4
    |
    | character_set_database   | utf8mb4
    |
    | character_set_filesystem | binary
    |
    | character_set_results    | utf8mb4
    |
    | character_set_server     | latin1
    |
    | character_set_system     | utf8
    |
    | character_sets_dir       | /usr/local/mysql-5.7.23-macos10.13-
    x86_64/share/charsets/ |
    +--------------------------+---------------------------------------
    --------------------+
    8 rows in set (0.01 sec)

Observation:

In my colleague's local set up, this is working fine. There,
  java/hibernate is treating input string in latin1 and not in UTF-8.
  so, rotebühlstr is encoded in DB as cm90ZWL8aGxzdHI= and decoded
  correctly as rotebühlstr.

^This was happening because of difference in character_set_server. It was set as latin1 in my local and as utf-8 in colleague's local.
What we have tried so far:

*

*Tried sending "Accept-Charset" as latin1. Didn't work.

*Tinkered with config.yaml file to change charset setting for mysql. Didnt work

What I can do now:
I can may be write a wrapper layer for encoding and decoding and stop using @ColumnTransformer. That way problem can be fixed.
Thanks.

A: I had a problem with charsets one time and the only charset could fix the problem was utf8mb4. As I can remember The problem arises from that utf8 cannot support some characters.
Additionally, for more information, you can check https://stackoverflow.com/a/43692337/2137378 too.

A: It works on your colleague, but not on your terminal, because yours is connected with latin1 charset, even though the database and field might be in utf8mb4.
You want to find your mysql config and add these options in their sections. Create the sections if they're missing.
[mysql]
default-character-set=utf8mb4

[client]
default-character-set=utf8mb4

[mysqld]
character_set_server = utf8mb4
collation_server = utf8mb4_general_ci

Exit any clients, restart the server and you should be fine. Also from now on when you do a show create database or show create table you will see when it's the wrong encoding.


text:
Q: conv across dimensions matlab I have a 3D volume and I want to apply a gaussian filter (with conv) on the first dimension.
That means that I want each column to be convolved with the filter independently.
I need something like:
result = conv(cube, Gfilter, 1 ,'same')

What I tried is padding with zeros the cube's columns (to the size of the filter width) and then used:
conv(cube(:), Gfilter)

but this is too memory/time consuming !
Thanks
Matlabit

A: For convolution among one dimension, you can still use convn. I assume here that Gfilter is a k-by-1 array.
result = convn(cube,Gfilter,'same');


text:
Q: codepen bootstrap mobile version wrong I am getting the hang of bootstrap and so far its been awesome.
I tried to make my site from mobile first then up. But I guess I did something wrong or missed a step. When I view the page in codepen where I built it it looks fine at any width. However, when I look at it through my iPhone or jsfiddle the works side looks totally wrong, they're not aligned and they're just all over the place. I wanted to have my items in 2 rows when the screen is xs or sm, and have three columns when the device is md and 4 columns when the device is lg. It seems that the sm,md,lg parts are working how they should but not the xs.
Also, when the viewport is small enough for the navbar is collapsed, how can I remove it once I click on something in it. Example I expand it and click projects, it goes to that section but it doesn't remove it.

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navie" aria-expanded="false">
            Toggle navigation

          </button>
          PORTFOLIO

Home

About

Projects

Contact

About

            Hi there! My name is Irving Gonzalez and I am a Computer Science graduate from John Jay College of Criminal Justice. Currently, I am working towards becoming a Full Stack Web Developer with the help of the curriculum from freeCodeCamp            as well as other self-taught web services. I have a passion for innovation, deviation, technology, and languages.

 Below are some of the projects I've made.

Works

Random Quotes

Calculator

Tribute

Weather App

Future Project

Future Project

Future Project

Future Project

 CONTACT

            If you have any questions and/or comments, feel free to send me a message through any of these

@ 2016 Irving Gonzalez

A: Use the grid
The main problem here appears to be the lack of rows in your layout, or more specifically everything being in a single
. Cols can handle collapsing most of the time, but in your case some of your project names wrap to two lines when on a small enough viewport, causing the height of the containers to mismatch and throwing the layout off. If you wrap every row of cols in a, well, row, this won't happen as the cols will have a direct container to align themselves with.
This could be fixed by messing with the headings and font-sizes, but really, the safest way to ensure your layout will keep its rows and cols is to explicitly define them instead of implying them like in your code.
Additional note
Also, please put your section headings in a separate row/col. I'm talking about these parts:
...

Works

...

should be
...

Works

...

You are somehow getting away with it in this case, but non-floated non-col elements should have their own row + full-width col or stay outside of rows with floated/col elements inside them, otherwise strange things can happen.
Automatically collapse navbar on menu item click
This should be a separate question to keep with SO's single Q/A format - regardless, here is a solution to it: simply emulate a click event on the navbar collapse button after a link has been clicked (or you could use bootstrap's js methods but I'll leave that up to you).
$('.nav li a').on('click', function() {
    $('.navbar-toggle').trigger('click');
})


text:
Q: How do i map a column in a dataframe using a nested dictionary? I have created this nested dictionary for certain trading strategies, say:
{'Strategy1' :{'AAPL':'Strategy1_APPLE', 'MSFT':'Strategy1_MICROSOFT'}, 'Strategy2' :{'AAPL': 'Strategy2_APPLE', 'MSFT':'Strategy2_MICROSOFT'}}

I already built a dataframe with a list of trades that belong to either strategy1 or strategy2 and have made a column with that information. What i am then trying to do is map the values in the dict to a new column based on both the top level key (i.e. strategy1 or strategy2) and the nested key(i.e. AAPL or MSFT). So that every single trade is accompanied by its correct strategy and ticker in the same row of the dataframe.
So a row in the dataframe with Strategy1 and AAPL gets a value of Strategy1_APPLE in the new column, but Strategy2 and AAPL gets Strategy2_APPLE.
I have been playing around with both map() and a bunch of lambda functions but i can't get this to work. I think this is possible without doing a bunch of ugly loops and if statements and i could really use some help on how to do that here.
edit: example
So it currently looks like this
  ticker Strategies
1   AAPL  Strategy1
2   MSFT  Strategy1
3   MSFT  Strategy2
4   AAPL  Strategy1
5   MSFT  Strategy2

and the desired result is this
  ticker Strategies          substrategy
1   AAPL  Strategy1      Strategy1_APPLE
2   MSFT  Strategy1  Strategy1_MICROSOFT
3   MSFT  Strategy2  Strategy2_MICROSOFT
4   AAPL  Strategy1      Strategy1_APPLE
5   MSFT  Strategy2  Strategy2_MICROSOFT

Note that concatenating the strings or something like that doesn't work for my actual problem where the substrategy names are a lot more complicated

A: use a method:
def get_substrategy(t,s):
    v = mydict[s][t]
    return v

and than apply a lambda:
df['substrategy'] = df.apply(lambda x: get_substrategy(x['ticker'], x['Strategies']), axis=1)

desired result
   ticker   Strategies  substrategy
1   AAPL    Strategy1   Strategy1_APPLE
2   MSFT    Strategy1   Strategy1_MICROSOFT
3   MSFT    Strategy2   Strategy2_MICROSOFT
4   AAPL    Strategy1   Strategy1_APPLE
5   MSFT    Strategy2   Strategy2_MICROSOFT

Note: make sure to try catch in your function in the event the strategy/ticker doesn't exist
Note2: without the function:
df['substrategy'] = df.apply(lambda x: mydict[x['Strategies']][x['ticker']], axis=1)

but you'll need to consider a scenario where the strategy/ticker doesn't exist.

A: I will use reindex + MultiIndex, d is your dict here
df['New']=pd.DataFrame(d).stack().reindex(pd.MultiIndex.from_frame(df)).values
df
  ticker Strategies                  New
1   AAPL  Strategy1      Strategy1_APPLE
2   MSFT  Strategy1  Strategy1_MICROSOFT
3   MSFT  Strategy2  Strategy2_MICROSOFT
4   AAPL  Strategy1      Strategy1_APPLE
5   MSFT  Strategy2  Strategy2_MICROSOFT

A: Here, another way using the pandas.DataFrame constructor, with reshaping and merge:
d1 = (pd.DataFrame(d).rename_axis(index='ticker',columns='Strategies')
                     .stack()
                     .rename('substrategy')
                     .reset_index())
df.merge(d1)

Output:
|    | ticker   | Strategies   | substrategy         |
|---:|:---------|:-------------|:--------------------|
|  0 | AAPL     | Strategy1    | Strategy1_APPLE     |
|  1 | AAPL     | Strategy1    | Strategy1_APPLE     |
|  2 | MSFT     | Strategy1    | Strategy1_MICROSOFT |
|  3 | MSFT     | Strategy2    | Strategy2_MICROSOFT |
|  4 | MSFT     | Strategy2    | Strategy2_MICROSOFT |

A: I would recommend looking into a better way to store your data if a dataframe is your target. To convert your existing structure into a more dataframe friendly format (and achieve the target dataframe you want):
import pandas as pd

# input nested dict in OP
source_dict = {'Strategy1' :{'AAPL':'Strategy1_APPLE', 'MSFT':'Strategy1_MICROSOFT'}, 'Strategy2' :{'AAPL': 'Strategy2_APPLE', 'MSFT':'Strategy2_MICROSOFT'}}
tmp_rows = []

# convert nested-dict to pandas friendly input format
for strategy in source_dict.keys():
    for ticker in source_dict[strategy].keys():
        substrategy = source_dict[strategy][ticker]
        tmp_rows.append({'ticker': ticker, 'Strategies': strategy, 'substrategy': substrategy})

# create output dataframe
output_dataframe = pd.DataFrame(tmp_rows)

print(output_dataframe.head(10))


text:
Q: Convert Dictionary of List of Dictionaries to a Pandas Dataframe I have a dictionary in the structure given below and I need to convert it into a Pandas Dataframe to do some aggregation operations. But I couldn't able to convert it into given output format
{
  "raj": [
    {
      "subject": "science",
      "score": "35",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "40",
      "create_time": "1595980800000"
    }
  ],
  "dev": [
    {
      "subject": "science",
      "score": "23",
      "create_time": "1595990288421"
    }
  ],
  "mag":[
    {
      "subject": "science",
      "score": "41",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "25",
      "create_time": "1595980800000"
    }
  ]
}

I need the output dataframe to be in the given format
name    subject     score   create_time
------------------------------------------
raj     science     35      1595990288421
raj     maths       40      1595980800000
dev     science     23      1595990288421
mag     science     35      1595990288421
mag     maths       25      1595980800000

Can anyone help me convert the dictionary into required dataframe output ?

A: Using a list comprehension
Ex:
df = pd.DataFrame([{'name': k, ** j} for k, v in data.items() for j in v])
print(df)

Output:
  name  subject score    create_time
0  raj  science    35  1595990288421
1  raj    maths    40  1595980800000
2  dev  science    23  1595990288421
3  mag  science    41  1595990288421
4  mag    maths    25  1595980800000


text:
Q: MongoDB aggregate query to SpringDataMongoDB I have below MongoDB aggregate query and would like to have it's equivalent SpringData Mongodb query.
MongoDB Aggregate Query :
db.response.aggregate(
        // Pipeline
        [
            // Stage 1 : Group by Emotion & Month
            {
                $group: {
                    _id: {
                        emotion: "$emotion",
                        category: "$category"
                    },
                    count: {
                        $sum: 1
                    },
                    point: {
                        $first: '$point'
                    }
                }
            },
            // Stage 2 : Total Points
            {
                $addFields: {
                    "totalPoint": {
                        $multiply: ["$point", "$count"]
                    }
                }
            },
                        // Stage3 : Group By Category - Overall Response Total & totalFeedbacks
            {
                $group: {
                    _id: '$_id.category',
                    totalFeedbacks: {
                        $sum: "$count"
                    },
                    overallResponseTotal: {
                        $sum: "$totalPoint"
                    }
                }
            },
                        // Stage4 - Overall Response Total & totalFeedbacks
            {
                $project: {
                    _id: 1,
                    overallResponseTotal: '$overallResponseTotal',
                    maxTotalFrom: {
                        "$multiply": ["$totalFeedbacks", 3.0]
                    },
                    percent: {
                        "$multiply": [{
                            "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                        }, 100.0]
                    }
                }
            },
                        // Stage4 - Percentage Monthwise
                {
                    $project: {
                        _id: 1,
                        overallResponseTotal: 1,
                        maxTotalFrom: 1,
                        percent: {
                            "$multiply": [{
                                "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                            }, 100.0]
                        }
                    }

                }
            ]
);

I have tried it's equivalent in Spring Data but got stuck at Stage 2 on how to convert "$addFields" to java code. Though I search about it on multiple sites but couldn't find anything useful. Please see my equivalent java code for Stage 1.
//Stage 1 -Group By Emotion and Category and return it's count

GroupOperation groupEmotionAndCategory = Aggregation.group("emotion","category").count().as("count").first("point")
                        .as("point");

Aggregation aggregation = Aggregation.newAggregation(groupEmotionAndCategory);

AggregationResults<CategoryWiseEmotion> output = mongoTemplate.aggregate(aggregation, Response.class, CategoryWiseEmotion.class);

Any helps will be highly appreciated.

A: $addFields is not yet supported by Spring Data Mongodb.
One workaround is to pass the raw aggregation pipeline to Spring.
But since you have a limited number of fields after stage 1, you could also downgrade stage 2 to a projection:
{
    $project: {
        // _id is included by default
        "count" : 1, // include count
        "point" : 1, // include point
        "totalPoint": {
            $multiply: ["$point", "$count"] // compute totalPoint
        }
    }
}

I haven't tested it myself, but this projection should translate to something like:
ProjectionOperation p = project("count", "point").and("point").multiply(Fields.field("count")).as("totalPoint");

Then you can translate stage 3, 4 and 5 similarly and pass the whole pipeline to Aggregation.aggregate().


text:
Q: Self table comparison I Have a table emp which has
ename sal
Smith 1000
Mark  2000
Jack  500

The output should be(person earning lower salary on the left)
Jack Smith
Jack Mark
Smith Mark

Please help

A: Seems like a cross join with a filter.
select h1.ename as first, h2.ename as second
from have as h1
cross join have as h2
where h1.sal>h2.sal


text:
Q: ajax on update data in database using codeigniter  <button id="survey_act" method="post" class="tiny ui blue button" type="button" value="<?php echo $surv['id']; ?>"  >Activate Survey</button>

This is my button on click -
<script>
$(document).ready(function(){
       $(document).on("click","#survey_act", function(){
           alert(this.value);
                idx = this.value;

    $.ajax({
       type: "POST",
       url: "<?php echo base_url('index.php/admin/survey/act_surveyby_id/')?>/"+idx,

      }).done(function(msg){
            if(msg=="success"){
                      alert('You Successfully Activated the Survey!');
             }

                   });
             });
     });

    </script>

This is my javascript -
   public function act_surveyby_id($id){
    $this->load->model('survey_m');
    if($this->survey_m->insert_activate($id)){
                echo "success";

    }else{

        echo "invalid";
    }
}

This is my controller -
         public function insert_activate($id){

                $date = date('m-d-Y',now());
                $stat = 'Active';

                        $data = array(
                                   'issued_date' =>  $date ,
                                   'status' => $stat
        );

                     $this->db->update('survey', $data)->where('survey_id', $id);
    if($this->db->affected_rows()>0){
            return true;
        }else{
                    return false;

                }

    }

  }

This is my model -
Problem: when i click the activate survey it wont change/update the details of the survey. I really badly need a help regarding with this. Thanks . . .

A: change $.ajax function like below
$.ajax({
       url: '<?php  echo base_url(); ?>index.php/admin/survey/act_surveyby_id',
       type: "POST",
       data: {
             idx : idx;
             },

and controller like below
public function act_surveyby_id(){
    $id=$_POST['idx'];
    $this->load->model('survey_m');
    if($this->survey_m->insert_activate($id))
    {
      echo "success";

    }else{

        echo "invalid";
    }
}


text:
Q: Why does the proprietary nvidia driver break kernel dependencies? I'm running Fedora 25, with the following nvidia packages installed:
akmod-nvidia.x86_64                     1:375.26-1.fc25                 @rpmfusion-nonfree-updates
kmod-nvidia-4.8.12-300.fc25.x86_64.x86_64
kmod-nvidia-4.8.14-300.fc25.x86_64.x86_64
xorg-x11-drv-nvidia.x86_64              1:375.26-1.fc25                 @rpmfusion-nonfree-updates
xorg-x11-drv-nvidia-cuda.x86_64         1:375.26-1.fc25                 @rpmfusion-nonfree-updates
xorg-x11-drv-nvidia-kmodsrc.x86_64      1:375.26-1.fc25                 @rpmfusion-nonfree-updates
xorg-x11-drv-nvidia-libs.x86_64         1:375.26-1.fc25                 @rpmfusion-nonfree-updates

Whenever I run dnf upgrade, I get the following message:
Skipping packages with broken dependencies:
 kernel                                                       x86_64                                   4.8.15-300.fc25                                        updates                                         92 k
 kernel-core                                                  x86_64                                   4.8.15-300.fc25                                        updates                                         20 M
 kernel-modules                                               x86_64                                   4.8.15-300.fc25                                        updates                                         22 M

But if I remove all my nvidia packages, then I can run dnf upgrade no problem. I can install the nvidia packages again, after the kernel upgrade, no problem.
Why do the nvidia packages break kernel dependencies, and how can I stop that from happening?

A: It is most likely kmod-nvidia that is lagging behind.
You can either wait for the kmod-nvidia package for kernel 4.8.15 to be ready, or remove kmod-nvidia-* completely and let akmod-nvidia handle the making of the kernel modules.
I have done the latter on my nvidia based systems.


text:
Q: Flask request.get_json() returning None when valid json data sent via post request Building an app using flask. The app uses a table structure to display data. Part of its functionality is collecting the data from user specified table rows. To do this I have placed a button on each row that executes some js. The js collects the information from the row, uses JSON.stringify() to convert to json object and the issues the post request to the relevant flask url.
Logging the value of the jsonified object to the browser console from js file shows it is correctly formed. The post request contacts the correct route however the request.get_json() function returns a value of None in the method of that route.
I have set up a seperate route in flask for testing. Here is the relevant code
from javascript
    function do_some_work(e) {
        var row_data = get_table_row_data(e);
        row_data = JSON.stringify(row_data);
        console.log(row_data);
        $.post("test", row_data);
    }

get_table_row_data() simply returns an object with key:value pairs. The log shows the data is correctly formatted json.
And here is the python code
#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
    data = request.get_json()
    print("data is "+format(data))
    return redirect(url_for('index'))

Here data is coming up as None
any help much appreciated

A: It's request.json it will return a dictionary of the JSON data. To get a value you use request.json.get('value_name'). So your route will be like this
#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
    data = request.json
    print("data is " + format(data))
    return redirect(url_for('index'))


text:
Q: How Xcode Convert var names to View Names in Storyboard I would like to know if there is any easy way to do this
Here is the value name
Here is the View Name
I want to know how to do this programmatically, is there any easy way?
Preferably in Swift, obj-C will do too
Thank you

A: I managed to do it, for those ho will need this information one day:
 let string = "theMostInterestingViewOfAllTime"  //Default String
 var newString = string.stringByReplacingOccurrencesOfString("([a-z])([A-Z])", withString: "$1 $2", options: .RegularExpressionSearch, range:string.rangeOfString(string)) //Here the String will be separated
 newString = newString.capitalizedString //Here it will be capitalized

New Range gave me some problems - is there a more elegant way, compared to my version?


text:
Q: using QWebEngine without margins I am trying to get QWebEngine to fill the entire window. Per this answer I am trying to use setContentsMargins(0,0,0,0); with the result below: the QWebEngine loads the page at full window size but then immediately scales down to this:

When I use setContentsMargins(1,1,1,1); with the QWebEngine in the layout, it loads correctly, with a 1 px margin. I did a test of just loading the image directly, with no margin and it loaded fine and filled the screen.
Is this my bug/issue or QWebEngine's?

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWebEngineWidgets>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0,0,0,0);
    ui->centralWidget->setLayout(mainLayout);

//    // load and show image
//    inputImg = new QImage(":/images/testScreen.jpg");
//    imgDisplayLabel = new QLabel("");
//    imgDisplayLabel->setPixmap(QPixmap::fromImage(*inputImg));
//    imgDisplayLabel->adjustSize();
//     mainLayout->addWidget(imgDisplayLabel);

    view = new QWebEngineView(this);
     mainLayout->addWidget(view);

    QUrl url;
    url = QUrl("qrc:/testScreen.html");
    view->load(url);
}

A: This is working for me but I'm testing on windows platform.
I inlined the constructor definition here for brevity.
class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow() {
        auto webView = new QWebEngineView(this);
        auto main_layout = new QVBoxLayout(this);
        main_layout->setMargin(0);
        main_layout->addWidget(webView);
    }
};

And the html is like this:
<!DOCTYPE html>
<html style="width: 100%; height: 100%; margin: 0; padding: 0">
  <body style="overflow: hidden; width: 100%; height: 100%; margin: 0; padding: 0">
  </body>
</html>