text:
Q: AWS - Create a record set for an s3 static website I have a static website up and running at
http://volcalc.s3-website-ap-southeast-2.amazonaws.com/
It is stored on an aws S3 bucket.
I have bought the domain volcalc.io
I just want to switch to use that as the url of my website.
I'm following the instructions here. I'm doing "Create record sets".
I'm trying to create a record set but when I check the radio button "yes" for "alias" then I try to enter an "alias target" there are no options to select from and the tutorial is saying there should be:

So I just tried to paste in this: http://volcalc.s3-website-ap-southeast-2.amazonaws.com/
and click create but it says:

The record set could not be saved because:
  - Alias Target contains an invalid value.

What do I enter into alias target? Why aren't there any options to select from?

A: You will need to point your alias record to the resource, not the endpoint :
ALIAS : s3-website-ap-southeast-2.amazonaws.com

A: Steps required:

*

*Create a bucket with the name of the desired domain (eg A bucket called volcalc.io)

*Turn on Static Website hosting

*Create a Route 53 record set with Alias=Yes and select the static website from above

See: Routing Traffic to a Website that Is Hosted in an Amazon S3 Bucket

A: I know you might have solved the issue, but for the people who see this post:
If you cannot find the endpoint on the list, simply copy and paste it there.
Also you would need to remove the bucket name from your end point.
only input this part:  s3-website-ap-southeast-2.amazonaws.com/
Route 53 will find a bucket that has your exact domain name.

A: If you are trying to create the record but your s3 bucket is not showing up,
check that the bucket name matches the name of the subdomain / domain you are trying to setup.
For example, if my subdomain is www.passioncloud.net then I must make sure the name of my bucket is also www.passioncloud.net .
See: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RoutingToS3Bucket.html


text:
Q: C strings declarations I'm learning C and today I stuck with the "strings" in C. Basically I understand that there is no such thing like string in C.
In C strings are an array characters terminated with \0 at the end.
So far so good.
char *name = "David";
char name[] = "David";
char name[5] = "David";

This is where confusing starts. Three different ways to declare "strings". Can you provide me with a simple examples in which situations which one to use. I've read a lot tutorials on the web but still can't get the idea.
I read this How to declare strings in C question on stackoverflow but still can't get the difference..

A: *

*First one char *name = "David"; is string literal and is resides in read only section of memory. You can't do any modification to it. Better to write
const char *name = "David";

*Second one char name[] = "David"; is a string of 6 chars including '\0'. Modification can be done.

*char name[5] = "David"; invoke undefined behavior. "David" is a string of 6 chars (including terminating '\0'). You need an array of 6 chars to store it.
char name[6] = "David";
Further reading: C-FAQ 6. Arrays and Pointers.

A: This link provides a pretty good explanation.
char[] refers to an array, char* refers to a pointer, and they are not the same thing.
char a[] = "hello"; // array
char *p = "world"; // pointer

According to the standard, Annex J.2/1, it is undefined behavior when:

—The program attempts to modify a string literal (6.4.5).

6.4.5/5 says:

In translation phase 7, a byte or code of value zero is appended to
  each multibyte character sequence that results from a string literal
  or literals.

Therefore you actually need an array of six elements to account for the NUL character.

A: In the first example, you declare a pointer to a variable:
// A variable pointer to a variable string (i.e. an array of 6 bytes).
char *pName = "David";

At this time, you can modify the 6 bytes occupied by 'D', 'a', 'v', 'i', 'd', '\0':
pName[0] = 'c';
*pName = 'c';
*(pName+0) = 'c';
strcpy(pName, "Eric"); // Works well

But ONLY those 6 bytes:
// BUG: Will overwrite 2 random bytes located after \0 in RAM.
strcpy(pName, "Fredrik");

The pointer can be altered runtime to point to another variable string e.g.
pName = "Charlie Chaplin";

Which then can be modified
pName[0] = 'c';
*pName = 'c';
*(pName+0) = 'c';
// OK now, since pName now points to the CC array
// which is 16 bytes located somewhere else:
strcpy(pName, "Fredrik");

As stated by others, you would normally use const char * in the pointer cases, which also is the preferred way to use a string. The reason is that the compiler will help you from the most common (and hard-to-find) bugs of memorytrashing:
// A variable pointer to a constant string (i.e. an array of 6 constant bytes).
const char *pName = "David";
// Pointer can be altered runtime to point to another string e.g.
pName = "Charlie";
// But, the compiler will warn you if you try to change the string
// using any of the normal ways:
pName[0] = 'c';       // BUG
*pName = 'c';         // BUG
*(pName+0) = 'c';     // BUG
strcpy(pName, "Eric");// BUG

The other ways, using an array, gives less flexibility:
char aName[] = "David"; // aName is now an array in RAM.
// You can still modify the array using the normal ways:
aName[0] = 'd';
*aName = 'd';
*(aName+0) = 'd';
strcpy(aName, "Eric"); // OK

// But not change to a larger, or a different buffer
aName = "Charlie"; // BUG: This is not possible.

Similarly, a constant array helps you even more:
const char aName[] = "David"; // aName is now a constant array.
// The compiler will prevent modification of it:
aName[0] = 'd';       // BUG
*aName = 'd';         // BUG
*(aName+0) = 'd';     // BUG
strcpy(aName, "Eric");// BUG
// And you cannot of course change it this way either:
aName = "Charlie"; // BUG: This is not possible.

The major difference between using the pointer vs array declaration is the returned value of sizeof(): sizeof(pName) is the size of a pointer, i.e. typically 4. sizeof(aName) returns the size of the array, i.e. the length of the string+1.
It matters most if the variable is declared inside a function, especially if the string is long: It occupies more of the precious stack. Thus, the array declaration is normally avoided.
It also matters when passing the variable to a macros which use sizeof(). Such macros must be supplied with the intended type.
It also matters if you want to e.g. swap the strings. Strings declared as pointers are straight-forward and requires the CPU to access less bytes, by simply moving the 4 bytes of the pointers around:
const char *pCharlie = "Charlie";
const char *pDavid = "David";
const char *pTmp;

pTmp = pCharlie;
pCharlie = pDavid;
pDavid = pTmp;

pCharlie is now "David", and pDavid is now "Charlie".
Using arrays, you must provide a temporary storage large enough for the largest string, and use strcpy(), which takes more CPU, copying byte for byte in the strings.
The last method is rarely used, since the compiler automatically calculates that David needs 6 bytes. No need to tell it what's obvious.
char aName[6] = "David";

But, it is sometimes used in cases where the array MUST be a fixed length, independent of its contents, e.g. in binary protocols or files. In that case, it can be of benefit to manually add the limit, in order to get help from the compiler, should anyone by accident add or remove a character from the string in the future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image impact on application memory usage i am trying to figure the memory usage impact of an image to an application. I am loading an image in memory from a byte array and i notice that the memory usage is not proportional to the image's size.
I have a byte array of 96389 bytes that i convert to an image in the following ways:
var actualImage = (Bitmap)((new ImageConverter()).ConvertFrom(bytes));
var actualImage = Image.FromStream(new System.IO.MemoryStream(bytes));

I would expect the application's memory usage to increase by an equal amount but in reality what happens is that the application's memory increases by 17324 kilobytes.
Why is this happening and how can i avoid using too much memory?

A: Probably, the image stored in bytes is compressed. Images are not compressed in memory inside of the Bitmap class. Nothing you can do about that if you want to make use of the pixels.

A: It simply means that your original picture is compressed. In uncompressed bitmap representation, an image uses 4 bytes per pixel (one for each channel red/green/blue, and one for alpha channel).

How to avoid using too much memory?

It depends on what you're trying to do. Reduce the picture resolution, load only a portion of it, etc... But if you need to display the full picture at the original resolution, then there's no way to reduce the amount of memory used.


text:
Q: why Radio Button size() showing 0 in Selenium? WebDriver driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio");
List<WebElement> radio_buttons = driver.findElements(By.name("gender"));
System.out.println(radio_buttons.size());

A: Those elements are inside <iframe id="iframeResult" frameborder="0">. You need to switch to iframe first:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio");

WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iframeResult")));

List<WebElement> radio_buttons = driver.findElements(By.name("gender"));
System.out.println(radio_buttons.size());


text:
Q: Saving javascript code inside database I've very annoying problem with hosting of well known company however
I've website and at its back-end there is form has textarea field where it should be for google adsense code when i submit it does not respond at all and keep loading
but when i type anything else then adsense ads code it accepted so i noticed it not allowing for html
Form code
<form method=post action="1.php" name="adsense" id="adsense">

The Code : <textarea id="ad" name="ad">Put your code here</textarea>

<input type="submit" name="submit" value="Save">

</form>

1.php Code
<?PHP

include "header.php"; // connect to db

if(isset($_POST[submit])){

$qma = "update webads set
ad = '$_POST[ad]'";

$rma = mysql_query($qma) or die(mysql_error());
echo 'Thanks';

}

?>

The problem when i put adsense ads code it not respond and not save it in database but if i put any text it save it normally
so i've been thinking to addslashes() but it also didn't worked after i made such changes
ad1 = 'addslashes($_POST[ad1])'

here is example of unaccepted google adsense code
<script type="text/javascript">
google_ad_client = "pub-0000000000000000";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text";
google_ad_channel = "0000000000";
google_color_border = "FFFCE1";
google_color_bg = "FFFCE1";
google_color_link = "FFFCE1";
google_color_text = "FFFCE1";
google_color_url = "FFFCE1";
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

One last note
the database field structure is text NOT NULL
CREATE TABLE `webads` (
`id` varchar(50) NOT NULL default '',
`ad` text NOT NULL
PRIMARY KEY  (`id`))";

so any idea how to save it ! but it must be easy to recall it back without being altered
i don't know if it stupid or not but if i didn't got any answer how to do it, been thinking to base_64 encoder before save it then when i call it back will base_64 decode it but this sound last hope i can do
Thanks a lot

A: You need to escape the posted variable for MySQL - the best way to do this is to use PHP's built in function as it will do it correctly for your version of MySQL
$qma = "update webads set ad = '" . mysql_real_escape_string($_POST[ad]) . "'";

A: You have to use htmlentities before storing data to database.
and you can't use function inside string.
$ad = htmlentities($_POST['ad']);

Also when using addslashes you'd better first check if it's automatically enabled by server configuration, not to over-quote strings. See get_magic_quotes_gpc
if(!get_magic_quotes_gpc()) {
    $ad = addslashes($ad);
}

...

$qma = "update webads set ad = '$ad'";

A: Alternately, you can use
$ad = htmlspecialchars($_POST['ad']);

$qma = "update webads set ad = '$ad'";

A: When I work with MySQL Workbench and I do something like update webads set
ad = '$_POST[ad]' it throws an error because of the safe mode. My SQL query doesn't have an ID. Maybe the safe mode is on?
If you want to bypass it, just add WHERE ID != -1 but I don't recommend doing this.
Don't forget to sanitize your input.


text:
Q: Exported word doc gets saved as htm I'm using html_to_doc to export html to .doc format which all works fine.
But the problem I'm having is that when I open the document and go to Save As the default document type is always .htm / .html.
I'm using Linux and I'd like to keep using this class if possible. These are the set headers in PHP:
@header("Cache-Control: ");// leave blank to avoid IE errors
@header("Pragma: ");// leave blank to avoid IE errors
@header("Content-type: application/octet-stream");
@header("Content-Disposition: attachment; filename=\"$this->docFile\"");

and the DOC header (without style):
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 9">
<meta name=Originator content="Microsoft Word 9">
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]-->
<title>$this->title</title>
<!--[if gte mso 9]><xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:DoNotHyphenateCaps/>
<w:PunctuationKerning/>
<w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing>
<w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing>
</w:WordDocument>
</xml><![endif]-->
<!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1032">
<o:colormenu v:ext="edit" strokecolor="none"/>
</o:shapedefaults></xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]-->
$this->htmlHead
</head>


text:
Q: How to understand the JavaScript code generated by CoffeeScript's `extends` keyword This is the JavaScript code generated by CoffeeScript's extends keyword. How the prototype chain gets setup?
var __hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) {
    for (var key in parent) {
        if (__hasProp.call(parent, key)) child[key] = parent[key];
    }
    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
};

A: var __hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) {
    // Copy "static" attributes from the parent constructor to the child constructor
    for (var key in parent) {
        if (__hasProp.call(parent, key)) child[key] = parent[key];
    }
    // This is the surrogate constructor, used so you don't need
    // to instantiate an instance of the parent just to setup the prototype chain
    // the statement in the surrogate constructor properly attaches
    // the constructor property to object
    function ctor() { this.constructor = child; }
    // Attach the parent's prototype to the surrogate constructor
    ctor.prototype = parent.prototype;
    // This is setting up the chain, attaching an instance of a constructor whose
    // prototype is set to the parent to the prototype property of the child
    // In naive implementations, this would be child.prototype = new parent();
    child.prototype = new ctor;
    // Allows access to the parent from user code, and used by the `super` keyword
    child.__super__ = parent.prototype;
    return child;
};

See http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html (my own blog post)


text:
Q: sqlite between operator does not return rows in db When I use this query:
SELECT count(*) FROM verdicts WHERE Age BETWEEN 10 AND 20

I get 17 rows. But when I use this query:
SELECT count(*) FROM verdicts WHERE Age BETWEEN 7 AND 20

I get 0 rows. I know there are additional rows that should be caught by the second query. And the second query should be catching all the rows the first query catches. Does anyone know what could be happening?
The age column contains almost all ints except a couple text values such as:
0-10, 10-20, etc.
Could this be my problem?

A: I suspect Age is stored as a string.  That is a bad, bad thing.  So, your comparison is really:
where Age between '7' and '20'

Because '7' is greater than '20', between returns nothing (the smaller value goes first).
Basically, there is not that much you can do with your data.  You should really fix the data format.  Here are possibilities:

*

*Store Age as a number.

*Have numeric columns for MinAge and MaxAge if you are dealing with ranges.

*If you must use strings, then zero pad them so they are the same length:  '007' instead of '7'.

If you do the last, then this will work:
where Age between '007' and '028'


text:
Q: GNOME 3: Changing datetime format for lock screen? I'm using GNOME Shell 3.22.3 on Debian GNU/Linux 9 (stretch).
I've edited the settings for the way time and date is displayed in the Status bar using the excellent Datetime format extension. However, I haven't been able to find any way to configure the way the time and date is displayed when I lock the computer. It's always:

HH:MM:SS
weekday, DD month

I suppose this is set by my locale somehow, as the weekday is indeed displayed in my local language as set for the OS.
I'd like to change this, for example removing the leading zero. Is there any way of doing this?


text:
Q: Is there a way to disable stdout logging for AWS java SDK 2.0. for S3 Bucket upload Is there a way to disable the stdout responses when uploading to an s3 bucket? We currently log stdout, and as you can imagine this creates a lot of noise in our logs, and basically fills it up. Because of what we are using the S3 upload for it also creates an endless loop of uploading archived log files to the s3 bucket. We are using the AWS Java SDK 2.0. I am a little lost as to how this can be done, so any help will be appreciated. I see that it is logging out "http-outgoing-7 >>" as it uploads the file.

Thanks
Here is a section of the code:
  private void setUpS3Client() {

S3Client s3Client = S3Client.builder()
    .credentialsProvider(createStaticCredentialsProvider())
    .region(Region.of(properties.get(IS3Constants.PROPERTY_REGION)))
    .build();

this.s3Client = s3Client;
}

  private StaticCredentialsProvider createStaticCredentialsProvider() {
AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(properties.get(IS3Constants.PROPERTY_KEY_ID), properties.get(IS3Constants.PROPERTY_ACCESS_KEY));
StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(awsBasicCredentials);
return credentialsProvider;

}

private void putS3Object(S3BucketRequest bucketRequest) throws IOException, GenericException {
    PutObjectRequest putObjectRequest = PutObjectRequest.builder()
    .bucket(bucketName)
    .key(fileName)
    .build();

byte[] objectByteArray = getObjectByteArray(bucketRequest.getFilePath());
if (objectByteArray == null || objectByteArray.length == 0) {
  Logger.logln(Logger.DEBUG, "Nothing to upload for " + bucketRequest.getFilePath());
}
PutObjectResponse putObjectResponse = s3Client.putObject(putObjectRequest, RequestBody.fromBytes(objectByteArray));
String eTag = putObjectResponse.eTag();
}

A: I was able to solve this by reconfiguring "logback". I set the logs coming in from "org.apache.http" to 'WARN'. For me, by default, it was set to debug.
https://stackoverflow.com/a/51181745/5275728


text:
Q: how to implement the example of letter 'A' in the wiki of nonlinear dimensionality reduction When I read the wiki of nonlinear dimensionality reduction(https://en.wikipedia.org/wiki/Nonlinear_dimensionality_reduction), I found the interesting example of letter 'A', so I want to implement it using python, but I get some problems here. The code I use to generate the data is:
import matplotlib.pyplot as plt
for scale in range(15):
    for rot in range(50):
    fig = plt.figure(figsize=(2, 2.05),facecolor='w')
    ax=plt.axes([0,0,1,1],frameon=False,xticks=[],yticks=[])
    ax.text(0.5,0.5,'A',fontsize=150-scale*5,family='Times New Roman',
            fontdict={'ha':'center', 'va':'center'},
            rotation=rot*3.6)
    fig.savefig('./letterA/'+str(scale)+'s_r'+str(rot)+'.png',dpi=16)

Then I use pca and manifold sculpting in the Waffles packages to do dimensionality reduction, but I get different results from the figure on the wiki.


text:
Q: Generate multiple charts based on json in angular 8 I am using high charts in angular 8.I am getting chart for single object in an array of objects but i want to  get each chart for each object dynamically how to achieve that. Below I have attached my working stackblitz for reference.
JSON:
[
   {
      "nameList":[
         {
            "id":203,
            "Namelist_constrains":{

            },
            "lists":[
               {
                  "name":"books",
                  "data":{
                     "A15people":4285,
                     "A30people":4285,
                     "A90people":4285
                  }
               },
               {
                  "name":"paper",
                  "data":{
                     "A15people":4285,
                     "A30people":4285,
                     "A90people":4285
                  }
               },
               {
                  "name":"pen",
                  "data":{
                     "A15people":4285,
                     "A30people":4285,
                     "A90people":4285
                  }
               },
               {
                  "name":"ball",
                  "data":{
                     "A15people":4285,
                     "A30people":4285,
                     "A90people":4285
                  }
               },
               {
                  "name":"bat",
                  "data":{
                     "A15people":4285,
                     "A30people":4285,
                     "A90people":4285
                  }
               }
            ]
         },
         {
            "id":204,
            "Namelist_constrains":{

            },
            "lists":[
               {
                  "name":"books",
                  "data":{
                     "A15people":5004,
                     "A30people":345,
                     "A90people":1334
                  }
               },
               {
                  "name":"paper",
                  "data":{
                     "A15people":112,
                     "A30people":345,
                     "A90people":6667
                  }
               },
               {
                  "name":"pen",
                  "data":{
                     "A15people":9882,
                     "A30people":3456,
                     "A90people":29898
                  }
               },
               {
                  "name":"ball",
                  "data":{
                     "A15people":3465,
                     "A30people":224,
                     "A90people":455
                  }
               },
               {
                  "name":"bat",
                  "data":{
                     "A15people":876,
                     "A30people":234,
                     "A90people":664
                  }
               }
            ]
         }
      ]
   }
]

For the above I need to get two charts because it have two objects.
In my stackblitz i have only one object in the json. I am little bit confused how to achieve this.help me to solve this.
Link:
https://stackblitz.com/edit/angular-highcharts-example-xqcnyv?file=src/app/app.component.ts

A: You could create a simple component that will take a chart's data as it's Input and return standalone chart. Then you might use the *ngFor directive to generate that component for each element of your data.
Unfortunately, I am not familiar with the angular-highcharts, so I created the simple demo with highcharts-angular - the officially supported Angular wrapper.
Live demo:
https://stackblitz.com/edit/highcharts-angular-sparkline-j3nujf?file=src%2Fapp%2Fapp.component.html
data:
  myData = [
    { data: [1, 2, 3], name: "first" },
    { data: [4, 5, 6], name: "second" },
    { data: [7, 8, 9], name: "third" }
  ];

app.component.html
<app-spark-line
   *ngFor="let elem of myData"
   [name]="elem.name"
   [data]="elem.data"
></app-spark-line>

spark-line.component.ts:
export class SparkLineComponent {
  Highcharts: typeof Highcharts = Highcharts;
  @Input() data: Array<number>;
  @Input() name: string;
  updateFlag = false;
  chartOptions: Options = {
    chart: {
      type: "area",
      margin: [2, 0, 2, 0],
      width: 200,
      height: 200,
    },
    series: [
      {
        name: '',
        type: 'area',
        data: []
      }
    ]
  };

  ngOnChanges(change: SimpleChanges) {
      this.chartOptions.series = [{
        name: change.name ? change.name.currentValue : null,
        type: 'area',
        data: change.data.currentValue,
      }];
      this.updateFlag = true;
    }
  }

sparkline.component.html:
<highcharts-chart
  [Highcharts]="Highcharts"
  [options]="chartOptions"
  [(update)]="updateFlag"
>
</highcharts-chart>


text:
Q: Redux not working in a particularly Route after Refresh only I am using React-Redux , React-Router , Saga , React-Thunk
All my application works well , one component which also dispatch action to be rendered gives me an error whenever I refresh the page OR type the url myself its a component that renders only when a photo clicked it display the particular photo after dispatching and filtering the state by the id which I send in the url , It works fine when I click the photo but after one refresh the state returns an empty array to be rendered here is my code
import React,{useEffect} from 'react';
import styled from 'styled-components';
import {connect} from 'react-redux';
import {fetchImages} from '../redux/actions/Actions';
const Photos = props => {
    useEffect(()=>{props.fetchRequestedPhoto()},[props.requestedPhoto.length])
    console.log(props.requestedPhoto)
}

const mapStateToProps = state =>( {
    requestedPhoto:state.images
})

const mapDispatchToProps = () =>( {
    fetchRequestedPhoto:()=>{return fetchImages()}
})

export default connect(mapStateToProps,mapDispatchToProps)(Photos);

navigation.js
import React from 'react'
import {BrowserRouter as Router , Route } from 'react-router-dom'
import HomePage from '../components/home'
import Categories from '../components/categories'
import  Photos from '../components/photos.js'
import Category from '../components/category'
const Routes = () => {
   return(
       <Router>
       <Route exact path='/' component={HomePage}></Route>
       <Route exact path='/categories' component={Categories }></Route>
       <Route  exact path='/category/:category_id' component={Category}></Route>
       <Route exact path='/photo/:photo_id' component={Photos}></Route>
       </Router>
   )
}
export default Routes;

Action.js
import axios from 'axios';
import { GetCategories,GetImages } from './actionTypes'
export function fetchCategories() {
   var url = 'http://localhost:4000/all_categories';
   return (dispatch) => {
       return axios.get(url).then((res) => {
           dispatch({
               type: GetCategories,
               payload: res.data
           })
       })
   }
}
export function fetchImages(){
   var url ='http://localhost:4000/all_images';
   return(dispatch) => {
       return axios.get(url).then((res)=>{
           dispatch({
               type:GetImages,
               payload:res.data
           })
       })
   }
}

saga.js
import {takeEvery,delay,put} from 'redux-saga/effects'
import axios from 'axios';

function* getImagesAsync(){
   delay(4000)
   const response=axios.get('http://localhost:4000/all_images');
   const payloadImages = response;
   yield put({type: 'GetImagesSaga', payload:payloadImages});
}
export function* watchFetchImages(){
   yield takeEvery("GetImages",getImagesAsync);
}

Reducer.js
import { GetCategories , GetImages } from "../redux/actions/actionTypes"
const initialState = {
   categories: [],
   images:[]
};
const rootReducer = (state = initialState, action) => {
   switch (action.type) {
       case GetCategories:
           return {...state, categories:action.payload}
       case GetImages:
           return{...state,images:action.payload}
       default:
       return state;
   }
};
export default rootReducer;

Any one could help me with this??


text:
Q: Stuck with an Oracle SQL query I have a scenario like this: there is a table course_details as below:

Now what I am looking for is to find the details of students - in this case Stu_id - who have enrolled in courses in 2016.
Say for example - for 2016 there are course C1,C3 and C4. Of these courses only S1 has enrolled in all of them. S2 and S3 has enrolled only in some.
So my query should give only the result as S1.
I tried using subquery factoring, window functions, but unable to get it without hard-coding some values.

A: How about the following:
SELECT DISTINCT a.stu_id
FROM course_details AS a
WHERE
    NOT EXISTS (
        SELECT NULL FROM course_details AS b
        WHERE
            b.enrol_dt = 2016
            AND
            NOT EXISTS (
                SELECT * FROM course_details AS c
                WHERE c.c_id = b.c_id AND c.stu_id = a.stu_id
            )
    );


text:
Q: Optimizing model lookups in django I have a ToDo model, which represents a task. Each task belongs to an organization, a team within that organization, and a staff.
This is how I filter tasks, in the views:
def task_list(request, param=None, param_id=None):
    if param == "org":
        tasks = ToDo.objects.filter(org__id = param_id).exclude(todo_status=4)
    elif param == "orgstaff":
        tasks = ToDo.objects.filter(assigned_to__id = param_id).exclude(todo_status=4)
    elif param == "orgteam":
        tasks = ToDo.objects.filter(team__id = param_id).exclude(todo_status=4)
    return render(request, "task_list.html", {"tasks":tasks})

Is there a way, I could create dicts, and replace these the above 6 lines into 1 or 2?

A: Using dict and dict unpacking:
def task_list(request, param=None, param_id=None):
    field_mapping = {'org': 'org__id', 'orgstaff': 'assigned_to__id', 'orgteam': 'team__id'}
    tasks = ToDo.objects.filter(**{field_mapping[param]: param_id}).exclude(todo_status=4)
    return render(request, "task_list.html", {"tasks":tasks})


text:
Q: Update array object object value using spread operator I am trying to update a value from an array object and object. my sample code is below. Not getting the result as I expected. It would be nice if someone can help?
    let array = [
        {
            id:"01",
            "name": {
                "value": "jaison",
                "error": null
            },
            "email": {
                "value": "jaison@yopmail.com",
                "error": null
            }
        },
        {
            id:"02",
            "name": {
                "value": "jaison 1",
                "error": null
            },
            "email": {
                "value": "jaison1@yopmail.com",
                "error": null
            }
        }
    ];

    this.state{
        data:array
    }

    //This two data getting a from a form
    const key = "02";
    const editedData = {name:"updated jaison 1", email:"updatedjaison1@yopmail.com"}

    const newData = [...this.state.data];

    const index = newData.findIndex(item => key === item.id);

    let item = newData[index];

    //Working as expcted
    console.log('1', item);

    Object.keys(editedData).forEach(function (key) {
      item[key] = editedData[key];
    });

    //Working as expcted
    console.log('2', item);

    this.setState({ data: [...this.state.data, item]}, () => {
        //Not Working as expcted
        console.log(this.state.data);
    });

    Expected result
   let array = [
    {
        id:"01",
        "name": {
            "value": "jaison",
            "error": null
        },
        "email": {
            "value": "jaison@yopmail.com",
            "error": null
        }
    },
    {
        id:"02",
        "name": {
            "value": "updated jaison 1",
            "error": null
        },
        "email": {
            "value": "updatedjaison1@yopmail.com",
            "error": null
        }
    }
];

A: When you update item[key] inside the forEach, it just updates name and email with a string values. Also, it mutates the state
Instead, you could loop throguh editedData object update the clone of that specific index. Use the spread syntax to keep error and other properties as it is and update only the value property. Then update the index of the cloned data array and call setState like this:
const key = "02",
      editedData = { name: "updated jaison 2", email: "updatedjaison2@yopmail.com" },
      data = [...this.state.data],
      index = data.findIndex(item => key === item.id),
      updatedData = { ...data[index] };

// loop through and update only the keys you need
for(const key in editedData) {
  updatedData[key] = { ...updatedData[key], value: editedData[key] }
}

data[index] = updatedData;

this.setState({ data })

A: Instead of finding the index and using a forEach to loop over the array, I'd do something like:
const updatedArray = newData.map(item => {
   // if editedData has a key attribute:
   if (item.id === editedData.key) {
       return editedData; //you'd need to add a key attribute to the data
   } else {
       return item;
   }
});
this.setState({data: updatedArray});

A: You can just use map:
   let array = [
        {
            id:"01",
            "name": {
                "value": "jaison",
                "error": null
            },
            "email": {
                "value": "jaison@yopmail.com",
                "error": null
            }
        },
        {
            id:"02",
            "name": {
                "value": "jaison 1",
                "error": null
            },
            "email": {
                "value": "jaison1@yopmail.com",
                "error": null
            }
        }
    ];

    const key = "02";

    const updated = array.map(item => {
        if (item.id === key) {
            return {id: key, name:"updated jaison 1", email:"updatedjaison1@yopmail.com"}
        }
        return item;
    });

setState({data: updated});


text:
Q: ValueError: Attempted relative import in non-package - relative import in python The folder directory is:
server/
    |_entities.py
    |_config.py

In my entities.py file, I have the following:
from .config import config

But when I debug, it results in the following problem:
File "entities.py", line 14, in <module>
from .config import config
ValueError: Attempted relative import in non-package

A: Make sure you have an __init__.py in the server directory. This is an empty file required to make Python treat directories containing the file as packages.
Then try from server.config import config
Server is the top level name of your package.
From the docs

Packages are a way of structuring Python's module namespace by using
"dotted module names". For example, the module name A.B designates a
submodule named B in a package named A

You should also consider renaming the variable config to something else so that it's not confused with the file called config.


text:
Q: Java Swing: setting variables inside actionlistener that were defined outside I am new to using swing and I am having trouble with action listeners. I have an action listener set up for when a button is pressed and I am getting an error message when I try to set the value of a variable defined outside the listener. Here is the code
    // create puzzle object and array for puzzle numbers
    final Puzzle puzzle = new Puzzle();
    final int[][] nums = new int[9][9];

    // create buttons
    JButton btnSolve = new JButton("Solve");
    btnSolve.setEnabled(false);
    JButton btnGenerate = new JButton("Generate");

    // When generate button is clicked
    btnGenerate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            // generate puzzle
            nums = puzzle.generate();

            // fill board with puzzle
            fillBoard(nums);

            // enable solve button
            btnSolve.setEnabled(true);
        }
    });

    // When solve button is clicked
    btnSolve.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            // solve the puzzle
            nums = puzzle.solve(nums);

            // fill board with solved puzzle
            fillBoard(nums);
        }
    });

The code works if I declare the nums and puzzle objects inside the btnGenerate listener without them being final. But I want to use the nums array in the btnSolve listener.
On the lines nums = puzzle.generate(); and nums = puzzle.solve(nums); I am getting the error:

The final local variable nums cannot be assigned, since it is defined in an enclosing type

What does it mean by "defined in an enclosing type" and how should this be done?
Thanks in advance.

A: Declare this final int[][] nums = new int[9][9]; as a class member and not final. The message is clear. You cannot modify something that is final. You may or may not also need to do the same with Puzzle
public class MyClass {

   int[][] nums = new int[9][9];   <-- class member instead of in constructor
   Puzzle puzzle = new Puzzle();

   public MyClass(){
   }
}


text:
Q: canvas rotate isn't working as expected http://jsfiddle.net/s1n6cssa/12/
HTML
Rotate

CSS
#myCanvas {
height: 100%;
width: 100%;
background-color: blue;
}
#print-region {
    height: 542px;
    width: 520px;
    margin: 0;
    position: relative;
    overflow: hidden;
}
.overlay {
    position: absolute;
    pointer-events: none;
}
#rotate {
    width: 100px;
    height: 30px;
}

JAVASCRIPT
var context;
var canvas;
var nHeight;  //the new height after resizing
var nWidth;   //the new width after resizing
var TO_RADIANS = Math.PI / 180;
var imageObj = new Image();

//USE ONLY ONE OF THE BELOW IMAGES AT A TIME

//square image which does not distort after rotation
imageObj.src = "http://i.stack.imgur.com/hwxO6.png";

//rectangular image which distorts after rotation

var originalWidth = imageObj.width;
var originalHeight = imageObj.height;

$('#myCanvas').remove();

//used by context.rotate and updated after every rotation
$("#uploaded-image-container").attr({
    rotation: 0
});

$("#uploaded-image-container").append("<canvas id='myCanvas'></canvas>");

$("#uploaded-image-container").css({
    "position": "absolute",
        "height": originalHeight / 3, //one-third size of the original height of the uploaded image
        "width": originalWidth / 3,
        "top": $('#print-region').height() / 3,
        "left": $('#print-region').width() / 3
});

canvas = document.getElementById('myCanvas');

context = canvas.getContext('2d');
nHeight = canvas.height = originalHeight / 3;
nWidth = canvas.width = originalWidth / 3;

imageObj.onload = function () {
    context.drawImage(imageObj, 0, 0, originalWidth / 3, originalHeight / 3);
};

$("#uploaded-image-container").draggable({
    snap: false,
    scroll: false,
    cursor: "move",
    containment: '#print-region'
});

$("#uploaded-image-container").resizable({
    handles: 'nw, ne, sw, se',
    aspectRatio: true,
    containment: '#print-region',

    resize: function (e, ui) {
        nHeight = ui.size.height;
        nWidth = ui.size.width;
    }
});

$("#rotate").click(function () {
    updateRotation($("#uploaded-image-container"));
});

var imageRotation = 0; // the angle that the image is rotated
var updateRotation = function (elem) {
    var angle = parseInt(elem.attr('rotation'));

//after rotation, the nWidth and nHeight are interchanged hence temp variables
    var tempHeight, tempWidth;

    if (angle == 0) {
        imageRotation = 90;
        elem.attr('rotation', 90);
        tempHeight = nWidth;
        tempWidth = nHeight;
    } else if (angle == 90) {
        imageRotation = 180;
        elem.attr('rotation', 180);
        tempHeight = nHeight;
        tempWidth = nWidth;
    } else if (angle == 180) {
        imageRotation = 270;
        elem.attr('rotation', 270);
        tempHeight = nWidth;
        tempWidth = nHeight;
    } else {
        imageRotation = 0;
        elem.attr('rotation', 0);
        tempHeight = nHeight;
        tempWidth = nWidth;
    }

    $("#uploaded-image-container").css({
        "height": tempHeight,
            "width": tempWidth
    });

    canvas.width = tempWidth;
    canvas.height = tempHeight;
    context.translate(tempWidth / 2, tempHeight / 2);
    context.rotate(imageRotation * TO_RADIANS);
    context.translate(-tempWidth / 2, -tempHeight / 2);
    context.drawImage(imageObj, 0, 0, tempWidth, tempHeight);
};

I wanted to take a snapshot of the part shown in the result of jsfiddle using html2canvas plugin. But html2canvas does not support CSS3 rotate property.
So I used canvas to rotate image and the rotation is successfully captured by html2canvas.
In the above code, when I use a square image, it rotates perfectly but when a rectangular image is considered then the image width and height are distorted.
Any combination of resize, drag and rotate should not distort the image.
What is the issue?

A: It's because you use temporary value(width and height) as orientation when drawing and scaling image. then orientation's value is applied to setContainerHeight and setContainerWidth; in short: you use same value as coordinates and scaling
I cannot see your first image(it is blocked in my country), maybe because it is square(width = height); thus no problem occur, but rectangular is width = 2 * height;  So use image ratio. This should work in any box shape
    var context;
    var canvas;
    var nHeight;
    var nWidth;
    var TO_RADIANS = Math.PI / 180;
    var imageObj = new Image();
     imageObj.src = "http://g-ecx.images-amazon.com/images/G/01/electronics/detail-page/Klipsch-Image-S4-II-Black-Lifestyle.jpg";

    var originalWidth = imageObj.width;
    var originalHeight = imageObj.height;

    $('#myCanvas').remove();
    $("#uploaded-image-container").attr({
        rotation: 0
    });

    $("#uploaded-image-container").append("<canvas id='myCanvas'></canvas>");

    $("#uploaded-image-container").css({
        "position": "absolute",
            "height": originalHeight / 3,
            "width": originalWidth / 3,
            "top": $('#print-region').height() / 3,
            "left": $('#print-region').width() / 3
    });

    canvas = document.getElementById('myCanvas');

    context = canvas.getContext('2d');
    nHeight = canvas.height ;
    nWidth = canvas.width ;

    imageObj.onload = function () {
        context.drawImage(imageObj, 0, 0, originalWidth / 3, originalHeight / 3);
    };

    $("#uploaded-image-container").draggable({
        snap: false,
        scroll: false,
        cursor: "move",
        containment: '#print-region'
    });

    $("#uploaded-image-container").resizable({
        handles: 'nw, ne, sw, se',
        aspectRatio: true,
        containment: '#print-region',

        resize: function (e, ui) {
            nHeight = ui.size.height;
            nWidth = ui.size.width;
        }
    });

    $("#rotate").click(function () {
        updateRotation($("#uploaded-image-container"));
    });

 var imageRotation = 0; // the angle that the image is rotated
var updateRotation = function (elem) {
    var angle = parseInt(elem.attr('rotation'));
    var ratio = nWidth/nHeight;
    var customX = nWidth, scaleX = nWidth;
    var customY = nHeight, scaleY = nHeight;
    var tempHeight, tempWidth;
    //the problem is in number 1 and 3
    if (angle == 0) { //number 1
        imageRotation = 90;
        elem.attr('rotation', 90);
        tempHeight = nWidth;
        tempWidth = nHeight; customY = ratio*customY;
    } else if (angle == 90) { //number 2
        imageRotation = 180;
        elem.attr('rotation', 180);
        tempHeight = nHeight;
        tempWidth = nWidth ;
    } else if (angle == 180) {
        imageRotation = 270;
        elem.attr('rotation', 270);
        tempHeight = nWidth;
        tempWidth = nHeight;  customY = ratio*customY;
    } else { // number 4 handle
        imageRotation = 0;
        elem.attr('rotation', 0);
        tempHeight = nHeight;
        tempWidth = nWidth;
    }

    $("#uploaded-image-container").css({
        "height": tempHeight,
        "width": tempWidth
    });

    canvas.width = customX;
    canvas.height = customY;
    context.translate(customX / 2, customY / 2);
    context.rotate(imageRotation * TO_RADIANS);
    context.translate( -customX / 2, -customY / 2);
    context.drawImage(imageObj, 0, 0, customX, customY);
};

A: Try this one http://jsfiddle.net/5hrx77nr/ fiddle.
context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)

By default html5 scale out image to canvas size, so you must manage image size manually.

A: you should explain a little bit more about what are you trying to do. I think rotation is not that complex
Anyway. I spotted an error on line 33, 34
nHeight = canvas.height = originalHeight / 3;
nWidth = canvas.width = originalWidth / 3;

Maybe what you meant is addition or multiplication?? Because a blue canvas appear and  rotate after this is changed.
    nHeight = canvas.height + originalHeight / 3;
    nWidth = canvas.width + originalWidth / 3;


text:
Q: Raise an exception using mock when a specific Django model is called I have a class based view inheriting from FormView with an overridden form_valid() method that I would like to test.
As you can see, form_valid() is required to access the CustomUser model which is wrapped with a try and except.
What I am trying to do is raise an exception whenever create_user is called, but I am having no success.
The CustomUser has been created in the usual way via a CustomUserManager with a create_user method.

CustomUser = get_user_model()

class SignUpView(FormView):
    template_name = 'accounts/signup.html'
    form_class = SignUpForm

    def form_valid(self, form):

        try:
            self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first()

            if not self.user:

                self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'],
                                                           full_name=form.cleaned_data['full_name'],
                                                           password=form.cleaned_data['password'],
                                                           is_verified=False
                                                           )
            else:
                if self.user.is_verified:

                    self.send_reminder()

                    return super().form_valid(form)

            self.send_code()
        except:
            messages.error(self.request, _('Something went wrong, please try to register again'))
            return redirect(reverse('accounts:signup'))

        return super().form_valid(form)

What I have tried:
  def test_database_fail(self):
        with patch.object(CustomUserManager, 'create_user') as mock_method:
            mock_method.side_effect = Exception(ValueError)

        view = SignUpView.as_view()
        url = reverse('accounts:signup')
        data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'}
        request = self.factory.post(url, data)
        request.session = {}
        request.messages = {}
        response = view(request)

and ..
  def test_database_fail(self):

        CustomUser = Mock()

        CustomUser.objects.create_user.side_effect = CustomUser.ValueError

        view = SignUpView.as_view()
        url = reverse('accounts:signup')
        data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'}
        request = self.factory.post(url, data)
        request.session = {}
        request.messages = {}
        response = view(request)

In both cases no exception is triggered.
My question is, how can I raise an exception whenever create_user is called using mock?

A: You need to write the whole test under mock.patch context manager. Otherwise once with statement is finished, mock doesn't work anymore and has no effect. Try this:
def test_database_fail(self):
    with patch.object(CustomUserManager, 'create_user') as mock_method:
        mock_method.side_effect = Exception(ValueError)

        view = SignUpView.as_view()
        url = reverse('accounts:signup')
        data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'}
        request = self.factory.post(url, data)
        request.session = {}
        request.messages = {}
        response = view(request)

Also note that you can specify side_effect directly in patch.object method:
with patch.object(CustomUserManager, 'create_user', side_effect=Exception):
    # rest of your code


text:
Q: Unique name for row after each iteration of display Table in Struts2 I am trying to implement Survey functionality in Struts application. For each survey questions, users select one options among Excellent, Very Good, Good, Satisfactory or Poor.
So, what I am trying to achieve is I need to have "unique name" for  at each iteration of questionList so that user can select only one option per question.
Here is the part of jsp I have pasted:
<s:form id="screeningForm" action="submitSurvey" >
    <display:table uid="row" name="${questionList}"   >
        <display:column  property="statement" title="STATEMENT" />
        <display:column   title="EXCELLENT" >
            <s:radio name=?? list="{..}"></s:radio>
        </display:column>
        <display:column  title="VERY GOOD">
            <s:radio name=?? list="{..}"></s:radio>
        </display:column>
        <display:column  title="GOOD">
            <s:radio name=?? list="{..}"></s:radio>
        </display:column>
        <display:column   title="SATISFACTORY">
            <s:radio name=?? list="{..}"></s:radio>
        </display:column>
        <display:column  title="POOR">
            <s:radio name=?? list="{..}"></s:radio>
        </display:column>
    </display:table>

Thank you in advance!

A: You will add the index or count to the name for unique. like this
<s:iterator status="status" value='{0, 1}'>
      Index: <s:property value="%{#status.index}" />

      Count: <s:property value="%{#status.count}" />

   </s:iterator>

Refer this link.
Hope this may helpful for you

A: I solve this problem by adding a list at action class (private List select;) and gave name to each radio buttons as name="select[%{#attr.row_rowNum - 1}]"
<display:table uid="row" name="${questionList}"  requestURI=""  frame="" >
    <display:column  property="statement" title="STATEMENT" />
    <display:column   title="EXCELLENT" >
        <s:radio name="select[%{#attr.row_rowNum - 1}]" theme="simple" list="#{'1':''}"></s:radio>
    </display:column>
    <display:column  title="VERY GOOD">
        <s:radio name="select[%{#attr.row_rowNum - 1}]" theme="simple" list="#{'2':''}"></s:radio>
    </display:column>
    <display:column  title="GOOD">
        <s:radio name="select[%{#attr.row_rowNum - 1}]" theme="simple" list="#{'3':''}" ></s:radio>
    </display:column>
    <display:column   title="SATISFACTORY">
        <s:radio name="select[%{#attr.row_rowNum - 1}]"  theme="simple" list="#{'4':''}" ></s:radio>
    </display:column>
    <display:column  title="POOR">
        <s:radio name="select[%{#attr.row_rowNum - 1}]" theme="simple" list="#{'5':''}"></s:radio>
    </display:column>
</display:table>


text:
Q: Can I run .jar file on Tomcat? a very noob question.
Can I run a .jar file on Tomcat. I am not building a web-app. I simply need to run a .jar with
say HalloWorld in it. Is this possible/appropriate.
Thanks

A: You can run a Java archive without Tomcat, simply with a Java Runtime Environment:
$ java -jar myhelloworldapp.jar

Tomcat is a servlet container, only needed for web applications.

A: I don't really know what your use case is, but what you probably need is a virtual private server (VPS) provider. They give you a virtual host which runs OS of your choice and you can install JVM on it. There are many VPS' available. Try Linode or Slicehost.
It would help if you would explain what you are trying to achieve, then we might be able to give you a better answer.

A: I think what you want is Java's webstart

A: It sounds like want you want to do is deploy batch code to your server and then run it.  You could either create a new web-app that contains your jar, or add the jar to an existing web app.  Then you can trigger execution with a servlet.  You could even have a JSP that contains:
<%
  String [] args = new String[0];
  MyClass.main(args);
%>

Of course you'd want to secure that JSP so that not just anyone can run your job.
We use the quartz scheduler to schedule batch jobs from within tomcat.  This let's us monitor our jobs much more easily than if they were run from the command line.
http://www.quartz-scheduler.org/


text:
Q: Why maxConcurrent setting in bottleneck.js doesn't work? I'm using bottleneck npm package. I set my limiter as follows:
const limiter = new Bottleneck({
        maxConcurrent: 3,
        minTime: 100
});

to have 3 tasks running concurrently at most.
However, I see that at no time there're more than 1 task running concurrently.
This is my code:
const Bottleneck = require('bottleneck');

const main = () => {
    console.log('starting main');
    const limiter = new Bottleneck({
        maxConcurrent: 3,
        minTime: 100
    });

    const worker = (text, limiterCb) => {
        Promise.resolve()
        .then(() => {
            console.log(`starting ${text}`);
            let res;
            for (let i = 0; i < 10000000000; i++) {
                res++
            }
            console.log(`ending ${text}`);
            limiterCb();
        });
    };

    const limiterCb = res => console.log('limiter finished');

    limiter.submit(worker, 'hello', limiterCb);
    limiter.submit(worker, 'hello', limiterCb);
    limiter.submit(worker, 'hello', limiterCb);
    limiter.submit(worker, 'hello', limiterCb);
}

main();
console.log('exiting')

What I see is that the first task starts and finishes, then the second etc. But because each tasks takes more than 100ms to finish I expected more than 1 task to be running concurrently.


text:
Q: Backbonejs - Avoid parse after save Backbone documentation says,

parse is called whenever a model's data is returned by the server, in
  fetch, and save. The function is passed the raw response object, and
  should return the attributes hash to be set on the model.

But i have customized parse function for my model. I want to execute it only when i fetch data not when i save data.
Is there a way to do it? I can check my response inside parse function. But is there any built-in option to do it?

A: This is from the backbone source file regarding saving a model:
var model = this;
var success = options.success;
options.success = function(resp) {
    model.attributes = attributes;
    var serverAttrs = model.parse(resp, options);
    if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
    if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
        return false;
    }
    if (success) success(model, resp, options);
    model.trigger('sync', model, resp, options);
};

You could pass a custom option on your save like: model.save(null, { saved: true }), then in your custom parse:
parse: function(response, options) {
    if ( options.saved ) return this.attributes;
    // do what you're already doing
}

I haven't tested this at all, but it should at least get you started.

A: Just pass a parse:false into the save method as an option.
m = new MyModel()
s.save(null, {parse: false})


text:
Q: Angular 2 RC 4 - hashlocationstrategy no longer working We have upgraded our Angular 2 project to Release Candidate 4.
We are using HashLocationStrategy to be able to refresh a page in the browser (using BrowserSync).
But with RC4 this no longer works.
No component is loaded into the routeroutlet.
However, using the routerlink of a menu item does work.
Is the HashLocationStrategy for RC4 broken, or are we not using it correctly?
We haven't found any information on the Internet yet. (right now just trying to find our way through the Angular2 source code to find out what is going on)
Update: here is the code.
Also, we can't seem to find a way to get a default route working.
Tried the empty path as seen below, tried the redirect...nothing seems to trigger a default route that will load a component into the route-outlet.
// boot:

import {bootstrap} from '@angular/platform-browser-dynamic';

import {AppComponent} from './app.component';

bootstrap(AppComponent)
    .catch(err => console.log(err));

// AppComponent:

import {Component, provide, ExceptionHandler} from '@angular/core';
import {HTTP_PROVIDERS, XHRBackend} from '@angular/http';
import {CORE_DIRECTIVES, LocationStrategy, HashLocationStrategy} from '@angular/common';
import {TranslatePipe, TranslateService, TRANSLATE_PROVIDERS} from 'ng2-translate/ng2-translate';

import {SideMenuComponent} from './navigatie/index';
import {AppSettingsService, Auth, MockBackendToggle} from './shared/index';
import {EssStorage} from './shared/ess-storage';
import {EssHttp} from './shared/ess-http';
import {DienstverbandService} from './dienstverband/shared/dienstverband.service';
import {HeaderMenuComponent} from './navigatie/headermenu/headermenu.component';
import {WerknemerService} from './werknemer/werknemer.service';
import {PersoonService} from './werknemer/persoon/shared/persoon.service';
import {RouterOutlet} from '@angular/router';
import {APP_ROUTER_PROVIDER} from './navigatie/routes';
import {AuthGuard} from './shared/auth/auth-guard';
import {EssExceptionHandler} from './shared/ess-exception-handler';

@Component({
    selector: 'ess-app',
    pipes: [TranslatePipe],
    directives: [CORE_DIRECTIVES, SideMenuComponent, HeaderMenuComponent, RouterOutlet],
    providers: [TRANSLATE_PROVIDERS, TranslateService, HTTP_PROVIDERS, EssHttp, WerknemerService, APP_ROUTER_PROVIDER, AuthGuard,
                AppSettingsService, Auth, DienstverbandService, PersoonService, provide(XHRBackend, {useClass: MockBackendToggle}),
                provide(LocationStrategy, {useClass: HashLocationStrategy}), provide(ExceptionHandler, {useClass: EssExceptionHandler})],
    template: `

                <ess-headermenu></ess-headermenu>

            <ess-sidemenu></ess-sidemenu>

                        <router-outlet></router-outlet>

`
})
export class AppComponent { //..}

// routes:

import {provideRouter, RouterConfig} from '@angular/router';
import {DashboardComponent} from '../dashboard/index';
import {PersonaliaComponent} from '../werknemer/index';
import {LoginComponent} from '../login/index';
import {AuthGuard} from '../shared/auth/auth-guard';

export const appRoutes: RouterConfig = [
    {path: '',                      component: LoginComponent},
    {path: 'login/:url',            component: LoginComponent},
    {path: 'dashboard',             component: DashboardComponent},
    {path: 'personalia',            component: PersonaliaComponent,             canActivate: [AuthGuard]}
];

export const APP_ROUTER_PROVIDER = provideRouter(appRoutes);

Update:
When I navigate to a view by clicking on a link and using [routerLink], then the router-outlet gets filled with the correct Component. For instance when navigating to 'auto'.

{{'AUTO' | translate}}

But when I for instance refresh the 'auto' page, the router-outlet becomes empty.

A: In Angular 2 rc4, it appears LocationStrategy has been moved from router to common. You'll have to import it from there.
Also note the curly brackets around the 'provide' line.
rc4: main.ts
// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

rc5: app.module.ts
In rc.5 this is changed again because of the major changes to main.ts. Hashlocationstrategy is now implemented in app.module.ts as an option when importing the RouterModule.
@NgModule({
imports: [routing, RouterModule.forRoot(routing,{ useHash: true })],

2.0.0: app.module.ts
In Angular 2.0.0 (= release version) Hashlocationstrategy stayed in app.module.ts, but the phrasing changed a little bit. It's now sitting with the providers.
...
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
...

@NgModule({
  bootstrap: [AppComponent],
  imports: [
    //all your modules
  ],
  declarations: [
    //all your components
  ],
  providers: [
    //all your services
    {provide: LocationStrategy, useClass: HashLocationStrategy},
  ]
})


text:
Q: How to handle a UIScreenEdgeGestureRecognizer with a map view covering the whole view? I have iOS program over here, with a map view covering the whole container view. I want the map view to handle the UIScreenEdgeRecognizer, since it is covering the whole container view. I think it would be better to let the gestureRecognizers array to reference the recognizer. But the pan gesture of the map view is interrupting the screen edge recogniser. I tried gestureRecognizer:shouldFailRequireFailureOfGestureRecognizer and all that, but it still doesn't work. But solution would you people recommend? Could I let the gestureRecognizers array of the container view reference the screen edge recogniser?

A: What I did was to add a view with a 10pt width and clear color background over the edge I needed the gesture recognizer and I added the gesture recognizer to this view.
In the picture, the white rectangle on the right is the view which will have the gesture recognizer. You should change the background color to clear color.

The view outlet:
@property (weak, nonatomic) IBOutlet UIView *rightEdgeGestureView;

Add the gesture recognizer to the view on the screen right edge:
- (void)setupGestureRecognizer {

      UIScreenEdgePanGestureRecognizer *gestureRecognizer = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandler:)];
      gestureRecognizer.edges = UIRectEdgeRight;
      [_rightEdgeGestureView addGestureRecognizer:gestureRecognizer];
 }


text:
Q: C# library for connecting different RDBMS I'm currently working on one project. I want to analyze a few things in the database, to see which is faster, more reliable, less resource-consuming.
I would like to create one program in C# and connect five databases. From that program, I will call the procedures and measure the time of execution.
Which library do I use in C# to connect: Microsoft SQL Server, Oracle, MySQL, PostgreSQL, IBM Db2 with Visual Studio?
I have found this library on the internet: http://dbnetdata.codeplex.com/
Has anyone used it? Does anyone know about another library?

A: Entity Framework would be able to connect to those engines.
What database systems are fully supported by Entity Framework 6 and/or 7?

A: To make fair comparisons you should use the native provided libraries.  These are:

SQL Server:        System.Data.SqlClient
Oracle:            Oracle.ManagedDataAccess
PostgreSQL:        Npgsql
MySQL:             MySQL.Data
IBM DB2:           Sorry don't know never used it!  I hope someone
  else can supply


text:
Q: Does "I have a daughter" mean "I have one daughter"? Let's say I have two daughters and someone asks me:

Do you have a daughter?

Should I respond "yes" or "no"? In other words, does "I have a daughter" mean "I have one daughter"?

A: You asked about answering "yes" or "no". If the question is "do you have a daughter" and you have one, two or more daughters, then the correct answer is "yes".
However, if I ask the question, I might get the answer "yes, I have a daughter" and the problem is: Does the person have exactly one daughter or possibly more than one?
It depends on the context. Let's say I have trouble with my daughter and some know-it-all is trying to give me advice, which really gets on my nerves. So I ask "do you have a daughter?" because that kind of unwanted advice often comes from people who know nothing. In that case an answer "yes, I have a daughter" means one or more daughters. My question really meant "do you know what you are talking about" and the answer meant "yes, I know what I'm talking about".
In other situations, you would expect "I have a daughter" to mean "I have one daughter", and you would expect a different answer like "I have two daughters" from someone with more than one daughter. Then of course it depends on how much of a pedant the person is, so your expectation might be wrong.

A: The long standing play on words relating to this subject is this joke:
"Hey, you got a haircut!"
"Actually, I got all of them cut!"
This is funny (or supposed to be funny) exactly because "a haircut" (the act of getting your hair cut) sounds exactly like "a hair cut" (you got exactly one of your hairs cut), and the deliberate misinterpretation is unexpected.
The fact that this answer is unexpected highlights how strange it would be to me to answer anything other than "Yes" to the original questioner.

A: "I have a/an X" does not necessarily mean that I have exactly one X, it just means that I have one or more.
Suppose someone was looking for a ride home, and he asked, "Do you have a car?" If you own two cars, you wouldn't say, "No". You probably wouldn't even find it necessary to say, "I have two cars". You'd just say "Yes". (Well, unless you're looking for an excuse to not give him a ride.)
Suppose your local school announced they were having a "father/daughter dance", and said, "This is open to any man who has a daughter in this school." If you have two daughters, would you conclude that you were not welcome? Almost certainly not.
Or to take it a step further, if someone asked, "Do you have a daughter?", and in fact you have one daughter and one son, would you say, "No, I don't?" Probably not. Or if someone asked, "Do you own a cell phone?", would you say "no" because you own a cell phone and you own a laptop computer and you own a car and you own six pairs of underwear, etc? Normally, asking if you "have X" doesn't imply "and nothing else". If you want to specify "and nothing else", you normally need to add some words, like "only" or "just one". Like if someone asked me, "Do you have only one daughter?", I would answer, "No, I have two." I might also say that I have two sons as well, if the context of the question implied that the person was asking if I had only daughters.
All that said, there may be contexts where it would be understood to mean exactly one. I can't think of one, but I can think of a somewhat similar example. Suppose someone said, "In this country it is illegal for anyone under 18 to buy alcohol." If in fact the law said it is illegal for anyone under 21 to buy alcohol, there's a sense in which the statement is technically accurate: Yes, it is illegal for anyone under 18 to buy alcohol. But it is also illegal for anyone between 18 and 21 to buy alcohol. But as worded the sentence is very misleading. It implies that anyone over 18 can buy alcohol, without actually saying that.
I suppose if someone said, "We are holding a conference for parents of girls being raised without any brother or sisters, only children who are girls. You sir, do you have a daughter?" Clearly then he means exactly one, but this example is highly contrived.

A: "I have a daughter" does mean you have only one, though it's correct to ask "do you have a daughter" if you're not sure if the person has one, none, or multiple daughters. The correct answer is "yes, I have two daughters."

A: In common usage, the question "do you have a daughter" usually carries with it an implied elaboration in the response, since "a" does NOT literally mean "one" in this context.
If you had one daughter, a typical response might be "yeah, a 9 year old girl" or "I do, she's in college", or simply "yes, I do".
If you had two or more, you might say "I have two of them, a 9 year old girl and another in college" or just "two of them".
If I had to put a rule to how it's commonly used (in my experience), I'd say:

*

*for 0 daughters, say that you do not

*for 1 daughter, say that you do, and a small piece of information as well, such as her age or any basic descriptor

*for 2 or more daughters, it's acceptable to just say how many you have, with any extra information being completely optional to include

A: On its own, "I have a daughter" does mean "I have one daughter". (An exception might be if you've just now got/learned of the newest daughter, by birth or prenatal testing results or adoption or a transgender announcement.) In response to the question "Do you have a daughter?", "no" alone means "I have zero daughters."
Other than that, the answer will depend on the reason for the question. As it happens I do have two daughters, but won't always say that if the person is clearly only asking about one of them, or if one is enough.
"I saw a teenager who looks just like you. Do you have a daughter?" "yes"
"I'm seeking the opinions of mothers of girls for a study. Do you have a daughter?" "yes"
If the person is asking in a conversational way, an answer of just "yes" would be almost as weird as an answer of "no". It would be appropriate to say something about my daughters and ask about theirs.
"Do you have a daughter?" "Yes, two in fact, they're 16 and 19."

A: I skimmed other answers and didn't find any mention of articles, so I'll just add some information about grammar:
The word a in English is an indefinite article. It is used in the following situations:

*

*before phrases of time and measurements (per week/weekly)

I go to English class 4 times a week

*

*you can also use per week here

*before phrases of jobs

I am a doctor

*with a noun complement

Do you have a daughter? Yes, I have a daughter

*

*This is your case

*Note that if you have more than one daughter, you would start numbering how many: I actually have three daughters!

*before phrases of nationality (very rarely)

He is an American

*

*This is not used often, only when the nationality is being used as a noun phrase (as used above). Some more examples/exceptions:

*

*She is a native French speaker (the noun phrase is in bold).

*She is a French

*

*This is incorrect because French is being used as an adjective to describe the woman; it is not a noun phrase

*half/quite with a noun phrase

He is quite a handsome man
The recipe requires half a cup of sugar

A: To expand on the answer mentioning indefinite articles...
The words "a" and "an" are indefinite articles. By definition, this means that they do not refer to a specific quantity - "a" and "an" mean "at least one". The word "the" is called a definite article, and refers to a single entity.
A native English speaker will never, in seriousness, ask that question on its own with the intention of asking if you have exactly one daughter.

A: As an algorithm:
Do you have a daughter?
---If (number of daughters) > 0
---------YES
---Else
---------NO

A: Yes this does mean you have ONE daughter. If you were asking how many children someone had you would say "how many children do you have". This could mean single or multiple children!


text:
Q: Why is the font changed when exporting a word-file to pdf? We use this code in access-vba to convert our word to a pdf:
    Set w_app = CreateObject("word.application")
    w_app.Documents.Open(fileName:="C:\Temp\Test.docx")
    w_app.ActiveDocument.ExportAsFixedFormat "c:\Temp\test.pdf", wdExportFormatPDF, _
                                             OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
                                             Range:=wdExportAllDocument, From:=1, To:=1, item:=wdExportDocumentContent, _
                                             IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:=wdExportCreateNoBookmarks, _
                                             DocStructureTags:=True, BitmapMissingFonts:=True, useIso19005_1:=false

But when we open the pdf, all the text which was written with the font: "Apercu Pro" has changed to the font: "Segoe Script".
This does not happen when we use Office-Word to manually export the file.
Strangly, it also does work fine when the font "Apercu Pro" in !not! installed in windows.
What we already tried:

*

*We changed every single parameter of ExportAsFixedFormat => no effect

*We used the function ExportAsFixedFormat2 instead of ExportAsFixedFormat => no effect

*Tried to use w_app.ActiveDocument.SaveAs2("c:\Temp\test.pdf", EmbedTrueTypeFonts:=False) instead of ExportAsFixedFormat  => no effect

A: I did not really find out what the problem was exactly but my solution was to deinstall the .otf-Version (OpenType format) of the font and instead install the .ttf-Version (True type format).


text:
Q: Xamarin app deployment I am wondering how I can actually download the app I created from Xamarin onto my phone (iOS). I am not sure if I have to publish it on the app store or if there is a medium that I take it through so I can use the App?
I am new to coding and made a basic calculator and just want to run it on my phone to test it. Also, I have already tested it through the emulator to know it is working.
Thanks!


text:
Q: Site opens up fine in mozilla but not chrome so the problem i'm facing is the site works fine in firefox , and it even works fine while loaded on http in chrome, but when you switch to https it stops working and in network tab only returns the site url with 304 status and doesn't load anything, but then again when you switch to icognito mode in chrome it still works fine, i've already removed all my extensions and cleared my cache and site data and ...
but the problem still remains, the url for the site is below:
https://hichhop.com
http://hichhop.com

please test both urls in both chrome and firefox to get what i mean exactly,
thank you in advance.

A: On reloading the mentioned website and keeping an eye on the networks tab in developer mode , you can check that in normal mode , i.e. , not incognito one , the site crashes before the below warning comes whereas you can see the below warning in incognito mode .
Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure element ''. This request was automatically upgraded to HTTPS, For more information see
You can read more about this warning and how to resolve it using below link :
https://www.thesslstore.com/blog/how-to-find-and-fix-mixed-content-warnings-on-https-sites/
FYI , in incognito mode , insensitive and mixed content isn't blocked by default leading to your site opening in it .

A: Works fine for me, I think this may be an issue with your Chrome and STS

*

*Browse to chrome://net-internals/#hsts

*Under Delete domain security policies type hichhop.com and click Delete

*Browse to chrome://settings/clearBrowserData

*Check Cached images and files and click Clear data


text:
Q: a word for functionalism as decoration a word for an element of a design, or an object, that appears overtly functional but is decorative.
ie, 4x4 rugged styling that is not functional; plastic bull bars.
Lots of buckles or oversized, clasps, giant rivets, on 'rugged''utility' combat style clothing or backpacks.

A: gewgaw, as defined by Wiktionary

Showy; unreal; pretentious.

It has a nice 600 year history, too. 1678, Dryden, John, All for Love, Scene II,

The rattle of a globe to play withal, This gewgaw world, and put him
  cheaply off.

Another example:  1855, Alfred, Lord Tennyson, Maud; A Monodrama, X, stanza 1,

Seeing his gewgaw castle shine, New as his title, built last year.

A: I would use the phrase "purely cosmetic", as it reflects that the only function is to affect the appearance of something rather than its substance.

A: Kitsch

1:  something that appeals to popular or lowbrow taste and is often of
  poor quality
  2:  a tacky or lowbrow quality or condition

"Kitsch." Merriam-Webster.com. Merriam-Webster, n.d. Web. 13 May 2016.
There is a strong air of, shall we say, unoriginality about kitsch.
Of course, if it was done a long time ago, we call it neoclassical.

A: Are you talking about the "steampunk" fashion/style? It is a low-tech homage inspired by the writing of Arthur Conan Doyle and H.G.Wells. (Think: 19th century mad-scientist or inventor.)


text:
Q: Parse a String containing a JSON array to an Object I succeeded to parse my object to a JSON array string :
public class MyClass extends JsonElement {

    private JsonArray array;

    public MyClass(String name, String role, String title) {
        this.array = new JsonArray();
        this.array.add(Objects.requireNonNull(name));
        this.array.add(Objects.requireNonNull(role));
        this.array.add(Objects.requireNonNull(title));
    }

    @Override
    public JsonElement deepCopy() {
        return array.deepCopy();
    }

    @Override
    public boolean isJsonArray() {
        return true;
    }

    @Override
    public JsonArray getAsJsonArray() {
        return array;
    }

}

Gson gson = new Gson();
MyClass obj = new MyClass("ab", "cd", "ef");
System.out.println(gson.toJson(obj)); // "["ab", "cd", "ef"]"

How can we do the opposite ?
MyClass obj2 = gson.fromJson("[\"ab\", \"cd\", \"ef\"]", MyClass.class);

I got :

Exception in thread "main" com.google.gson.JsonSyntaxException: Expected a MyClass but was com.google.gson.JsonArray

I tried :
public class MyAdapter extends TypeAdapter<MyClass> {

    @Override
    public void write(JsonWriter out, CommunityTeamMember value) throws IOException {
        TypeAdapters.JSON_ELEMENT.write(out, value);
    }

    @Override
    public MyClass read(JsonReader in) throws IOException {
        JsonArray array = TypeAdapters.JSON_ELEMENT.read(in).getAsJsonArray();
        return new MyClass(array.get(0).getAsString(),array.get(1).getAsString(),array.get(2).getAsString());
    }

}

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(MyClass.class, new MyAdapter());
Gson gson = builder.create();

A: You've done some trickery by making your object behave as a JsonArray to the serializer, so you get a JsonArray back, but the deserializer only knows to put it into a JsonArray.  To get back an instance of the class you had, you can add a constructor that takes a JsonArray
class MyClass extends JsonElement {
    private JsonArray array;

    public MyClass(String name, String role, String title) {
        this.array = new JsonArray();
        this.array.add(Objects.requireNonNull(name));
        this.array.add(Objects.requireNonNull(role));
        this.array.add(Objects.requireNonNull(title));
    }

    public MyClass(JsonArray jsonArray) {
        this.array = jsonArray;
    }

    @Override
    public JsonElement deepCopy() {
        return array.deepCopy();
    }

    @Override
    public boolean isJsonArray() {
        return true;
    }

    @Override
    public JsonArray getAsJsonArray() {
        return array;
    }

}

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        MyClass obj = new MyClass("ab", "cd", "ef");
        String serialized = gson.toJson(obj);

        System.out.println(serialized); // "["ab", "cd", "ef"]"
        MyClass obj2 = new MyClass(JsonParser.parseString(serialized).getAsJsonArray());
        System.out.println(obj2.getAsJsonArray()); //["ab","cd","ef"]
    }
}


text:
Q: Content pushing down and up with fixed bg issue I'm needing a fixed full size background in a section that is below the navbar. When I get down to mobile, and toggle my navigation, it pushes the section down including the image - but once fully expanded it will go back up while the content stays where it is meant to.
If I change the background from fixed then my content will be too long for the image's height and this is not what I'm after.
Can anyone offer a solution?
I've included a codepen below - please note this is just a snippet to provide an example.
(need to provide code to link codepen)
.contact__full-bg-container {
    width: 100%
    height: 100%
    ...
}

http://codepen.io/jreynolds90/pen/BLqZvj

A: You need to add some css to .nav--lower. Try adding:
position: absolute;
z-index: 1;


text:
Q: Finding Y value from X value in MSChart Series I have created a Line chart using MSChart 2008.I have Dates on the x axis and Double values on y axis.Now I need to find Y value on Todays Date(Which will be my x value)..Can anybody help me to achieve this.
Thanks

A:
I use a similar approach to this with cursors: I wanted to find the closest record to where the vertical cursor was added and show the value for that (as opposed to the value of the cursor coordinates):
If you swap out e.NewPosition with your query value (eg. today's date), the code should do what you want.
// Cursor Position Changing Event
private void chart1_CursorPositionChanged(object sender, CursorEventArgs e)
{
    //Get the nearest record and use its X value as the position
    double coercedPosition = chart1.Series[0].Points.Aggregate((x, y) => Math.Abs(x.XValue - e.NewPosition) < Math.Abs(y.XValue - e.NewPosition) ? x : y).XValue;

    //Set cursor to the coerced position
    chart1.ChartAreas[0].CursorX.Position = coercedPosition;

    SetPosition(e.Axis, coercedPosition);
}

// Update the labels with the values at the indicated position
private void SetPosition(Axis axis, double position)
{
    if (double.IsNaN(position))
        return;

    if (axis.AxisName == AxisName.X)
    {
        //Get the value at the position
        DateTime dt = DateTime.FromOADate(position);

        //set the timestamp label
        lbl_CursorTimestampValue.Text = dt.ToString();

        //get the point at that timestamp (x value)
        var point = chart1.Series[0].Points.FindByValue(position, "X");

        //set the y value label
        lbl_CursorYValue.Text = point.IsEmpty == true ? "--" : point.YValues[0].ToString();
    }
}

Also note that if you will want to convert your DateTime to an OA value:
double yourOADate = yourDateTime.ToOADate();


text:
Q: Left += Operation for Strings In Python, the += operation is a right-action, meaning that a+=b is equivalent to a=a+b.
Since, for strings, this operation is not commutative, it raises the question if there is a similar operator for a left-action, i.e. some operator (or other hack) say %= such that a%=b does a=b+a?
Addendum
The solutions so far, except the obvious a=b+a, involved overriding the str.__add__ method which, as pointed out by @BrianJoseph, was not quite what I had in mind since it merely shifts the problem to the other extreme.
The following workaround, involving this amazing hack, illustrates the behaviour I was seeking.
Prelims
# -------------------------------------------------------------
# Following class can be found in Tomer Filiba's blog
# Link provided in the question
from functools import partial

class Infix(object):
    def __init__(self, func):
        self.func = func
    def __or__(self, other):
        return self.func(other)
    def __ror__(self, other):
        return Infix(partial(self.func, other))
    def __call__(self, v1, v2):
        return self.func(v1, v2)
# -------------------------------------------------------------

# Custom Class
class my_str(str):
    def __init__(self, string):
        self.string = string
    def __str__(self):
        return self.string.__str__()
    def __repr__(self):
        return self.string.__repr__()
    @Infix
    def left_assign(self, string):
        self.string = string + self.string

Example
# Testing
a = my_str('World')
b = 'Hello'
print(a)
# World
a |my_str.left_assign| b
print(a)
# HelloWorld

Of course the line a |my_str.left_assign| b is not exactly easier to write then a = b + a, but this was just an example for illustrations.
Finally, for those to whom my non-edited question might have been unclear: I am (was) wondering if a=b+a can bone writing a just once (analogously to a+=b for a=a+b).

A: If you're asking if there's a single operator to prepend strings (instead of appending them like +=), I don't think there is one.  Writing out:
b = a + b

is the most succinct way I know of how to prepend a onto b.
(Interestingly, because string appending is non-commutative, Larry Wall (the creator of Perl) chose to use . as the string-appending operator, so as to leave + completely commutative and mathematical, in that a += b means both a = a+b and a = b+a.  Unless you explicitly overload it, of course.)

A: Short answer is no.
The long answer:
You can create your own class based on str and override some operator action.
class A(str):
    def __add__(s, st):
        return st + s

This one will work as:
>>> A(50)
'50'
>>> A(50) + 'abc'
'abc50'
>>> a = A('aaa')
>>> a += 'ccc'
>>> a
'cccaaa'

But you definitely will need to learn documentation about overriding "magic" methods such as __add__ to be sure that you'll implement right behavior, because there is many side-cases in which it could work not ideal in current implementation. For example, current implementation causes RecursionError if both sides is instances of A class.
Honestly, all this stuff is not very good practice because it's not about Zen of Python and may be cause of headache of other programmers that will work with this code. So all these things is nothing but interesting just for fun experiments. For real convenient solution see short answer.
P.S.: Of course, you can override some other operator instead of +. For example, __mul__ is for *. You can even override bitwise ops such as << and &
P.P.S.: The operator that you mentioned, %=, really exists. Not much people know about it, but it is a shorthand for a = a % b, it's very useful for formatting strings:
a = 'Some number: %d; some string: %s'
a %= 1, 'abc'
print(a)

Will give you Some number: 1; some string: abc

A: No, there is no such operation. The complete list of operators can be found in the Python language reference, starting at section 6.5.

A: You could define another class inheriting from str:
class myStr(str):
    def __init__(self, s):
        super(str, s)

    def __add__(self, other):
        return other + self

s = myStr("abc")
print(s) #prints 'abc'

s += "d"
print(s) #prints 'dabc'

I don't see any use case frankly, though.

A: Short answer is no. Read here. The += is called augmented assignment
It is implemented for the common binary operators in python:"+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="| ">>=" | "<<=" | "&=" | "^=" | "|="
You can change the workings of the augmented assignment operation by changing the way the operation is computed at class level, e.g. in your example:
class Foo(str):
    def __add__(s, other):
        return other + s

Although I would not recommend it.


text:
Q: How to map data from Parent table to its child table on change function I created a function that map data into child table when some fields changes in parent table, data saves in child table when parent table fields changes I can see it in the db, but  the problem is data doesn't display in tree grid view of child table.
Here is my code :
def on_change_test(self, cr, uid, ids, district_id,
                   select_db,sub_district_id,ward, context = None):
    obj_master = self.pool.get('Parent_table')
    MasterID = obj_master.create(cr, uid,
              {'district_id':district_id,
               'sub_district_id':sub_district_id,
               'to_master_ward':ward,
               'select_db':select_db})
        obj_child = self.pool.get('Child_table')
        obj_child.create(cr, uid,
                        {'sex':'male',
                         'wardID':MasterID,
                         'from_ward':child_line_id.address_id.name,
                         'Parent_ID':child_line_id.id,
                         'date_o_birth':child_line_id.date_of_birth})
    return True

A: def create(self, cr, uid, vals, context=None):
    obj_master = super(parent_table,self).create(cr,uid, vals, context=context)
    obj_child = self.pool.get('child.table')
    obj_child.create(cr, uid,{'field_name':obj_child.field_value......})

your method is not correct , you can do it by overriding the create method with a super call


text:
Q: How to programmatically obtain the mobile number from the current device? I want to obtain mobile number from device for registration page.
I used TelephonyManager but its not working in all devices and I also used GoogleApiClient with HintRequest in this service open dialogbox to select mobile number but its looking weird, so please suggest me a better option which is supported all android devices

A: I think the easiest way is to ask user to manually type his own phone number. Telephony permission looks dangerous and you can face issues with releasing to google play store.
Typically, you may also need to intercept incoming sms messages


text:
Q: strange array values (C, psoc, usbuart) I am still fairly new to programming,  so I'm sorry in advance if my terminology/formatting isn't up to scratch.
I am currently working on an element of a musical instrument that will allow me to actuate a button multiple times with a varying time delay between presses, record this and loop the pattern.
I currently have an array for recording the timings of the button presses, I am using USB-UART/terra term to check my values are being recorded correctly but I am finding the array being populated with seemingly nonsensical values. I am wondering where this data is coming from.
Highlighted in red in the image below are the values that I expect to be retained in the T0, T1..etc values. In short - Mtapi is the int used in selecting what location in the array I want to store the current milliTAP value (T0, T1 etc..). But as you can see from the following data lines they are being replaced by 10 digit numbers.
Basically, I am wondering what those numbers are, why I am seeing them and how to stop them populating my array!
I did think they maybe something to do with data locations of the array instances? but honestly this is all new to me and I have no idea. That and how they are changing at what seems to be random to me.

Any help or direction to further reading is much appreciated.
you can see the code on GigHub here
for quick reference (shortened for posting here):-
if ((Mtapi==0)&&(MTap[0]>0)&&(MTapBtnCHK==0))
{
     int i;
     for (int i=0; i<63; i++)
     {
         MTap[i]=0;
     }
}

if (MTapBtn_Read()==0)
{
    MultiTapTempo();
}
if (MTapBtn_Read()==1)
{
    MTapBtnCHK=0;
}

//gap in code posted here, then:
void MultiTapTempo(void)
{
    if (MTapBtnCHK==0)
    {
        Mtapi++;
        MTapBtnCHK=1;

        if(Mtapi==0){}
        if(Mtapi==1){MTap[0]=millisMTAP;}
        if(Mtapi==2){MTap[1]=millisMTAP;}
        if(Mtapi==3){MTap[2]=millisMTAP;}
        if(Mtapi==4){MTap[3]=millisMTAP;}
        if(Mtapi==5){MTap[4]=millisMTAP;}
        if(Mtapi==6){MTap[5]=millisMTAP;}
        if(Mtapi==7){MTap[6]=millisMTAP;}
        if(Mtapi==8){MTap[7]=millisMTAP;}
        if(Mtapi==9){MTap[8]=millisMTAP;}
     }

A: the problem was that my character array holding the data to send over UART was not large enough to hold the information i was trying to send.
this line in the code--
char buff[64];//output UART buffer


text:
Q: replace numpy array loop in array calculations Hi is there a faster and easy option to do below code without using loop? When increasing multiplier value the computation is time expensive.
import numpy as np
import random
import timeit

multiplier = 2
vectors_number = 4 * multiplier
variable_number = 6
input_matrix = np.random.uniform(-5, 5, (vectors_number, variable_number))

offset = np.arange(multiplier)[:, None]*4
winning_matrix = np.random.rand(multiplier, 4).argsort(1)[:, :4] + offset

out_matrix = np.zeros(shape=(multiplier, variable_number))
start = timeit.default_timer()

for i in range(winning_matrix.shape[0]):
    for k in range(variable_number):
        out_matrix[i][k] = input_matrix[winning_matrix[i][2]][k] -
                           input_matrix[winning_matrix[i][1]][k]

end = timeit.default_timer()
print('Computation time %f' % (end - start))

A: How about
out_matrix = input_matrix[winning_matrix[...,2]] - input_matrix[winning_matrix[...,1]]

Using
multiplier = 200
vectors_number = 4 * multiplier
variable_number = 6000

I get

Computation time 1.576242

for the original method, and

Computation time 0.027881

for my code above. So a speed up of about 140.
Note that you can also get rid of the allocation & initialisation step:
out_matrix = np.zeros(shape=(multiplier, variable_number))

since out_matrix is now created for you.


text:
Q: MPDF not writing html footers properly I am using mpdf to generate pdfs. So there is a problem when dealing with html footer. My Configuration is like this;
private $pdfMode = ''; //For loading fonts
private $pageFormat = 'A4'; //Default is A4 size
private $marginLeft = 2;
private $marginRight = 2;
private $marginTop = 2;
private $marginBottom =2;
private $marginHeader = 9;
private $marginFooter = 9;

function __construct() {
    parent::mPDF($this->pdfMode, $this->pageFormat, '', '',$this->marginLeft,$this->marginRight, $this->marginTop, $this->marginBottom, $this->marginHeader, $this->marginFooter);
    $this->setAutoTopMargin= true;
    $this->setAutoBottomMargin = true;
    parent::SetAutoFont(AUTOFONT_ALL);
}

When setting AutoTopMargin is true, It is working fine even though when header is too large. But footer content is cropped and there is a so much space between body and footer
Please help in this...


text:
Q: in mysql trigger.. how to use insert into and update query I have a product_price_log table. I updated where ever new price is updated in product_price
table.
I am using a trigger:
drop trigger if exists product_update;

delimiter $$
CREATE TRIGGER product_update
BEFORE update ON w3xab_virtuemart_product_prices
FOR EACH ROW
BEGIN
DECLARE virtuemart_product_id int;
DECLARE old_product_price decimal(15,5) default 0;
DECLARE new_product_price decimal(15,5) default 0;
DECLARE price_update_date DATE;

IF (new.product_price <> old.product_price)
THEN

INSERT into product_price_log
(virtuemart_product_id,old_product_price, new_product_price,  price_update_date)
VALUES (new.virtuemart_product_id, old.product_price, new.product_price, CURDATE())
ON DUPLICATE KEY UPDATE
old_product_price = VALUES(old.product_price),
new_product_price = VALUES(new.product_price),
price_update_date = CURDATE();

END IF;
    END$$
    delimiter ;

now no error..but update not working when i try to update price... only insert is working
i set virtuemart_product_id is primay key
i dont know whats going i m totally stuck at this point... cant understand why not updating..

A: I don't think you can do VALUES(CURDATE()) since it isn't actually a column name.
Try just price_update_date=CURDATE()


text:
Q: Short story about a space pilot trapped in a "Hab" by a robot Dying to find this story I read in the lates 70s or 80s. A fighter pilot from a space battle crashes and takes refuge in a Hab or pod meant for emergencies. Unfortunately, every time he moves, the maintenance robot/drone thinks he is a threat and attacks him. He ultimately defeats the robot by shining his flashlight on a panel where the robots computer resides. The robot attacks the movement and disables itself.

A: Life Hutch by Harlan Ellison
fighter pilot takes refuge in a life hutch. Maintenance robot has malfunctioned so it attacks anything that moves. Pilot is wounded by robot and figures out that if he moves again the robot will kill him. Pilot blinks his flashlight on panel containing robots brain.