text:
Q: Tensorflow 2.1.0 - AttributeError: module 'tensorflow' has no attribute 'RunMetadata' I am trying to find out the number of FLOPS my model uses using this code that I got online:
def get_flops(model):
    run_meta = tf.RunMetadata()
    opts = tf.profiler.ProfileOptionBuilder.float_operation()

    # We use the Keras session graph in the call to the profiler.
    flops = tf.profiler.profile(graph=K.get_session().graph,
                                run_meta=run_meta, cmd='op', options=opts)

    return flops.total_float_ops  # Prints the "flops" of the model.

# .... Define your model here ....
print(get_flops(model))

However, running this code gives me this error:
Traceback (most recent call last):
  File "/Users/Desktop/FYP/Code/Python/code/main.py", line 243, in <module>
    print(get_flops(model))
  File "/Users/Desktop/FYP/Code/Python/code/main.py", line 232, in get_flops
    run_meta = tf.RunMetadata()
AttributeError: module 'tensorflow' has no attribute 'RunMetadata'

How can I bypass this error? I have read online and the only help that I got is to update my tensorflow version. However, this is the most updated version.

A:
AttributeError: module 'tensorflow' has no attribute 'RunMetadata'

You have received this error because the code which you have executed is compatible only to Tensorflow 1.x.
I have executed your code successfully without any changes in TF 1.x
%tensorflow_version 1.x
import tensorflow as tf
from keras import backend as K
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
print(tf.__version__)

def get_flops(model):
    run_meta = tf.RunMetadata()
    opts = tf.profiler.ProfileOptionBuilder.float_operation()

    # We use the Keras session graph in the call to the profiler.
    flops = tf.profiler.profile(graph=K.get_session().graph,
                                run_meta=run_meta, cmd='op', options=opts)

    return flops.total_float_ops  # Prints the "flops" of the model.

# .... Define your model here ....
model = Sequential()
model.add(Dense(8, activation = 'softmax'))
print(get_flops(model))

Output:
Using TensorFlow backend.
1.15.2
0

In TF 2.x you have to use tf.compat.v1.RunMetadata instead of tf.RunMetadata
To work your code in TF 2.1.0, i have made all necessary changes that are compliant to TF 2.x
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
print(tf.__version__)
def get_flops(model):
    run_meta = tf.compat.v1.RunMetadata()
    opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()

    # We use the Keras session graph in the call to the profiler.
    flops = tf.compat.v1.profiler.profile(graph=tf.compat.v1.keras.backend.get_session().graph,
                                run_meta=run_meta, cmd='op', options=opts)

    return flops.total_float_ops  # Prints the "flops" of the model.

# .... Define your model here ....
model = Sequential()
model.add(Dense(8, activation = 'softmax'))
print(get_flops(model))

Output:
2.1.0
0

Please refer all compatible symbols for Tensorflow 2 here

A: replace run_meta with the following
run_meta= tf.compat.v1.RunMetadata()

check this link for more information: https://www.tensorflow.org/guide/migrate


text:
Q: What is the meaning of // (double forward slash) and : (colon) in bazel build //my_folder/my_subfolder:node_modules? I do not understand this syntax:
bazel build //<my_dir>/<my_subdir>:node_modules

I believe // is to specify a route relative to a WORKSPACE, but the meaning of : is unclear to me.
Similarly, you can use bazel build ... and that seems to build all subfolders within a WORSKPACE.
What are all these strange symbols? Where are they documented?

A: The documentation for this is here:
https://docs.bazel.build/versions/master/build-ref.html
Additional syntax related to external dependencies is documented here:
https://docs.bazel.build/versions/master/external.html
Things like ... are called target patterns and are documented here:
https://docs.bazel.build/versions/master/guide.html#target-patterns

I believe // is to specify a route relative to a WORKSPACE

Correct, // starts an "absolute label"

meaning of :

This separates the package (on the left) from the target name in the package (on the right).

you can use bazel build ... and that seems to build all subfolders within a WORSKPACE

That will build all targets in the current package (i.e., current working directory) and subpackages of the current package. If you're at the root of the workspace, then it's the same as //... which will build everything.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save Items in Local Storage with specific ID I am practicing blog stuff. posting and deleting posts. mini social media I can say. And I wanted to save posts on localStorge. however I could save only 1 post at a time. and then I wanted to do it with IDs.
I create id with random number generator:
let newId = Math.floor(Math.random() * (1000000 - 100000) + 100000)
let postContents = {
    ID : newId,
    text: value,
}

an then I upload those values in let storedPosts = [] array.
then I save it to local storage with JSON:
let toJson = () => {
    localStorage.setItem('storedPosts', JSON.stringify(storedPosts));
}

and then I get it from Local Storage:
let storedJsonPosts = localStorage.getItem('storedPosts')
let storedPosts_toUpload = JSON.parse(storedJsonPosts)

and then I join these two arrays together:
let storedPostsArray = storedPosts.concat(storedPosts_toUpload)

and after this I don't know what to do. I tried this:
let uploadStoredPosts = () => {
    for (let i = 0; i < storedPostsArray.length; i++) {
        let post = document.createElement('div')
        $post_place.appendChild(post)

        let text = document.createElement('p')
        post.appendChild(text)
        text.textContent = storedPostsArray[i].text
    }
}

but it showed this:

It couldn't reach array values. plz help

A: Is this something that you're after?
The code reads from localStorage, parses that information, returns an empty array if it's the first time the user posted, pushes a new value to the array, stores that array by stringifying it, and the appending the new value to the document.
If you want the page to read from localStorage on page load, you need to add a function that reads from localStorage, and then loops through all posts to add each one of them by using appendToDocument().
StackOverflow doesn't allow the use of localStorage, so I used a variable for demo purposes.
I left out id as a property. You can play around with that by yourself, but I would suggest to use a timestamp as a foreign key ("id").

var justForDemoPurpose = null;

const addPostBtn = document.getElementById("add-button");
const addPostInput = document.getElementById("add-post");
const postContainerEl = document.getElementById("post-container");

addPostBtn.addEventListener('click', addPost);

function readFromLocalStorage(key) {
  let localStorageItem = JSON.parse(justForDemoPurpose);
  // let localStorageItem = JSON.parse(localStorage.getItem(key));

  console.log('returning items:', localStorageItem);

  return localStorageItem;
}

function storeInLocalStorage(key, value) {
  justForDemoPurpose = JSON.stringify(value);
  // JSON.stringify(localStorage.setItem(key, value));
}

function addPost() {
  let postValue = addPostInput.value;

  if (postValue) {
    const LOCAL_STORAGE_KEY = 'posts';
    let storedPosts = readFromLocalStorage(LOCAL_STORAGE_KEY) || [];

    storedPosts.push(postValue);
    storeInLocalStorage(LOCAL_STORAGE_KEY, storedPosts);

    appendToDocument(postValue);
  }
}

function appendToDocument(postValue) {
    let divEl = document.createElement('div')
    divEl.textContent = postValue;

    postContainerEl.appendChild(divEl);
}

  <input id="add-post" placeholder="Type here"> <button id="add-button">Add Post</button>


text:
Q: Escape square brackets in ExtJS template markup (XTemplate)? I'm using ExtJS 4 and have a need to use sets of square brackets within XTemplate markup. This need arises from the fact that I require the square brackets to be preserved in the rendered output. More specifically, I'm dealing with object properties that contain a dash (minus sign) in their names, which requires one to use square brackets to access those properties' values in JavaScript, e.g.:
raw.cmsInstances[\'cms-thumb\'].url
Anyone who has worked with CSS in JavaScript has encountered this issue with dashes in CSS property names.
I haven't been able to find an alternate syntax (to the square bracket notation) that achieves the same result.
I have worked-around this limitation using an ExtJS custom object type. In particular, I am accessing ExtDirect's raw input and pushing values therefrom into the template markup using the following technique:
Ext.define('my.ux.file.IconBrowser', {
    tpl: [
        '<tpl for=".">',
            //Am trying to use this notation, due to dash in property name:
            //''
            //But this causes XTemplate to evaluate whatever is between the square
            //brackets.

            (!Ext.isIE6? '' :
            '

'),
        '</tpl>'
    ],
    initComponent: function() {
        Ext.data.Types.RAW = {
            convert: function(v, data) {
                return data.raw;
            },
            type: 'Raw'
        };
        var types = Ext.data.Types;
        this.store = Ext.create('Ext.data.Store', {
            proxy: {
                type: 'direct',
                directFn: this.loadLibraryApi,
                paramOrder: ['instanceType'],
                reader: {
                    root: 'data'
                }
            },
            fields: [
                {name: 'raw', type: types.RAW}
            ]
        });

        this.callParent(arguments);
    }
});

I would much prefer to escape the square brackets or find an alternative to them that achieves the same result.
Thanks in advance!


text:
Q: PHP CURL Enable Linux I have some php scripts that I've been running on an Apache server on a windows machine. These scripts use curl which isn't enabled by default in php. For windows enabling it was as easy and un-commenting the line with the curl .dll file in the php.ini file. Well since Linux uses .so instead of .dll files that wont work.
Does anyone have any idea how to enable curl on an Apache server running on a Linux machine? Php is already installed so I'm really hoping for a solution that doesn't involve re-installing php. Thanks in advance!

A: You just need to install the needed package if not already installed.
On ubuntu, you just type:
$ sudo apt-get install php5-curl

RPM-based distribution should have a similar package name like yum install for fedora and centos.


text:
Q: Firebase OrderByChild return extra empty child I'm trying to make query with orderBy and I get another empty child.
component .ts
 loadCourses(){
this.profileProvider.getSpecificCourse().on('value',f=>{
  console.log(f.val());
})

}
provider
     getSpecificCourse(){
  return firebase.database().ref(`CoursesRelated`).orderByChild('cs').equalTo(2);

 }

firebase structure

getting the another empty node

expected result:
the same result without the empty node.
in addition I want to make another orderby and get the ls equal to 6, how can I do that?

A: You're using numeric indexes to store the nodes, which means that Firebase SDK interprets them as an array. For the results: { "0": {...}, "2": {...} it then creates a three element array [{...}, null, {...}].
For a good, longer explanation of how Firebase deals with arrays, read this blog post Best Practices: Arrays in Firebase.
The way to get rid of this behavior is to not use sequential numeric keys. The simplest way to do this is to either add the items by calling Firebase's push() method (which generates keys in a format -K... and is explained here), or by prefixing the numbers with a fixed string (e.g. Course0, Course1, Course2). Since these format are strings, they bypass the Firebase SDK's array-coercion logic.


text:
Q: clipboard.js - paste multiple lines per cell to Excel I have a problem I'm trying to solve, namely that I'd like to be able to paste the contents of the clipboard (filled using clipboard.js i) to Excel with some cells having two rows.
I won't bore you with the ins and outs of my project, but here's a simplified version:
Currently my clipboard.js implementation iterates through a javascript object pulling stuff out.  I'm building it so that it can be pasted in to excel - tab separated with \t and each 'row' ends with a \n.
For example, the clipboard string for a row looks like this (spaces and variable names for readability):
"avatar\t date\t text\t time\n"

...which when pasted in to Excel produces, as expected, avatar, date, time and text in their own cells - great.
What I want to do though is have multiple rows per cell.  For example, the 'alpha' column will hold two things - an avatarImage, and avatarName.
Now obviously I can't use (spaces for readability):
avatarImage\n avatarName\t date\t time\t text

...because that puts avatarImage in row 1 and the rest on row 2.
I'm fairly new to software development so I lack the wizardry to see a solution to this as yet, but I don't doubt there is a way.
Does anyone have any suggestions or ideas?  Honestly anything at all would be much appreciated.
Cheers,
Dave

A: The js assignment would look like:
 var s = '"avatarImage\n avatarName"\t date\t time\t text';

Here's the VBA equivalent (how I tested that clipboard string): running this then pasting into A1 gives the output shown.
Sub Tester()
   ''Add reference to: Microsoft Forms 2.0 Object Library
    Dim d As New DataObject

    d.SetText """a" & vbLf & "b""" & vbTab & "c"
    d.PutInClipboard

End Sub


text:
Q: Creating a 'second' mouse to do actions without using your normal one I'm looking to develop a program in C# that has a second mouse. What I mean by this is that if I pressed the 1 button on my keyboard, it would click on a certain location on the client window. But when the button is clicked, your normal, visible cursor doesn't move and you can freely control it.
I have no idea if this is possible and I have a feeling it won't be, but if it is... Does anyone have an idea how to do it? Or where I could start?

A: How important is it that the mouse does not move? If not terribly, You could jump the location of the mouse to where you needed to click, simulate the click, and then jump the mouse back to where it was. As this could be done very quickly, it would still give the appearance of having free control over the mouse.


text:
Q: Where is the mistake in finding $c$ and $n$ of $\sqrt{x^3+4x} - \sqrt{x^3+x} \sim cx^n$ for $x \to 0$ and $x \to +\infty$ First we simplify in the following way:
$$\frac{3}{\sqrt{x}\left( (1+\frac{4}{x^2})^{1/2}+(1+\frac{1}{x^2})^{1/2} \right)}$$
For $x \to 0$:
We then postulate that since the above must be equivalent to some constant times $x$ to some power, then the inverted fraction is equivalent to some $\frac{1}{cx^n}$, I actually think that this step is flawed, because for $x \to 0$, $\frac{1}{cx^n}$ is indeterminate for $x \neq 0$. We then have
$$\lim_{x \to 0} \frac{\sqrt{x}}{3}\left(\left(1+\frac{4}{x^2}\right)^{1/2}-1 \right) + \lim_{x \to 0} \left( \left(1+\frac{1}{x^2} \right)^{1/2}-1 \right) = \\ \frac{\sqrt{x}}{6} \left( \frac{4}{x^2} + \frac{1}{x^2} \right)$$
And so $c=6/5$ and $n=1.5$, because we have to invert back.
For $x \to +\infty$:
We invert again, but this time also divide by $cx^n$. So that we end up with:
$$\lim_{x \to +\infty} \frac{c}{3} x^n \sqrt{x} \left(\left( 1+\frac{4}{x^2} \right)^{1/2} + \left( 1+\frac{1}{x^2}\right)^{1/2} \right) = \\
\frac{2c}{3}(x^n \sqrt{x})$$
that means that $c=2/3$ and $n=0.5$.
But one or both of these solutions are, in fact, incorrect.

A: Your first line is useful when $x\to +\infty$:
$$\frac{3}{\sqrt{x}\left( (1+\frac{4}{x^2})^{1/2}+(1+\frac{1}{x^2})^{1/2} \right)}\sim \frac{3}{\sqrt{x}(1+1)}=\frac{3}{2}\cdot x^{-1/2}.$$
For $x\to 0$, you may simply note that
$$\sqrt{x^3+4x} - \sqrt{x^3+x}=\sqrt{x}(\sqrt{x^2+4} - \sqrt{x^2+1})\sim \sqrt{x} (\sqrt{4}-1)=x^{1/2}.$$
Alternative method.
In both cases, it suffices to use the following fact: as $t\to 0$,
$$\sqrt{1+t}=1+\frac{t}{2}+o(t).$$
1) As $x\to 0$,
$$\begin{align}
\sqrt{x^3+4x} - \sqrt{x^3+x}&=x^{1/2}\left(2\sqrt{1+(x/2)^2} - \sqrt{1+x^2}\right)
\\&=x^{1/2}\left(2(1+\frac{(x/2)^2}{2}+o(x^2)) - (1+\frac{x^2}{2}+o(x^2)\right)\\&=x^{1/2}+o(x^{1/2}).
\end{align}$$
2) As $x\to +\infty$,
$$\begin{align}\sqrt{x^3+4x} - \sqrt{x^3+x}&=x^{3/2}\left(\sqrt{1+4/x^2} - \sqrt{1+1/x^2}\right)
\\&=x^{3/2}\left((1+\frac{4/x^2}{2}+o(1/x^2)) - (1+\frac{1/x^2}{2}+o(1/x^2)\right)
\\&=x^{3/2}\left(\frac{(4-1)/x^2}{2}+o(1/x^2)\right)\\&=\frac{3}{2}\cdot x^{-1/2}+o(x^{-1/2}).\end{align}$$

A: For $x\to0$, $$\sqrt{x^3+4x} - \sqrt{x^3+x}=\frac{3x}{ \sqrt{x^3+4x} +\sqrt{x^3+x}}=x^{1/2}\frac3{ \sqrt{x^2+4} +\sqrt{x^2+1}}\\\to x^{1/2}$$
because the denominator of the fraction tends to $3$ (the $x^2$ become negligible).
And for $x\to\infty$, $$\sqrt{x^3+4x} - \sqrt{x^3+x}=\frac{3x}{ \sqrt{x^3+4x} +\sqrt{x^3+x}}=\frac32x^{-1/2}\frac{2x^{3/2}}{ \sqrt{x^3+4} +\sqrt{x^3+1}}\\\to \frac32x^{-1/2}$$
because the denominator of the fraction tends to $2x^{3/2}$ (the additive constant become negligible; you can as well consider $y:=\dfrac1x\to0^+$).

A: For $x\to 0$, recall that firstly we can estimate
$$\sqrt{x^3+4x}\sim \sqrt{4x}\left(1+\frac14x^2\right)^\frac12=2\sqrt{x}+\frac14\sqrt{x}x^2$$
$$\sqrt{x^3+x} \sim \sqrt{x}\left(1+x^2\right)^\frac12=\sqrt{x}+\frac12\sqrt{x}x^2$$
therefore it seems that
$$\sqrt{x^3+4x} - \sqrt{x^3+x} \sim  \sqrt{x}$$
to prove that we need to show that
$$\frac{\sqrt{x^3+4x} - \sqrt{x^3+x}}{\sqrt{x}}\to 1$$
For $x\to \infty$, recall that firstly we can estimate
$$\sqrt{x^3+4x}\sim \sqrt{x^3}\left(1+2\frac1{x^2}\right)^\frac12=\sqrt{x^3}+\frac{2}{\sqrt x}$$
$$\sqrt{x^3+x} \sim \sqrt{x^3}\left(1+\frac1{2x^2}\right)^\frac12=\sqrt{x^3}+\frac{1}{2\sqrt x}$$
therefore it seems that
$$\sqrt{x^3+4x} - \sqrt{x^3+x} \sim \frac32 \frac{1}{\sqrt x}$$
to prove that we need to show that
$$\frac{\sqrt{x^3+4x} - \sqrt{x^3+x}}{\frac32 \frac{1}{\sqrt x}}\to 1$$


text:
Q: 5.16 LAB: Adjust list by normalizing _ zybook - Java 5.16 LAB: Adjust list by normalizing
When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This adjustment can be done by normalizing to values between 0 and 1, or throwing away outliers.
For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow. Assume that the list will always contain fewer than 20 floating-point values.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Ex: If the input is:
5 30.0 50.0 10.0 100.0 65.0
the output is:
0.30 0.50 0.10 1.00 0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0.
For coding simplicity, follow every output value by a space, including the last one.
I have been confused about how to do floating-point values in arrays and loops as in my book it never went over that.
  Scanner scnr = new Scanner(System.in);
  double numElements;
  numElements = scnr.nextDouble();
  double [] userList = new double [numElements];
  int i;
  double maxValue;

  for (i = 0; i < userList.length; ++i) {
     userList[i] = scnr.nextDouble();
  }

  maxValue = userList[i];
  for (i = 0; i < userList.length; ++i) {
     if (userList[i] > maxValue) {
        maxValue = userList[i];
     }
  }

  for (i = 0; i < userList.length; ++i) {
     userList[i] = userList[i] / maxValue;
     System.out.print(userList[i] + " ");
     System.out.printf("%.2f", userList[i]);
  }

}
}
It's outputting:
LabProgram.java:8: error: incompatible types: possible lossy conversion from double to int
  double [] userList = new double [numElements];

I am confused about how to move forward, any help will be much appreciated!

A: Just change the data type of numElements to int and the scanner command to int as well
Like this:
int numElements = scnr.nextInt();


text:
Q: how to have windows.location.href response act as a promise I'm using implicit grant flow in angular 4 where the recommended approach is to set windows.location.href to the auth provider url.
Can I create a promise from windows.location.href so I know to trigger a follow-up action once the promise returns?
If a promise isn't an option are there alternatives?


text:
Q: How to move box without clearRect() in JS' canvas better? everyone. I am going to develop a game like Piano Tiles in JS.
The problem I encounter is that I need to let several tiles moving which might appear in different times, it let me can't use clearRect() and then draw next position's tiles, if I do so, my multiple tiles will twinkle(because when A tiles call clearRect, B tiles will disappear, which is shouldn't happen)
The solution I figure out is not to use clearRect() to clear whole screen ,I
just clear Rectangle where I don't want, and then fillRect(its fill style is same as my background color) to fill this little empty rectangle again.
My solution can almost reach my purpose, but there still some flaws in my code. When my black tiles moving, there still are some tiny gray rectangle appear (and disappear soon).
I want to know are there any better way can I move multiple box(or rectangle) ?
PS: my background is using gradient so it probably make my problem more tough.
Following is my code:
myTiles store two tiles, paintWindow function is aim at drawing background, my solution is written in move() function
var c = document.getElementById("piano");
var context = c.getContext("2d");

startGame();
function startGame(){
  paintWindow();
  myTiles = [];
  myTiles[0] = new Block(0);
  myTiles[1] = new Block(1);
}
function paintWindow(){
  my_gradient = context.createLinearGradient(0,0,0,600);
  my_gradient.addColorStop(0,"rgba(65,234,246,0.6)");
  my_gradient.addColorStop(1,"rgba(254,74,251,0.5)");

context.fillStyle = my_gradient;
context.fillRect(0,0,300,600);

context.beginPath();
context.moveTo(72,0);
context.lineTo(72,600);
context.strokeStyle = "white";
context.stroke();

context.beginPath();
context.moveTo(148,0);
context.lineTo(148,600);
context.strokeStyle = "white";
context.stroke();

context.beginPath();
context.moveTo(226,0);
context.lineTo(226,600);
context.strokeStyle = "white";
context.stroke();

context.beginPath();
context.moveTo(0,470);
context.lineTo(300,470);
context.strokeStyle = "white";
context.stroke();
}

function Block(index){
 this.index = index;
 this.appearPos = Math.floor(Math.random()*4);

 this.width = 70;
 this.height = 120;
 this.color = "black";
  switch(this.appearPos){
    case 0:
        this.x = 0;
        this.y = 0;
        break;
    case 1:
        this.x = 75;
        this.y = 0;
        break;
    case 2:
        this.x = 152;
        this.y = 0;
        break;
    case 3:
        this.x = 228;
        this.y = 0;
        break;
}
context.fillStyle = this.color;
context.fillRect(this.x,this.y,this.width,this.height);
this.interval = setInterval(move,10,this.index);
}
function move(index){
//context.clearRect(0,0,300,600);
//paintWindow();
myTiles[index].y += 1;
context.fillStyle = "black";
context.fillRect(myTiles[index].x,myTiles[index].y,70,120);

context.clearRect(myTiles[index].x,myTiles[index].y-2,70,2);
context.fillStyle = my_gradient;
context.fillRect(myTiles[index].x,myTiles[index].y-2,70,2);
}

A: I would suggest you not to create a new interval for each new block, but rather create one interval in which you update all the blocks at once. This might look something like this:
setInterval(moveAll,10);
function moveAll(){
    context.clearRect(0,0,c.width,c.height);

    for (var i=0;i<myTiles.length;i++){
        move(i);
    }
}

If you can't do that for some reason, you could also draw the tiles in a separate canvas so the background is preserved when clearing a tile:
<div>
    <canvas id="background" style="position:absolute;left:0;top:0;">
    <canvas id="tiles" style="position:absolute;left:0;top:0;">
</div>

That way the second canvas would be displayed over the first one, but the background would still be visible behind it where it is transparent.

A: Just use CSS for the gradient background. See this fiddle. Pay attention to the CSS:
<style>
    #piano {
        background: linear-gradient(rgba(65,234,246,0.6), rgba(254,74,251,0.5));
    }
</style>

Also get rid of everything about the gradient background in your paintWindow function:
  function paintWindow() {
    context.beginPath();
    context.moveTo(72, 0);
    context.lineTo(72, 600);
    context.strokeStyle = "white";
    context.stroke();

    context.beginPath();
    context.moveTo(148, 0);
    context.lineTo(148, 600);
    context.strokeStyle = "white";
    context.stroke();

    context.beginPath();
    context.moveTo(226, 0);
    context.lineTo(226, 600);
    context.strokeStyle = "white";
    context.stroke();

    context.beginPath();
    context.moveTo(0, 470);
    context.lineTo(300, 470);
    context.strokeStyle = "white";
    context.stroke();
  }

That's all!


text:
Q: using mixed effect logistic regression properly I am new to data analysis and now working on a Mixed Effects Logistic Regression Model.Currently I have a data frame (model_data) that looks like the following:
Vehicle_id    entry_time         exit_time          last_veh_time  vehicle_type
__________     ___________       __________        ____________    ____________
   1        2017-01-31 00:00:00  2017-01-31 00:00:00    300         4 wheel
status
_______
  0

Likewise, I have information(nearly a million rows) on all vehicles entering a place and exiting the same place. status can be either 1 or 0 for all of these. last_veh_time is the last vehicle passed the same place before how much time. I want to know the probability of a getting status 0 for a vehicle based on entry_time and last_veh_time. So here my response is status and which will be my dependent variable?Is it entry_time and  last_veh_time?Any help is appreciated


text:
Q: AFNetworking post image issue in iOS Client ask me to POST some data fields: type, description, email, phone, price, location, photo (file attachment). Mime-Type: multipart/form-data
I have success with all fields except images.
I am using next code:
    UIImage *testImage = [UIImage imageNamed:@"landish.jpeg"];
    NSDictionary *parametres = @{@"type" : @"Suche",
                             @"description" : @"Flowers",
                             @"email" : @"myemail@ya.ru",
                             @"phone" : @"+565124512645",
                             @"price" : @"100",
                             @"location" : @"Gorppingen",
                             @"image" : testImage};

    UIImage *image = param[@"image"];
    NSURL *url = [NSURL URLWithString:API_URL_BASE];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    NSMutableDictionary *mutableDict = param.mutableCopy;
    [mutableDict removeObjectForKey:@"image"];
    param = mutableDict;
    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"
                                    path:@"anzeigen.php"
                                    parameters:param
                                    constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"landish" fileName:@"landish.jpeg" mimeType:@"image/jpeg"];
    // etc.
}];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Request Successful, response '%@'", responseStr);
        completition (YES);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
        completition (NO);
    }];
    [httpClient enqueueHTTPRequestOperation:operation];

I send successfully text fields, but image not shown in iPhone, that must work, because from Android app it's sending successfully for the same API, but I cann't talk with that developer
If I try use nil parameters and send only image
 NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"
                                 path:@"anzeigen.php"
                                 parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"landish" fileName:@"landish.jpg" mimeType:@"image/jpeg"];
    // etc.
}];

I take next in log
 2013-10-23 02:41:26.345 ****[2280:c07] [HTTPClient Error]: Expected status code in (200-299), got 400

Maybe you know what I make wrong?


text:
Q: How to mine Specified from text in python? I have an output from a program as a text like:
------------
Action specified: GetInfo

Gathering information...

Reported chip type: 2307

Reported chip ID: 98-DE-94-93-76-50

Reported firmware version: 1.08.10

------------

But I must save just, Reported chip type: value "2307" in a variable.
how it's possible?

A: You would usually do something like this with regex
import re
match = re.search('Reported chip type:\s(?P<chip_type>\d+)', my_text)
chiptype = int(match.group('chip_type'))

>>> print chiptype
2307

In your case though, it's probably simple enough to just use a couple splits:
chiptype = int(my_text.split('Reported chip type:', 1)[-1].split('\n')[0].strip())

A: Assuming that you can read the file and have read it into a variable named text:
for line in text:
    if line.startswith("Reported chip type:"):
        _, chiptype = line.split(':')
        break

print chiptype

This will put the first instance of "Reported chip type:"'s value into chiptype.
Your output looks like this:
 2307

Notice that there is a leading space. We can convert this to an int if you know it is always an int you can do this:  chiptype = int(chiptype). If it's just a string, you can strip of the leading space: chiptype = chiptype.strip()


text:
Q: How to schedule a job once every Thursday using Kue? Using Kue, how do I schedule a job to be executed once every Thursday? The Kue readme mentions that I can delay a Job, but what about repeatedly executing the Job at a specific time?
I can do what I want with a cron job, but I like Kue's features.
What I want is to process a Job once anytime on Thursday, but only once.

A: I had a similar question and I basically came up with the following. If anyone else has a different solution I would love to see some other ideas.
var jobQueue = kue.createQueue();

// Define job processor
jobQueue.process('thursday-jobs', function (job, done) {

  var milisecondsTillThurs = // TODO: Get the time until next thursday.  For this I used moment.js

  // do this job again next Thursday
  jobQueue.create('thursday-jobs').delay(milisecondsTillThurs).save();

  // For Example purpose this job waits then calls done
  setTimeout(function () {
      done();
  }, 10000);

});

// Use some initialization code to check if the job exists yet, and create it otherwise
kue.Job.rangeByType('thursday-jobs','delayed', 0, 10, '', function (err, jobs) {
    if (err) {return handleErr(err);}
    if (!jobs.length) {
        jobQueue.create('thursday-jobs').save();
    }
    // Start checking for delayed jobs.  This defaults to checking every 5 seconds
    jobQueue.promote();
});

Kue has minimal documentation, but the source is well commented and easy to read

A: Take a look at kue-scheduler.  I'm pretty sure that you should be able to do something like this:
var kue = require('kue-scheduler');
var Queue = kue.createQueue();

//create a job instance
var job = Queue
            .createJob('every', data)
            .attempts(3)
            .backoff(backoff)
            .priority('normal');

//schedule it to run every Thursday at 00:00:00
var thursday = '0 0 0 * * 4';
Queue.every(thursday, job);

//somewhere process your scheduled jobs
Queue.process('every', function(job, done) {
    ...
    done();
});

kue-scheduler docs: https://github.com/lykmapipo/kue-scheduler;
link in their docs to cron stuff: https://github.com/kelektiv/node-cron;


text:
Q: (Java) Cannot instantiate the type image? Here is my code:
package Main;
import java.awt.*;
import java.awt.Event;
import javax.swing.*;

public class Gamestart {

    public static void main(String[] args) {

    Image i = new Image();

    }

}

It gives me an error. I know that this is supposed to happen when it's an abstract class, but it's not abstract,and the superclass is just java.lang.Object. Does anyone know why this is happening?
EDIT:
Okay, i learned that java.awt.image is abstract, but still, how come it still gives me an error?

A:
I know that this is supposed to happen when it's an abstract class,
  but it's not abstract

see JavaDoc:
public abstract class Image
extends Object

The abstract class Image is the superclass of all classes that
  represent graphical images. The image must be obtained in a
  platform-specific manner.


text:
Q: crystal reports error when hosting on server I have a web application which I developed which uses crystal reports for VS 2010. The reports work fine on my machine, but when I publish the web application, I get the following error when loading the report:
Error
This group section cannot be printed because its condition field is nonexistent or invalid. Format the section to choose another condition field. Error in File temp_9b46c401-8cdb-45a6-bade-4d3e37dda1fb {572D2B99-425A-4EC5-A758-6497001368A3}.rpt: Invalid group condition.
I've searched for this and from what I can understand it's a connection issue.  But I've checked and the database connection string is fine.  Other parts of web application work fine with it.  Is there anything else I should be checking for?

A: I've resolved the issue.  It was very frustrating and so I thought I should put this here in case anyone runs into this:

*

*Make sure you have the same version of Crystal Reports Runtime installed on your server as on your development machine.  I had 13.0.3 on my development machine and 13.0.1. on my server.  Of course crystal reports gave an obscure error which makes it very difficult to know where to look.

*After I did this, I kept getting a blank page.  This linked help me resolve this issue: http://www.codeproject.com/Questions/287543/Crystal-Reports-not-rendering-when-webpage-is-serv.  Apparently visual studio doesn't copy all the necessary files for it to render the reports.
Thanks.

A: I'm not so sure that the error is because of a database connection issue. If I were you I would look into a few things first:

*

*Make sure that the database fields haven't changed. Is the application accessing the same database when deployed as it does in the development environment?

*What about Null values? Have you checked the "Convert Database Null Values" in the Report Options?

*What about the groups? Are there any formulas in them or are any of them based on groups? Browse the data to see if you get any errors.

*Just because it runs on your development machine doesn't mean the problem isn't in the datasource. Maybe one of your report's formulas is expecting a field to be non-null, and there is a single null entry. Or a date somehow got entered as #01/01/9999# and a formula in the report is expecting a realistic date.

That should get you started and maybe even solve your issue. Give us some more info about the report and the datasource if you can.


text:
Q: Mule dataweave: convert decimal to an integer I want to convert a decimal (78.22) to an integer (78) using Dataweave.
<root>
<MoneyAmountRequired>78.22</MoneyAmountRequired>
</root>

I try as below and it doesn't work if I add default 0
moneyAmountRequired: payload.root.MoneyAmountRequired as :number{format: "0"} default 0

Can some one please point out why it doesn't work when  default 0   is present.
Thank you!

A: Use floor function of dataweave.
{
    root: {
        MoneyAmountRequired: floor payload.root.MoneyAmountRequired
    }
}

A: You can try the following :-
moneyAmountRequired: payload.root.MoneyAmountRequired as :string {format: "0"}as :number default 0

Here you need to convert it first in String as :string then in number as :number
This is the only way it seems to work !!
ref:- Mule Dataweave format :number

A: Try myvalue: removeDecimal(28.23)

A: This works for me.
moneyAmountRequired: payload.root.MoneyAmountRequired as :number {format: "##,##"} as :string {format: "##"} as :number

Hope this helps.

A: Check this:
%dw 1.0
%output application/java
%var regex = /(.\d+?)0+\b/
data replace regex with ""

A: ((payload.root.MoneyAmountRequired as :string) splitBy '.')[0] as :number

If you prefer to use a function, then:
%function truncateDecimals(d) ((d as :string) splitBy '.')[0] as :number when d != null otherwise d
---
{value: truncateDecimals(payload.root.MoneyAmountRequired)}

A: After the number is formatted, it is indeed a string, but you are defaulting it to a number 0 instead of defaulting it to a string "0". But that would be enough if 'as :number' did not failed when the variable is null, which is in the first place the reason you need the default. Therefore, default it before converting it to a number as follows:
moneyAmountRequired: (payload.root.MoneyAmountRequired default "0") as :number{format: "0"}

Hope this will answer your question about the default 0 not working.

A: Use this for
%dw 1.0
%output application/json
{
    value : moneyAmountRequired: floor payload.root.MoneyAmountRequired as :number  default 0
}


text:
Q: Why doesn't Java optimize String.split("regex") calls for String literals? In Java, String class has a method: public String[] split(String regex)
This method accepts a regular expression and splits the string it's called on by this regular expression, returning an array of Strings, the result of the split.
Basically, it has some optimizations for regexes with length of 1, and for the longer regular expressions, it calls just this code:
Pattern.compile(regex).split(this, 0)

So basically, it compiles the regular expression every time the split(String regex) method is called. But actually, pattern compilation is a relatively costly operation, but a pattern can be used to process (split in this case) multiple strings at different times (also it's immutable and therefore thread safe).
My question is: Why doesn't Java compiler or JVM optimize this somehow, either on compilation or runtime, by (maybe lazy) precompiling the regular expressions of split("regex") calls? I cannot think of a benefit of compiling a string literal to a pattern over and over. I'm thinking about something similar to String interning, or just keeping an array somewhere for precompiled Patterns?
I wrote the following code to observe the difference in performance (Regular Expression and String taken from this answer) (the sample string emails is the list of emails with SOMETHING between each of them):
public static final String REGEX = "(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\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?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)";

public static void main(String[] args) {
    String emails = "\"Fred Bloggs\"@example.comSOMETHINGuser@.invalid.comSOMETHINGChuck Norris <gmail@chucknorris.com>SOMETHINGwebmaster@müller.deSOMETHINGmatteo@78.47.122.114";

    long t1 = System.currentTimeMillis();
    test1(emails);
    System.out.println("Test 1 took " + (System.currentTimeMillis() - t1) + " milliseconds...");

    long t2 = System.currentTimeMillis();
    test2(emails);
    System.out.println("Test 2 took " + (System.currentTimeMillis() - t2) + " milliseconds...");
}

public static void test1(String input) {
    for (int i = 0; i < 100000; i++) {
        input.split(REGEX);
    }
}

public static void test2(String input) {
    Pattern pattern = Pattern.compile(REGEX);
    for (int i = 0; i < 100000; i++) {
        pattern.split(input);
    }
}

And the output is:

Test 1 took 34831 milliseconds...
  Test 2 took 11799 milliseconds...

After all, that's a pretty big difference, isn't it?

A: It is not the compiler's responsibility to improve your use of the API.
The compiler couples to a minimal subset of the huge number of standard Java classes. Some of these are listed in the Java Language Specification, section 1.4: Relationship to Predefined Classes and Interfaces:

As noted above, this specification often refers to classes of the Java SE platform API. In particular, some classes have a special relationship with the Java programming language. Examples include classes such as Object, Class, ClassLoader, String, Thread, and the classes and interfaces in package java.lang.reflect, among others. This specification constrains the behavior of such classes and interfaces, but does not provide a complete specification for them. The reader is referred to the Java SE platform API documentation.

Satisfying your request with a special case for String.split() would:

*

*Require coupling the compiler to the Pattern class.

*Require coupling the compiler to a particular implementation of String.split(), which might differ from the library used at run-time.

*Raise similar questions about potentially many other API methods.

Satisfying your request with a general approach would be more difficult. Java is not a functional language. Method calls are not necessarily referentially transparent -- multiple calls to the same method with the same arguments may return different results, and have side effects. In your case, Pattern.compile() returns different results on every call. Automatic memoization is easier in functional languages.
As you note, you have a way to use the API efficiently - compile once, split many, rather than using the convenience method String.split(). Increasing the complexity and coupling of the compiler for this special case (and others) carries a cost that outweighs the benefits.

A: The Java compiler just doesn't do optimisation. It does constant folding and it will delete branches that have conditions that reduce to false under constant folding, but it doesn't do anything more substantial. This is often surprising to people who've come from C/C++: Java is a language where source-level microoptimisations aren't always completely useless (though the JIT does make them usually so)
In some situations, it does comically terrible things. For instance, this code fragment:
Integer X = 3;
X++;

Ends up in bytecode as:
0: iconst_3            // Push 3
1: invokestatic #2     // Integer.valueOf(3)
4: astore_1            // Store the Integer in x.
5: aload_1             // Push x....
6: astore_2            // ... Store x in y.
7: aload_1             // Push x again...
8: invokevirtual #3    // x.intValue()
11: iconst_1           // Push 1
12: iadd               // x.intValue() + 1
13: invokestatic #2    // Integer . valueOf ( x . intValue () + 1)
16: dup                // Duplicate the new Integer .
17: astore_1           // Store it in x.
18: astore_3           // ... And also in z
19: aload_2            // Put y on the stack ...
20: pop                // .. discard it .

... Which is clearly ridiculous.
Similarly, each string append operation compiles down to a separate StringBuilder use.
The claim is that the Just-in-time compiler can do all the optimisation. That doesn't always work brilliantly: it's no use for binary size, some platforms have poor JIT, and the JIT can't optimise very aggressively anyway because it's got a very short amount of time to work with.
To make matters worse, excessive bytecode bloat can cause the JIT to be more reluctant to process your function, and harm the quality of the eventual output. Eeep.
There do exist optimisers for Java bytecode, such as Proguard, though I don't think any handles your specific case.
There is probably room for a useful source-level compile time optimiser for Java, but none currently exists. Well, unless you count the one I wrote at uni (it's on my GitHub if you're super keen. You can use it as a platform for implementing optimisations like the one you want. PRs welcome :P).
Essentially, if you want ahead-of-time optimisation, Java is not the language to use. In practice, on platforms where the JIT is good, things work out alright, though seemingly AoT optimisation could make them somewhat better. On platforms like old Android where JIT is suckful or nonexistent, this flaw in Java can be quite harmful (that's basically why Proguard exists)


text:
Q: Question about pinch singularities I am reading the book "Analytic S-matrix" by Eden,Landshoff, Olive and Polkinghorne.
In Sec.2, they discuss the different kinds of singularities of a function $f(z)$ defined as an integral of an analytic function $g(z,\omega)$ in the complex $\omega-$plane along some closed contour $\mathcal{C}$, i.e.
$$
f(z) = \int_\mathcal{C}\, d\omega\, g(z,\omega)\,.
$$
It is assumed that we know the singularities of $g(z,\omega)$. They discuss the case of pinch singularities, i.e. those singularities that approach the contour from the opposite sides and eventually coincide. As an example, they consider
$$
f(z) = \int_0^1 \frac{d\omega}{(\omega-z)(\omega-a)}
$$
where the contour is not really specified. This is already strange... shouldn't they specify the contour?
Their result is
$$
f(z) = \frac{1}{z-a}\log{\left[\frac{a(1-z)}{(1-a)z}\right]}\,,\qquad(a>1)
$$
To perform this integral, I was thinking to take the parameterization $\omega(t) = \sqrt{t} e^{i \arccos{\sqrt{t}}}$ where $t\in [0,1]$. This parameterization actually selects the path of a semi-cicle in the upper-half complex $\omega-$plane, running from $\omega=0$ to $\omega=1$. The integral then can be computed as
$$
f(z) = \int_0^1 dt \frac{d\omega(t)}{dt}\frac{1}{(\omega(t)-z)(\omega(t)-a)}
$$
If $z=a>1$ or $z=a<0$, the singularities of the integrand lie outside my integration path, and the integral is perfectly convergent.
Under Eq.(2.1.5) of their book, the authors write

the singularity at $z=a$ is only encountered on encircling one of the
logarithmic singularities, so that now $\log{1}$ is $\pm 2\pi i$ instead of zero and no longer cancels the pole.

Can anyone explain to me what they mean by the last sentence? It is not clear to me which kind of contour can give a singularity at $z=a$.


text:
Q: MongoDB connection via Django connector using X.509 certificate I have a Django API project for which I am using a MongoDB cloud database. The connection to the DB requires authentication via X.509 certificates.
How do I achieve this trusted connection using the Djongo connector?
Below is the Database connection configuration for my local setup. What needs to change for the CLoud connection with X.509?

Thank you for your time and valuable suggestions!!!


text:
Q: Angular Mat Select Trigger with FormControl Angular material select dropdown with mat select trigger.
Trying to create select dropdown like this :
https://stackblitz.com/angular/omvmgjjbnnq?file=app%2Fselect-custom-trigger-example.ts
My Code :
component.ts

export class SelectCustomTriggerExample implements OnInit {
  dispForm : FormGroup
  constructor(private fb : FormBuilder) {}
  ngOnInit() {
    this.dispForm = this.fb.group({
        toppings : ['']
     })
  }

  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}

component.html
<mat-form-field>
  <form [formGroup]="dispForm">
  <mat-select placeholder="Toppings" formControlName="toppings" multiple>
    <mat-select-trigger>
      {{toppings.value ? toppings.value[0] : ''}}
      <span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
        (+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
      </span>
    </mat-select-trigger>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
  </form>
</mat-form-field>

I have changed formControl to formControlName and code stopped working

A: Your code defines two form controls. When using [formControl], you're using only one of them: the one created using toppings = new FormControl();.
When using formControlName, you're using both: the one created using toppings : [''] is the one bound to your select, and the other one is the one used by your trigger.
There should be only one form control. And all the code should use that using form control.
Replace, in your component,
toppings = new FormControl();

by
get toppings(): FormControl {
  return this.dispForm.get('toppings') as FormControl;
}

Also, your form is named dispForm, not dispform. And it must be formControlName="toppings", not [formControlName]="toppings".
Demo


text:
Q: How to use Vert.x event loop to schedule RxJava execution Is it possible to use Vert.x event loop as scheduler for RxJava execution? Something like...
Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(new VertxScheduler()).
  subscribe(System.out::println);

...where VertxScheduler should be some kind of Vert.x event loop based scheduler.

A: As described in Vert.x RxJava documentation you can create Vert.x based scheduler using io.vertx.reactivex.RxHelper:
Vertx vertx = Vertx.vertx();
Scheduler scheduler = RxHelper.scheduler(vertx);

Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(scheduler).
  subscribe(System.out::println);

There is also RxHelper.blockingScheduler(Vertx) method creating scheduler from Vert.x worker threads pool.


text:
Q: Server Side Rendering with React Router Dom getting error: Warning: React.createElement: type is invalid -- expected a string Exact Error:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for co
mposite components) but got: object.
    in Posts
    in Connect(Posts)
    in Route
    in Switch
    in div
    in App
    in Route
    in Switch
    in div
    in Router
    in StaticRouter
    in Provider

I am getting error with doing server side rendering with react router 4. The error doesn't really point to anything in particular, but I think this comes from how I use the routes and exporting the components. I will post relevant code to this problem.
For client code I will post one component container since I export all of them in the same way. I just want you to get a since on how this is done. The component itself works just fine so I will be posting the export code at the bottom.
Note: this is a full working demo project (https://github.com/tbaustin/demo-SSR-RR4) and I use this same technique. I am also using turbo which is a scaffold type of system for react/redux. You will see that the app.js looks a little different than a normal express application, but I ensure you it works the same.
SERVER:
app.js:
require('babel-core/register')({
  presets: ['env', 'react', 'stage-0', 'stage-1']
});

const pkg_json = require('./package.json');
const vertex = require('vertex360')({ site_id: pkg_json.app });
var renderer = require('./renderer.js');

// initialize app
const app = vertex.app();

// import routes
const index = require('./routes/index');
const api = require('./routes/api');

// hopefully will be used on every Route, this should handle SSR RR4
app.use(renderer);

// set routes
app.use('/', index);
app.use('/api', api); // sample API Routes

module.exports = app;

renderer.js:
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(res, req) {
  const store = createStore.configure(null); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }

    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>

{renderRoutes(routes)}

        </StaticRouter>
      </Provider>
    );

    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;

index.mustache:
<!DOCTYPE html>

    {{{ helmet.title }}}
    {{{ helmet.meta }}}
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <link href="https://fonts.googleapis.com/css?family=Pathway+Gothic+One:300,400,500,600,700|Lato:300,400,400italic,600,700|Raleway:300,400,500,600,700|Crete+Round:400italic" rel="stylesheet" type="text/css" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link rel="stylesheet" href="/dist/css/style.min.css" type="text/css" />

{{{ content }}}

CLIENT:
index.js:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';

import store from './stores';
import routes from './routes';

const initialState = window.INITIAL_STATE;

ReactDOM.hydrate(
  <Provider store={store.configure(initialState)}>
    <BrowserRouter>

{renderRoutes(routes)}

    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

Root App component:
import React from 'react';
import { renderRoutes } from 'react-router-config';

import Header from './partials/Header';
import actions from '../actions';

const App = ({ route }) => {
  return (

      {renderRoutes(route.routes)}

  );
};

export default {
  component: App,
  loadData: ({ dispatch }) => dispatch(actions.currentUser())
};

Posts.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import swal from 'sweetalert';
import { Link } from 'react-router-dom';

import { CreatePost } from '../view';
import { Account } from '../containers';
import actions from '../../actions';
import { DateUtils } from '../../utils';

class Posts extends Component {
  componentDidMount() {
    if (this.props.post.all == null) {
      this.props
        .fetchPosts({})
        .then(response => {
          return null;
        })
        .catch(err => {
          console.log(err);
        });
    }
    if (this.props.reply.all == null) {
      this.props
        .getReplies({})
        .then(() => {
          return null;
        })
        .catch(err => {
          console.log(err);
        });
    }
  }

  createPost(params) {
    const { currentUser } = this.props.user;
    if (currentUser == null) {
      swal({
        title: 'Oops...',
        text: 'Please Login or Register before posting',
        type: 'error'
      });
      return;
    }

    const updated = Object.assign({}, params, { profile: currentUser });

    this.props
      .createPost(updated)
      .then(data => {
        swal({
          title: 'Post Created',
          text: `Title: ${data.title}`,
          type: 'success'
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    const posts = this.props.post.all;
    const { currentUser } = this.props.user;
    return (

              {posts == null
                ? null
                : posts.map(post => {
                    return (

                          <Link to={`/post/${post.id}`}>

                          </Link>

                            {post.title.length > 17 ? post.title.substr(0, 17) + '...' : post.title}

                            {post.text.length > 30 ? post.text.substr(0, 30) + '...' : post.text}

                            ~{' '}
                            <Link to={`/profile/${post.profile.id}`} style={{ color: 'white' }}>
                              {post.profile.username || 'Anonymous'}
                            </Link>

                            {DateUtils.relativeTime(post.timestamp)}

                    );
                  })}

                <Account />

            {currentUser == null ? null : (

Create a Post

                    <CreatePost onCreate={this.createPost.bind(this)} />

            )}

    );
  }
}

const stateToProps = state => {
  return {
    post: state.post,
    user: state.user,
    reply: state.reply
  };
};

const dispatchToProps = dispatch => {
  return {
    createPost: params => dispatch(actions.createPost(params)),
    fetchPosts: params => dispatch(actions.fetchPosts(params)),
    getReplies: params => dispatch(actions.getReplies(params))
  };
};

const loadData = store => {
  return store.dispatch(actions.fetchPosts());
};

export default {
  loadData: loadData,
  component: connect(stateToProps, dispatchToProps)(Posts)
};

CLIENT/SERVER ROUTES:
import React from 'react';

import { Post, Posts, Profile, NotFound } from './components/containers';
import App from './components/App';

export default [
  {
    ...App,
    routes: [
      {
        ...Posts,
        path: '/',
        exact: true
      },
      {
        ...Post,
        path: '/post/:id'
      },
      {
        ...Profile,
        path: '/profile/:id'
      },
      {
        ...NotFound
      }
    ]
  }
];

A: My best guess would be that, within Posts.js, this code:

  <Account />

should be:

  <Account.component />

Or you could extract the component part at a higher level somewhere.
I'm basing this from the fact that Account is imported from containers, and other parts of your code expect exported containers to be of the form { component, loadData }.
If not, the other culprit could be CreatePost.


text:
Q: mysqldump is not working in cron First, I created .my.cnf in /home/username/ with the following text:
[client]
user = sample_user
password = sample_password
host = localhost
Then, I executed the command below and it went successfully:
/usr/bin/mysqldump sample_table > home/username/backup_db/$(date +%F)_full.sql
But, when I entered it in crontabs, it didn't worked:
0 0 * * * /usr/bin/mysqldump sample_table > /home/username/backup_db/$(date +%F)_full.sql
I even tried changing the minutes and hour portion but still, it won't work.

A: You need to escape the percent sign (%), as it has a special meaning in crontab entries, use \% instead.


text:
Q: HTTP Error 500.30 - ANCM In-Process Start Failure - 'Microsoft.Data.SqlClient.TdsParser' threw an exception After upgrading to .net core 3.1(3.1.12 sdk) everything works fine on localhost(hosting model outofprocess and inprocess) but when publishing to azure i have issues with the inprocess hosting model, it does not run at all and i get the error below.
After some further investigation and updating every package(including entity framework) to 3.1.12 compatibility, switching every project from Any CPU to x64, solving any compatibility issues with all packages, the code still breaks, but i found out where, and i still can't determine why this happens.

Also the error comes from this part of code(ADDED TRY CATCH TO SEE IF THE APP WORKS WITHOUT IT, AND IT DOES BUT WE NEED THIS PART, AND I'M PRETTY SURE OTHER STUFF WILL BREAK FURTHERMORE):


text:
Q: JAXB - IllegalAnnotationExceptions I have an XSD like this:
<xs:element name="Measure">
 <xs:complexType>
  <xs:sequence>
    <xs:element minOccurs="1" ref="Measure_Id"/>
    <xs:choice minOccurs="1" maxOccurs ="4">
        <xs:element ref="Measure_Value"/>
        <xs:element ref="Measure_Value_Max"/>
        <xs:element ref="Measure_Value_Min"/>
        <xs:element ref="Measure_Value_Average"/>
    </xs:choice>
    <xs:element minOccurs="0" ref="Files"/>
  </xs:sequence>
 </xs:complexType>
</xs:element>

In particular, with <xs:choice> i'd like to specify that element Measure must have at least one type of Measure_Value.
Unfortunately this kind of code generate an exception:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
  There's no ObjectFactory with an @XmlElementDecl for the element {}Measure_Value_Max.

What i have to do to fix this problem?
I use Netbeans 7.4 and jdk1.7.
In addition, in another part of my schema, this type of restriction works correctly! Why?
<xs:element name="UD_Info">
 <xs:complexType>
  <xs:sequence>
    <xs:element minOccurs="1" ref="UD_Identificator"/>
    <xs:choice minOccurs="1" maxOccurs ="3">
        <xs:element ref="UD_Measures"/>
        <xs:element ref="UD_Alarms"/>
        <xs:element ref="UD_Diagnostics"/>
    </xs:choice>
  </xs:sequence>
 </xs:complexType>
</xs:element>

Stack trace:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/francesco/.m2/repository/org/slf4j/slf4j-log4j12/1.7.6/slf4j-log4j12-1.7.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: Found binding in [jar:file:/home/francesco/.m2/repository/ch/qos/logback/logback-classic/1.0.6/logback-classic-1.0.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions

There's no ObjectFactory with an @XmlElementDecl for the element {}Measure_Value_Max.
this problem is related to the following location:
    at protected java.util.List com.fra.jaxb.Measure.measureValueOrMeasureValueMaxOrMeasureValueMin
    at com.fra.jaxb.Measure
    at protected java.util.List com.fra.jaxb.UDMeasures.measure
    at com.fra.jaxb.UDMeasures
    at protected java.util.List com.fra.jaxb.UDInfo.udMeasuresOrUDAlarmsOrUDDiagnostics
    at com.fra.jaxb.UDInfo

at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:405)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:253)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:84)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:248)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:235)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:432)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:637)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at com.fra.mavenparser.unMarsh.doInfr(unMarsh.java:56)
at com.fra.mavenparser.Parser.main(Parser.java:26)

A: To get the ObjectFactory processes you need to either pass it in as one of the classes used to bootstrap the JAXBContext, or create the JAXBContext on the package name of the generated model.


text:
Q: Icons should stay at the top of the column I have a basic table js fiddle, the icons are obvi font awesome, you can see here that as the right hand side grows with text the icons always stay in the enter, well I want them to stick to the top with a padding of 10 px's.
I am, although not here, using bootstrap. So is there a class to do this? .table in bootstrap will pull the icons to the top - but it also adds a top border which I don't want, I could go in and remove that, but I would rather not.
So is there a bootstrap class that will cause all icons to jump to the top of the tr element they are in? - or better yet, is there some simple css I could do to make the icon "stick" to the top of the containing tr element they are in?

A: Add this css-property to the TD of the icon:
vertical-align:top;

This makes sure the icon stays at the top. You could change the position with padding ;)


text:
Q: Melt/Stack/Reshape multi header dataframe I've scraped from data from excel that has more than one header row of data, with some nans in one row:
df = pd.read_excel(file, header=None)
0  nan  nan   jan20  jan20  feb20  feb20
1  ID   Name   GrpA   GrpB   GrpA   GrpB
2  1    One     1       2      3     4
3  2    Two     5       6      7     8

Each ID/Name pair has 4 pieces of data it needs to be associated with.  The goal for the data is to look like:
ID Name
1   One jan20 grpA 1
1   One jan20 grpB 2
1   One feb20 grpA 3
1   One feb20 grpB 4
2   Two jan20 grpA 5
2   Two jan20 grpB 6
2   Two feb20 grpA 7
2   Two feb20 grpB 8

Note when this is scraped, I don't indicate the header rows upon import, as there is some cleaning of the data to do.  I've tried lots of various combinations of pd.melt, pd.stack, pd.unstack, but not getting there.  I've tried making the first two rows both header rows, but then I have problems with the keys.
It seems like .melt might be the right answer because you can choose a col_level and could name the resulting columns, but when I try that route I can't access the dates (first row) it seems
df.melt(col_level=1, id_vars=['ID'])
Any ideas on this one?

A: Assuming the lines of your sample are all rows of the dataframe (not spreadsheet), this should work. Here I'm creating a 2-level MultiIndex containing the 2 first rows, then dropping those rows, and doing 2 melts.
df.columns = pd.MultiIndex.from_arrays([df.iloc[0], df.iloc[1]])
df = df.iloc[2:] # trim off the first 2 rows after we put them in the MultiIndex

tmp = df.melt(id_vars=['ID', 'Name'], col_level=1)
tmp['x'] = df.melt(col_level=0).dropna()[0].to_numpy()
tmp = tmp.rename({1: 'y', 'value': 'z'}, axis=1).set_index(['ID', 'Name'])[['x', 'y', 'z']].sort_index()

Output:
>>> tmp
             x     y  z
ID Name
1  One   jan20  GrpA  1
   One   jan20  GrpB  2
   One   feb20  GrpA  3
   One   feb20  GrpB  4
2  Two   jan20  GrpA  5
   Two   jan20  GrpB  6
   Two   feb20  GrpA  7
   Two   feb20  GrpB  8

A: Let us load the file correctly
df = pd.read_excel('yourfile.xlsx',
                   header=[0,1],
                   index_col=[0,1])

Then you can just do stack twice
out = df.stack().stack()

A: A crude way can be to manually reshape:
(df
 .set_index([0,1]).T
 .set_index([(float('nan'), float('nan')), ('ID', 'Name')])
 .rename_axis(index=[None,None], columns=[None,None])
 .stack()
 .stack()
)

Output:
jan20  GrpA  One  1    1
             Two  2    5
       GrpB  One  1    2
             Two  2    6
feb20  GrpA  One  1    3
             Two  2    7
       GrpB  One  1    4
             Two  2    8
dtype: object


text:
Q: Python FPDF can't find the font pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)

Works only in PyCharm console, if run from the command line i get an error

File "C:\\Program Files\\Python310\\lib\\site-packages\\fpdf\\fpdf.py", line 469, in add_font
raise RuntimeError("TTF Font file not found: %s" % fname)
RuntimeError: TTF Font file not found: DejaVuSansCondensed.ttf
←\[?25h

the font is at the root
when using pycharm, an additional file is automatically created DejaVuSansCondensed.pkl
and everything works fine, but when using the command line, the file is not created and I get an error. Please help me with the solution.

A: FPDF only works with absolute path, works in this form:
path = os.path.abspath('DejaVuSansCondensed.ttf')
pdf.add_font('DejaVu', '', path, uni=True)


text:
Q: Redirect to https using ngrok Hi i am using ngrok to serve my web application hosted in Apache tomcat running on my machine. I am following commamd to run ngrok
ngrok tls -region=us -hostname secure.example.com -key mydoamin.key -crt mydoamin.crt 80

Its works fine in HTTPS but when i access my domain using http it says Tunnel secure.example.com  not found. I think by using tls it is only exposing https what i want is to redirect user from HTTP to HTTPS. Can i achieve this using ngrok?

A: I hope that you have found a solution to your problem.
Here my solution.
To use it, you must have your certs.
ngrok.yml
authtoken: <your token>
region: <your region>
tunnels:
   <name-https>:
   addr: 8443
   crt: path/to/cert/cert.pem
   key: path/to/key/key.pem
   host_header: "rewrite"
   proto: tls
   hostname: www.myexample.test
<name-https>:
   addr: 80
   proto: http
   bind-tls: false
   hostname: www.myexample.test

Navigate to the directory /etc/apache2/sites-available and create a new file nano example.conf
<VirtualHost *:80>
    ServerName myexemple
    Redirect permanent / https://www.myexample.test
</VirtualHost>
<VirtualHost *:8443>
     ServerName <servername>
     DocumentRoot /var/www/html/<your-project>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save all and start the commands:
a2ensite example.conf
systemctl reload apache2

Reach the location of your ngrok.yml file and start it with the command:
ngrok start --all

Try it and have fun :)


text:
Q: How to save object state/selection? I have 2 forms. One is a main form(form1), and other one(form2) is called when I press a button.
When I press a button, form2 shows and it contains several checkboxes and comboboxes.
My question is, how can I store or save the checkbox state and combobox selection so that I can use them (check their state/selection) in my form1 after I close form2?
Here's a basic example:
Form2:

--I click on checkbox and the state changes:

checkbox1.Checked = true;

Form1:

private void button1_Click(object sender, EventArgs e)
{
if (checkbox1.Checked == true)
{
MessageBox.Show("Checkbox on form2 is checked")
}
}

Thanks in advance!

A: Use Databinding and an object to pass around. The following example demonstrates how to achieve this without having to make anything static. Because the values become bound together if you do: state.IsChecked = false; that would also uncheck the checkbox on Form2.
Don't just add global variables, that's a large pain waiting to happen.
class Form1: Form
{
    private State state = new State();

    public Form1()
    {
        Load += HandleLoad;
    }

    public HandleLoad(object sender, EventArgs e)
    {
        label1.DataBindings.Add("Text", state, "IsChecked"); // or just query state.IsChecked
    }
    public void someEvent_Handler()
    {
        Form2 form2 = new Form2();
        form2.Bind(state);
        form2.Show();
    }
}

class Form2: Form
{
    public void Bind(State state)
    {
        checkBox1.DataBindings.Add("Checked", state, "IsChecked");
    }
}

class State
{
    public bool IsChecked {get;set;}
}

A: In your current code, you are creating new form instance every time, something like:
private void OpenForm2
{
    //open form2:
    Form2 form2 = new Form2();
    form2.ShowDialog(this);

    //read form2 values:
    if (form2.Checkbox1.Checked)
    {
        MessageBox.Show("Checkbox on form2 is checked")
    }
}

Instead, use one global instance and just show it every time, this way preserving its state:
Form2 form2 = new Form2();
private void OpenForm2
{
    //open form2:
    form2.ShowDialog(this);

    //read form2 values:
    if (form2.Checkbox1.Checked)
    {
        MessageBox.Show("Checkbox on form2 is checked")
    }
}


text:
Q: Type Mismatch: Signed to Unsigned I have the following line of code,
const CHAR* GetText() { return Text; } // Text is char[16]"Character Array"

The Fortify security tool is complaining about the above line as follows:
Type Mismatch: Signed to Unsigned GetText()is declared to return an unsigned value, but on line xxx it returns a signed value.
I did not understand where i am converting it from signed to unsigned. I do understand the signed to unsigned conversion stuff if it is related to integers.
If i inferred correctly from the line of code,
Is char which being returned a signed char?
Is LPCSTR(const char*)the return type is unsigned char?
How do we assume (Text-which is a string) is signed and unsigned?
Any help would be appreciated.


text:
Q: MySQL syntax error near Other people i'v googled with this MySQL error have had restricted words, but I cant see any in mine.
I'm having trouble storing an css div in a variable and inserting it into a table as a field.
I'm very confused because the 2
's work perfect, but then it breaks when I try a div.
userrepost.php
    /* Connect and Query database "accounts", then close connection */
    $connection=mysql_connect("localhost","root","");
    if (!$connection)
    {
        die('Cannot connect to MySQL. Error: ' . mysql_error());
    }

    $check_database = mysql_select_db("accounts", $connection);
    if (!$check_database)
    {
        die('Cannot connect to database. Error: ' . mysql_error());
    }

    /* Escape all POST variables */
    $query=mysql_query("SELECT * FROM posts WHERE id='$_GET[postid]'");
    $result = mysql_fetch_row($query);
    $escaped_repostinfo=$_POST['repostinfo'];
    $final_repostinfo=$escaped_repostinfo."

".$result[0]." ".$result[1]."
";
    echo $final_repostinfo;
    $date = new DateTime('Canada/Saskatchewan');
    $date->setTimezone(new DateTimeZone('Canada/Saskatchewan'));
    $date_string=$date->format('d/m/Y H:i:s');

    /* Query database to save user's post */
    /* If field "repostid==0", then the post is not a repost; if the field "repostid>0", then the post is a repost with the field "repostid" linking to the id of the post to be reposted */
    $result = mysql_query("INSERT INTO posts (user, content, repostid, date) VALUES ('$_SESSION[username]', '$final_repostinfo', '$_GET[postid]', '$date_string')");
    if (!$result)
    {
        die('Cannot query. Error: ' . mysql_error());
    }

    /* Close Connection */
    mysql_close($connection);

'rptext' is a css div( #rptext{stuff;} )
This is the error:
Cannot query. Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'rptext'>shawn619 dfsd', '51', '09/11/2013 15:27:11')' at line 1

A: You are inserting an unescaped string which contains single quotes:
'rptext'

This needs to be properly escaped to work.

A: Escape all the variables you put into a query using mysql_real_escape_string. EVERY variable. I am 99% certain it's what causing your errors, and also: passing $_GET variables directly into an SQL query is very dangerous. With every variable you forget, you leave a hole for these kinds of errors and SQL Injection attacks.
It's as easy as this:
$var = $_GET['some-parameter'];
$var = mysql_real_escape_string($var); // now you may use it in a query

Edit: just to clarify, you don't just need to escape $_GET variables, but all of them! Don't forget $final_repostinfo and $date_string.

A: $query=mysql_query("SELECT * FROM posts WHERE id='$_GET[postid]'");

$_GET[postid] is not like $_GET['postid'], big difference
please use this way:
$query=mysql_query("SELECT * FROM posts WHERE id=`".$_GET[postid]."`");

and $_GET['postid'] is it numeric or string? If numeric you don't need to use apostrophe.
same problem here:
$result = mysql_query("INSERT INTO posts (user, content, repostid, date) VALUES ('$_SESSION[username]', '$final_repostinfo', '$_GET[postid]', '$date_string')");

$_SESSION and $_GET...


text:
Q: Socket#getOutputStream#write freezes current thread I believe that I'm making some really simple mistake, but I can't seem to work it out.
The client connects to the server without a problem. But when I try to send client a message through socket.getOutputStream().write('☺'); It freezes current thread. And the only way to unfreeze is to exit the client.

A: The problem was, that I was creating ServerSocket through SSLSocketFactory.


text:
Q: Dropdown sets as System.Data.DataRow, What is wrong with my code?     System.Data.DataTable dt = new System.Data.DataTable();
    CDbAccess db = new CDbAccess();
    IDbConnection conn = db.GetConnectionInterface();
    conn.Open();
    string str = "select eName from bt_modules";
    IDbCommand cmd = db.GetCommandInterface(str);
    IDbDataAdapter da = db.GetDataAdapterInterface(cmd);
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    dt = ds.Tables[0];
    DropDownList2.DataSource = dt;
    DropDownList2.DataBind();
    conn.Close();

The above code set Dropdown items as System.Data.DataRow
How to get the actual values?

A: DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "eName";
DropDownList2.DataBind();
conn.close();
You can refer this code also http://www.aspdotnet-suresh.com/2012/10/showbind-data-to-aspnet-dropdownlist.html

A: try like this :
 DropDownList2.DataSource = dt;
 DropDownList1.DataTextField = "eName " '// Column Name
 DropDownList2.DataBind();

If you want to use value field also using like this
 DropDownList2.DataSource = dt;
 DropDownList1.DataTextField = "eName " '// Column Name
 DropDownList1.DataValueField = "eid" '// Column Name
 DropDownList2.DataBind();


text:
Q: HTML Note Textbox I'm brand new to HTML and am having difficulties.
I have implemented a note page.
Where the user can type in a note and press submit.
When they press submit, I want the note that they typed in to display in a text box below, however Im struggling to implement that.
<form class="form-horizontal">
<fieldset>

<legend>Form Name</legend>

  Note:

  <input id="Type Note" name="Type Note" type="text" placeholder="" class="form-control input-md">

    <button id="" name="" class="btn btn-primary">Submit</button>

</fieldset>
</form>

The output looks like...
Note:[==insertnotehere==]

Submit[button]

[Want my notes to display below in a text box]

If anyone has insight that would be awesome! Thank you!

A: HTML is a declarative markup language so it can't do that level of interactivity on its own. Instead, you will need to write some javascript to make this work.
You'll need to write some javascript that does the following:

*

*Find the form element

*Listen for the submit event on said element

*Inside the event handler:

*

*Cancel the default form submit, otherwise it will refresh the page

*Create the HTML elements necessary to display the note

*Populate the HTML with the value of the textbox

*Add the elements into the DOM

*Clear the value of the textbox

A:

$(function () {
  $(".form-horizontal").submit(function (e) {
    e.preventDefault();
    alert($("#Type Note").val());
  });
});

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

      <form class="form-horizontal">
        <fieldset>

          <legend>Form Name</legend>

            Note:

              <input id="Type Note" name="Type Note" type="text" placeholder="" class="form-control input-md">

              <button class="btn btn-primary">Submit</button>

        </fieldset>
      </form>


text:
Q: Calling decorated function internally in concrete implementation of abstract class I have one more question about decoration of c++ classes. With decorators I change virtual int get() function. But in NPC class I also call the get() function to get some values for calculation. Is there a way to call Elite::get() inside NPC. I want to get 100 and not 10. Thank you.
class AbstractNPC {
public:
    virtual int get() = 0;
};

class NPC: public AbstractNPC {
public:
    NPC() { }
    int get(){ return 10; }
    calc(){ int i = get(); }
};

class NPCDecorator: public AbstractNPC {
private:
    AbstractNPC * npc;
public:
    NPCDecorator(AbstractNPC *n) { npc = n; }
    int get() { npc->get(); }
};

class Elite: public NPCDecorator {
public:
    Elite(AbstractNPC *n): NPCDecorator(n) { }
    int get() { return 100; }
};

Or is there a better way? Maybe the use of function pointers?

A: You can just use inheritance:
class Elite: public NPC {
public:
    int get() { return 100; }
};

See it online!

get() method is polymorphic. This means compiler will know whether it should call Elite::get or NPC::get, no matter where you call it. You have to be careful about using virtual methods in constructors or destructors, but otherwise it should work just right.


text:
Q: Syntax error on creating and extracting name variable using MsgBox I am trying to execute a macro to create and extract name variable using MsgBox. I have tried to run it without '_' in the MsgBox code, it didn't work. It shows a message that there is a syntax error in the code defining name equal to Steve Jobs.
Sub test1()
Dim name as string, lname as string, fname as string
name = "Steve Jobs"
lname = right(name, 4)
fname = left(name,5)
Msgbox "First name is" & fname & "" & " the number of characters are" & len(fname)
Msgbox "Surname is" & fname & "" & " the number of characters are" _ & len(fname)
End Sub

A: Sub test1()
Dim name As String, lname As String, fname As String
name = "Steve Jobs"
lname = Right(name, 4)
fname = Left(name, 5)
MsgBox "First name is " & fname & "" & " the number of characters is " & _
Len(fname)
MsgBox "Surname is " & lname & "" & " the number of characters is " & _
Len(lname)
End Sub

The quote mark you use looks weird, this way it should be fine

A: The _ you're referring to is a line continuation character.
Also, the quotation marks in your post are incorrect - although it may be a result of how you copied the text to this site (perhaps you had to "email it to yourself" in the process). Once the quotation marks are changed from " and " to ". then either of these will run fine:
with line continuation:
Msgbox "Surname is" & fname & "" & " the number of characters are" & _
    len(fname)

without line continuation:
Msgbox "Surname is" & fname & "" & " the number of characters are" & len(fname)

I think this is what you're trying to do:
Debug.Print "Surname is """ & lName & """ and the number of characters is " & Len(lName)

In your example, you're using fName for both first name & last name. Also, this is how we can put quotes around a variable.


text:
Q: The approximate uncertainty in $r$ The volume of a cylinder is given by the expression
$V=\pi r^2 h$
The uncertainties for $V$ and $h$ are as shown below
$\begin{align}
V&\pm 7\%\\
h&\pm 3\%
\end{align}$

What is the uncertainty in $r$?

Now, the obvious answer would be $2\%$, from
$$\frac{dV}{V}=\frac{dh}{h}+2\frac{dr}{r}$$
However, rearranging to $r^2=\frac{V}{\pi h}$ gives
$$2\frac{dr}{r}=\frac{dV}{V}+\frac{dh}{h}$$
which gives a different answer of $5\%$. Thus, by simply rearranging the formula, we get different values for uncertainty in $r$.

How do you explain this?
(The mark scheme lists $5\%$ as the correct answer)

A: You're confusing independent and dependent variables.  When you propogate from uncertainties in the $x_{i}$ to some $f(x_{1},x_{2}...)$, the formula $\delta f(x_{1}...)=\sum \left|\frac{\partial f}{\partial x_{i}}\right|\delta x_{i}$ assumes that each of the $x_{i}$ is an independently measured variable and that $f$ is a dependent variable to be calculated from the $x_{i}$.
In the example you give, you have two independent measurements of $V$ and $h$ and are expected to calculate the uncertainty in $r$.  Well, to use the above formula, you need to write $r$ as a dependent variable of $V$ and $h$.  Therefore, it's only correct to solve for $r$ first, and then calculate the uncertainty.

A: Jerry Schirmer's right about why solving for $r$ first is the right procedure. One way to illustrate this is to notice that with the other procedure the uncertainty could go negative, which can't be right.
But the main thing I wanted to point out is that, if the measurements of $V$ and $h$ are independent, and if the "errors" mean standard deviations as usual, then the correct procedure is to add the errors in quadrature (i.e., to add the squares and take the square root):
$$
{\delta r\over r}={1\over 2}\sqrt{\left(\delta V\over V\right)^2+\left(\delta h\over h\right)^2}.
$$
See, e.g., any of the first few Google hits for "propagation of errors."

A: This should be a comment to Jerry Schirmer's right answer.
The solutions you give solve different problems.
In the first calculation you measure V with its uncertainty $\Delta V$, you know it depends with r and h, you know the uncertainty you have in the measurement of h, $\Delta h$ and thus you infer the uncertainty you had associated with measuring r, $\Delta r$.
In the second calculation you want to measure r from V and h. Knowing the uncertainties in V and h you predict the uncertainty that you will have in r.

A: Your first formula is correct, but it looks like you substituted in the incorrectly signed value for (dh/h).  Your second formula is missing a sign change for the (dh/h) term.
In the first equation, substituting, to get the MAXIMUM (dr/r) --->
+7% = (-3%) + (2 x (+5%))
 -OR-
-7% = (+3%) + (2 x (-5%))
So, your text is correct: +/-5% is the (approximate) uncertainty for r.
If you solve this problem algebraically, you will find that the (corrected) differential equations you constructed gives a very close but not exact answer.  The correct uncertainty for r is something like + SQRT(1.07/0.97) and - SQRT(0.93/1.03) = +5.0282% / -4.9783%.  This is because the differential eqns are valid only for infinitesimal deltas; but we are using deltas on the order of +/-5% (hardly infinitesimal).

A: I will use two ways to derive the uncertainity on r
1 - very simple method: the 'interval arithmetic' present in the Euler math package (free)
2 - derive the formula of dr(V,h, dV,dh)
Both answers : 5%  (for any value V or h that I choose for V and h)
// 'using interval arithmetic'
>dV=0.07 dh=0.03         // deltas
>V=1000 h=40             //arbitrary choosen values
>r0=sqrt(1/pi*V/h)       //central value for r
 2.82094791774
>r=sqrt(1/pi*((V±V*dV)/(h±h*dh))) //interval values for r
 ~2.6,3~                          //    from 2.6 to 3
>(r-r0)
 ~-0.14,0.14~
>(r-r0)/r0
 **~-0.05,0.05~                     // 5% for dr/r0 for any V, h**

//calc dr(V,h, dV,dh) (seeResistance_measurement Example and adapting the derivatives)

dr=1/2/sqrt(pi)*sqrt(dV^2/V/h+dh^2*V/h^3)
   0.00106245302667
  1-(r-dr)/r0
~-0.05,0.05~                     // the result is again 5%


text:
Q: routing requests with htaccess and codeigniter I have a codeigniter app with one controller (main.php)
Currently, I have the htaccess file set to remove the index.php and the main.php
So instead of www.domain.com/index.php/main/function_name, it's just www.domain.com/function_name
My htaccess files looks like this:
 <IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/main/$1 [L]

ErrorDocument 404 /index.php

I now need to add a large piece to the site. It's currently built in a seperate codeigniter app, and I need to move it over. The new part of the site is in controllers/manage_emails/contacts.php...
My question is, how do I change the htaccess file to remove the main.php from the URL for most of the time, but then if you put in www.domain.com/manage_emails/contollername it would go to the proper controller.
Thanks!

A: From what I understand there are 2 separate problems you have:
1.remove the index.php file from Codeigniter's default
2.redirect any call from 'www.domain.com/main/method' to 'www.domain.com/method'
For the first problem, I always use Elliot Haughin's htaccess file for CI: CodeIgniter and mod_rewrite with multiple applications
For your second problem, you need to change config/routes.php in CI, and add this line:
$route['(:any)'] = "main/$1";

..and you can also check this post:Codeigniter, bypassing the main or default controller
Try to separate these 2 problems, and like it has been said, stick with CI for routing and just use htaccess for removing index.php from URL.

A: Your application would be a lot easier to manage if you remove any URI routing from the .htaccess file, and let your CodeIgniter's routes do that for you.
Your .htaccess should have just the standard "get rid of index.php" code (the last part, without the /main in it). Then your application's routes can define when/where the rest of the URLs will go.
Slightly unrelated FYI, if you are using a more recent version of CI such as 2.1.x, you don't need the system and application folder-specific rules in your .htaccess.

A: In addtion to @despina answer i want to add something:
You have to set $route['(:any)'] = "main/$1"; at the last route because CI  handle the routes in the order in which they appear on your routes.php file, so if you put $route['(:any)'] at the top, it will handle anything.
so your route.php file will be something like that:
$route['controllers/manage_emails/something.php'] = 'controllers/manage_emails/something.php'
$route['(:any)'] = "main/$1";

A: First of all your 2 rules are not correct and most likely not working. Here is the fixed version of your .htaccess with addition of one new rule that have asked for:
RewriteEngine On
RewriteBase /

RewriteRule ^(?:application|system)(/.*|)$ /index.php?/$1 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/manage_emails/contollername [NC]
RewriteRule ^(.*)$ index.php?/main/$1 [L]

ErrorDocument 404 /index.php

A: //config/routes.php
    $route['404_override'] = 'main/route';
//controllers/main.php
class Main {
...........
   function route() {
      $methodName = $this->uri->segment(1);
      if(method_exists($methodName, $this)) {
       $this->{$methodName}();
      } else {
        show_404();
      }
   }
}


text:
Q: How to enter with landscape mode with a UITabBarController App? I have a UITabBarController, and each tab handles a different UIViewController that pushes on the stack new controllers as needed. and every UIViewController be created with NIB and included method:
-(BOOL)shouldAutorotateToInterfaceOrientation:UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

but I found that when I enter the app with Landscape mode, it not work, still with a portrait mode, why?
and for my ipad app, it can work, and in plist have setted "Supported interface orientations (iPad)" and "Supported interface orientations (iPhone)" for all device orientations. and target of xcode enabled "Supported Interface Orientations " button for gray, but still not work for iphone, and ipad will fine, Why? Thank you very much!!!

A: Which iOS are you testing against?
-(BOOL)shouldAutorotateToInterfaceOrientation:UIInterfaceOrientation)interfaceOrientation;
Is for iOS5
If you are on iOS6 make sure these are clicked in the application settings.