Programs & Examples On #Serializearray

how to change text box value with jQuery?

You may try following this:

You forgot to add quote : $(#ch1).val("adfsadf") ;

This supposed to be : $('#ch1').val("adfsadf") ;

Capturing a form submit with jquery and .submit

try this:

Use ´return false´ for to cut the flow of the event:

$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

Edit

corroborate if the form element with the 'length' of jQuery:

alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

OR:

it waits for the DOM is ready:

jQuery(function() {

    alert($('#login_form').length) // if is == 0, not found form
    $('#login_form').submit(function() {
        var data = $("#login_form :input").serializeArray();
        alert('Handler for .submit() called.');
        return false;  // <- cancel event
    });

});

Do you put your code inside the event "ready" the document or after the DOM is ready?

Serialize form data to JSON

Well, here's a handy plugin for it: https://github.com/macek/jquery-serialize-object

The issue for it is:

Moving ahead, on top of core serialization, .serializeObject will support correct serializaton for boolean and number values, resulting valid types for both cases.

Look forward to these in >= 2.1.0

jQuery: Clearing Form Inputs

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Original Answer: Resetting a multi-stage form with jQuery


Mike's suggestion (from the comments) to keep checkbox and selects intact!

Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

jquery get all input from specific form

_x000D_
_x000D_
$(document).on("submit","form",function(e){
        //e.preventDefault();
        $form = $(this);
        $i = 0;
        $("form input[required],form select[required]").each(function(){
            if ($(this).val().trim() == ''){
                $(this).css('border-color', 'red');
                $i++;
            }else{
                $(this).css('border-color', '');    
            }               
        })
        if($i != 0) e.preventDefault();
    });
    $(document).on("change","input[required]",function(e){
        if ($(this).val().trim() == '')
            $(this).css('border-color', 'red');
        else
            $(this).css('border-color', '');    
    });
    $(document).on("change","select[required]",function(e){
        if ($(this).val().trim() == '')
            $(this).css('border-color', 'red');
        else
            $(this).css('border-color', '');
    });
_x000D_
_x000D_
_x000D_

Convert form data to JavaScript object with jQuery

Turn anything into an object (not unit tested)

<script type="text/javascript">
string = {};

string.repeat = function(string, count)
{
    return new Array(count+1).join(string);
}

string.count = function(string)
{
    var count = 0;

    for (var i=1; i<arguments.length; i++)
    {
        var results = string.match(new RegExp(arguments[i], 'g'));
        count += results ? results.length : 0;
    }

    return count;
}

array = {};

array.merge = function(arr1, arr2)
{
    for (var i in arr2)
    {
        if (arr1[i] && typeof arr1[i] == 'object' && typeof arr2[i] == 'object')
            arr1[i] = array.merge(arr1[i], arr2[i]);
        else
            arr1[i] = arr2[i]
    }

    return arr1;
}

array.print = function(obj)
{
    var arr = [];
    $.each(obj, function(key, val) {
        var next = key + ": ";
        next += $.isPlainObject(val) ? array.print(val) : val;
        arr.push( next );
      });

    return "{ " +  arr.join(", ") + " }";
}

node = {};

node.objectify = function(node, params)
{
    if (!params)
        params = {};

    if (!params.selector)
        params.selector = "*";

    if (!params.key)
        params.key = "name";

    if (!params.value)
        params.value = "value";

    var o = {};
    var indexes = {};

    $(node).find(params.selector+"["+params.key+"]").each(function()
    {
        var name = $(this).attr(params.key),
            value = $(this).attr(params.value);

        var obj = $.parseJSON("{"+name.replace(/([^\[]*)/, function()
        {
            return '"'+arguments[1]+'"';
        }).replace(/\[(.*?)\]/gi, function()
        {
            if (arguments[1].length == 0)
            {
                var index = arguments[3].substring(0, arguments[2]);
                indexes[index] = indexes[index] !== undefined ? indexes[index]+1 : 0;

                return ':{"'+indexes[index]+'"';
            }
            else
                return ':{"'+escape(arguments[1])+'"';
        })+':"'+value.replace(/[\\"]/gi, function()
        {
            return "\\"+arguments[0]; 
        })+'"'+string.repeat('}', string.count(name, ']'))+"}");

        o = array.merge(o, obj);
    });

    return o;
}
</script>

The output of test:

$(document).ready(function()
{
    console.log(array.print(node.objectify($("form"), {})));
    console.log(array.print(node.objectify($("form"), {selector: "select"})));
});

on

<form>
    <input name='input[a]' type='text' value='text'/>
    <select name='input[b]'>
        <option>select</option>
    </select>

    <input name='otherinput[c][a]' value='a'/>
    <input name='otherinput[c][]' value='b'/>
    <input name='otherinput[d][b]' value='c'/>
    <input name='otherinput[c][]' value='d'/>

    <input type='hidden' name='anotherinput' value='hidden'/>
    <input type='hidden' name='anotherinput' value='1'/>

    <input type='submit' value='submit'/>
</form>

will yield:

{ input: { a: text, b: select }, otherinput: { c: { a: a, 0: b, 1: d }, d: { b: c } }, anotherinput: 1 }
{ input: { b: select } }

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

How do I print the key-value pairs of a dictionary in python

To Print key-value pair, for example:

players = {
     'lebron': 'lakers',
     'giannis':   'milwakee bucks',
     'durant':  'brooklyn nets',
     'kawhi':   'clippers',    
}

for player,club in players.items():

print(f"\n{player.title()} is the leader of {club}")

The above code, key-value pair:

 'lebron': 'lakers', - Lebron is key and lakers is value

for loop - specify key, value in dictionary.item():

Now Print (Player Name is the leader of club).

the Output is:

#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers

Change user-agent for Selenium web-driver

This is a short solution to change the request UserAgent on the fly.

Change UserAgent of a request with Chrome

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

then return your useragent:

agent = driver.execute_script("return navigator.userAgent")

Some sources

The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

Split long commands in multiple lines through Windows batch file

It seems however that splitting in the middle of the values of a for loop doesn't need a caret(and actually trying to use one will be considered a syntax error). For example,

for %n in (hello
bye) do echo %n

Note that no space is even needed after hello or before bye.

How to split a string into an array of characters in Python?

You can use extend method in list operations as well.

>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']

Phonegap + jQuery Mobile, real world sample or tutorial

These may not solve exactly your "real-world problems", but perhaps something useful ...

Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.

Also, my github page has code, but no tutorial, for two apps:

  • AppLaudApp - a run-control, debugging enabling, download complementary app to a cloud IDE
  • NameTrendz - an app developed in at Android Dev Camp to do a bunch of queries about popular name data. The PhoneGap and jQuery Mobile versions are from March 2011.

How to read line by line of a text area HTML tag

This works without needing jQuery:

var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

Android - Package Name convention

Com = commercial application (just like .com, most people register their app as a com app)
First level = always the publishing entity's' name
Second level (optional) = sub-devison, group, or project name
Final level = product name

For example he android launcher (home screen) is Com.Google.android.launcher

What is a good game engine that uses Lua?

There's our IDE / engine called Codea.

The runtime is iOS only, but it's open source. The development environment is iPad only at the moment.

Angular File Upload

This way I implement upload file to web API in project.

I share for whom concern.

const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);

Step by step

ASP.NET Web API

[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage() 
{
    string imageName = null;
    var httpRequest = HttpContext.Current.Request;
    //Upload Image
    var postedFile = httpRequest.Files["Image"];
    //Create custom filename
    if (postedFile != null)
    {
        imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
        imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
        var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
        postedFile.SaveAs(filePath);
    }
}

HTML form

<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">

    <img [src]="imageUrl" class="imgArea">
    <div class="image-upload">
        <label for="file-input">
            <img src="upload.jpg" />
        </label>

        <input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
        <button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
                class="material-icons">save</i></button>
    </div>
</form>

TS file to use API

OnSubmit(Image) {
    this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
      data => {
        console.log('done');
        Image.value = null;
        this.imageUrl = "/assets/img/logo.png";
      }
    );
  }

Service TS

uploadImage(componentId, image) {
        const formData: FormData = new FormData();
        formData.append('Image', image, image.name);
        formData.append('ComponentId', componentId);
        return this.http.post('/api/dashboard/UploadImage', formData);
    }

How to use 'find' to search for files created on a specific date?

@Max: is right about the creation time.

However, if you want to calculate the elapsed days argument for one of the -atime, -ctime, -mtime parameters, you can use the following expression

ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find's date rounding.)

So, to find any file modified on September 24th, 2008, the command would be:

find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

This will work if your version of find doesn't support the -newerXY predicates mentioned in @Arve:'s answer.

Access Tomcat Manager App from different host

Following two configuration is working for me.

1 .tomcat-users.xml details
--------------------------------
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <role rolename="tomcat"/>


  <user  username="tomcat"  password="tomcat" roles="tomcat"/>

  <user  username="admin"  password="admin" roles="admin-gui"/>

  <user  username="adminscript"  password="adminscrip" roles="admin-script"/>

  <user  username="tomcat"  password="s3cret" roles="manager-gui"/>
  <user  username="status"  password="status" roles="manager-status"/>

  <user  username="both"    password="both"   roles="manager-gui,manager-status"/>

  <user  username="script"  password="script" roles="manager-script"/>
  <user  username="jmx"     password="jmx"    roles="manager-jmx"/>

2. context.xml  of <tomcat>/webapps/manager/META-INF/context.xml and 
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>

How to display raw html code in PRE or something like it but without escaping it

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

In other words, use htmlspecialchars() in PHP

UIButton action in table view cell

Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

Python how to exit main function

use sys module

import sys
sys.exit()

wget ssl alert handshake failure

You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).

Run this command after having installed Chocolatey (as Administrator):

choco install wget

iOS application: how to clear notifications?

If you're coming here wondering the opposite (as I was), this post may be for you.

I couldn't figure out why my notifications were clearing when I cleared the badge...I manually increment the badge and then want to clear it when the user enters the app. That's no reason to clear out the notification center, though; they may still want to see or act on those notifications.

Negative 1 does the trick, luckily:

[UIApplication sharedApplication].applicationIconBadgeNumber = -1;

How to randomize (shuffle) a JavaScript array?

By using shuffle-array module you can shuffle your array . Here is a simple code of it .

var shuffle = require('shuffle-array'),
 //collection = [1,2,3,4,5];
collection = ["a","b","c","d","e"];
shuffle(collection);

console.log(collection);

Hope this helps.

Insert data into a view (SQL Server)

Inserting 'test' to name will lead to inserting NULL values to other columns of the base table which wont be correct as Id is a PRIMARY KEY and it cannot have NULL value.

Best Java obfuscator?

I don't know for sure if the solution is safe, but about the ClassGuard solution, it's interesting to read the article and the comment at: http://www.javaworld.com/community/?q=node/1604#comment-12296

How can I run multiple npm scripts in parallel?

How about forking

Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.


Minimal example

This would just run the scripts as-is and assume they're located in the parent script's directory.

// fork-minimal.js - run with: node fork-minimal.js

const childProcess = require('child_process');

let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));

Verbose example

This would run the scripts with arguments and configured by the many available options.

// fork-verbose.js - run with: node fork-verbose.js

const childProcess = require('child_process');

let scripts = [
    {
        path: 'some-script.js',
        args: ['-some_arg', '/some_other_arg'],
        options: {cwd: './', env: {NODE_ENV: 'development'}}
    },    
    {
        path: 'some-other-script.js',
        args: ['-another_arg', '/yet_other_arg'],
        options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
    }
];

let runningScripts= [];

scripts.forEach(script => {
    let runningScript = childProcess.fork(script.path, script.args, script.options);

   // Optionally attach event listeners to the script
   runningScript.on('close', () => console.log('Time to die...'))

    runningScripts.push(runningScript); // Keep a reference to the script for later use
});

Communicating with forked scripts

Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.

 runningScripts.forEach(runningScript => runningScript.kill());

For more available events and methods see the ChildProcess documentation

How to configure custom PYTHONPATH with VM and PyCharm?

An update to the correct answer phil provided, for more recent versions of Pycharm (e.g. 2019.2).

Go to File > Settings and find your project, then select Project Interpreter. Now click the button with a cog to the right of the selected project interpreter (used to be a ...).

enter image description here

From the drop-down menu select Show All... and in the dialog that opens click the icon with a folder and two sub-folders.

enter image description here

You are presented with a dialog with the current interpreter paths, click on + to add one more.

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:

My class looks like this :

public class NodeDate
{
    public string nodedate { get; set; }
}
public class NodeList1
{
    public List<NodeDate> nodedatelist { get; set; }
}

and my c# code as follows :

        public string getTradeContribs(string Id, string nodedates)
    {            
        //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}";  // sample Json format
        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
        string thisDate = "";
        foreach (var date in nodes.nodedatelist)
        {  // iterate through if needed...
            thisDate = date.nodedate;
        }   
    }

and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.

I hope this helps.... Bob

How to get primary key of table?

If you want to generate the list of primary keys dynamically via PHP in one go without having to run through each table you can use

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.key_column_usage 
WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY' 

though you do need to have access to the information.schema to do this.

Use index in pandas to plot data

monthly_mean.plot(y='A')

Uses index as x-axis by default.

Change private static final field using Java reflection

The whole point of a final field is that it cannot be reassigned once set. The JVM uses this guarentee to maintain consistency in various places (eg inner classes referencing outer variables). So no. Being able to do so would break the JVM!

The solution is not to declare it final in the first place.

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

JavaScript require() on client side

I find the component project giving a much more streamlined workflow than other solutions (including require.js), so I'd advise checking out https://github.com/component/component . I know this is a bit late answer but may be useful to someone.

How to change Navigation Bar color in iOS 7?

self.navigationBar.barTintColor = [UIColor blueColor];
self.navigationBar.tintColor = [UIColor whiteColor];
self.navigationBar.translucent = NO;

// *barTintColor* sets the background color
// *tintColor* sets the buttons color

How should I log while using multiprocessing in Python?

Simplest idea as mentioned:

  • Grab the filename and the process id of the current process.
  • Set up a [WatchedFileHandler][1]. The reasons for this handler are discussed in detail here, but in short there are certain worse race conditions with the other logging handlers. This one has the shortest window for the race condition.
    • Choose a path to save the logs to such as /var/log/...

What does the DOCKER_HOST variable do?

It points to the docker host! I followed these steps:

$ boot2docker start

Waiting for VM and Docker daemon to start...
..............................
Started.

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_HOST=tcp://192.168.59.103:2375

$ export DOCKER_HOST=tcp://192.168.59.103:2375

$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete 
511136ea3c5a: Download complete 
97fd97495e49: Download complete 
2dcbbf65536c: Download complete 
6a459d727ebb: Download complete 
8f321fc43180: Download complete 
03db2b23cf03: Download complete 
Hello world

See:
http://docs.docker.com/userguide/dockerizing/

Accessing dict keys like an attribute?

Let me post another implementation, which builds upon the answer of Kinvais, but integrates ideas from the AttributeDict proposed in http://databio.org/posts/python_AttributeDict.html.

The advantage of this version is that it also works for nested dictionaries:

class AttrDict(dict):
    """
    A class to convert a nested Dictionary into an object with key-values
    that are accessible using attribute notation (AttrDict.attribute) instead of
    key notation (Dict["key"]). This class recursively sets Dicts to objects,
    allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
    """

    # Inspired by:
    # http://stackoverflow.com/a/14620633/1551810
    # http://databio.org/posts/python_AttributeDict.html

    def __init__(self, iterable, **kwargs):
        super(AttrDict, self).__init__(iterable, **kwargs)
        for key, value in iterable.items():
            if isinstance(value, dict):
                self.__dict__[key] = AttrDict(value)
            else:
                self.__dict__[key] = value

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

USB Debugging option greyed out

I had an LG Android phone, and could not get USB to work with Windows, even after trying the following:

  1. Settings > About phone > Software info
  2. Tap 'Build number' 7x, and Activate Developer mode
  3. Settings > Developer options > USB debugging [ON]
  4. Settings > Developer options > Select USB Configuration > MTP
  5. Plug into Windows PC with USB cable.

It DOES show the phone as charging via USB (so the plug must be OK), but it does not show up under 'This PC' in Windows File Explorer as a Device/Drive.. grrr.

Turns out that not all USB cables are the same — some USB cable manufacturers only make their cable with 2wires instead of 4wires, so that they will charge, but not pass data through the cable — so if software solutions do not appear to be working, try changing the USB cable (!).

im writing this here so that maybe someone else doesnt have to waste half an hour figuring out that some USB cable manufacturer doesnt include all 4 wires in their USB cables... grrr.

Set TextView text from html-formatted string resource in XML

Android does not have a specification to indicate the type of resource string (e.g. text/plain or text/html). There is a workaround, however, that will allow the developer to specify this within the XML file.

  1. Define a custom attribute to specify that the android:text attribute is html.
  2. Use a subclassed TextView.

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. I'm rather surprised that this approach is not part of the API.

This solution works to the degree that the Android studio simulator will display the text as rendered HTML.

enter image description here

res/values/strings.xml (the string resource as HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

Display progress bar while doing some work in C#?

Indeed you are on the right track. You should use another thread, and you have identified the best ways to do that. The rest is just updating the progress bar. In case you don't want to use BackgroundWorker like others have suggested, there is one trick to keep in mind. The trick is that you cannot update the progress bar from the worker thread because UI can be only manipulated from the UI thread. So you use the Invoke method. It goes something like this (fix the syntax errors yourself, I'm just writing a quick example):

class MyForm: Form
{
    private void delegate UpdateDelegate(int Progress);

    private void UpdateProgress(int Progress)
    {
        if ( this.InvokeRequired )
            this.Invoke((UpdateDelegate)UpdateProgress, Progress);
        else
            this.MyProgressBar.Progress = Progress;
    }
}

The InvokeRequired property will return true on every thread except the one that owns the form. The Invoke method will call the method on the UI thread, and will block until it completes. If you don't want to block, you can call BeginInvoke instead.

How do you completely remove Ionic and Cordova installation from mac?

To uninstall Ionic and Cordova:

sudo npm uninstall -g cordova
sudo npm uninstall -g ionic

To install:

sudo npm install -g cordova

Java Try Catch Finally blocks without Catch

Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!

jQuery get value of select onChange

Try the event delegation method, this works in almost all cases.

$(document.body).on('change',"#selectID",function (e) {
   //doStuff
   var optVal= $("#selectID option:selected").val();
});

How to open VMDK File of the Google-Chrome-OS bundle 2012?

This is for vmware workstation 6.5

It is pretty far down.

select Create new virtual machine -> select custom ->
on compatibility page take defaults ->
check I will install os later -> click through several pages choosing other for OS, give it a name, make sure it IS NOT in the same folder as the VMDK file. Choose bridged network.

You will now see a screen asking to select disk, select existing virual disk. then browse and select the VMDK file

facebook: permanent Page Access Token?

Thanks to @donut I managed to get the never expiring access token in JavaScript.

// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Get the user data
    fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
    .then((data) => {
        return data.json();
    })
    .then((userData) => {
        // Get the page token
        fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
        .then((data) => {
            return data.json();
        })
        .then((pageToken) => {
            // Save the access token somewhere
            // You'll need it at later point
        })
        .catch((err) => console.error(err))
    })
    .catch((err) => console.error(err))
})
.catch((err) => {
    console.error(err);
})

and then I used the saved access token like this

fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Do stuff
})
.catch((err) => console.error(err))

I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.

The request was aborted: Could not create SSL/TLS secure channel

Try this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Can you delete multiple branches in one command with Git?

Well, in the worst case, you could use:

git branch | grep '3\.2' | xargs git branch -D

Mongoimport of json file

I tried something like this and it actually works:

mongoimport --db dbName --file D:\KKK\NNN\100YWeatherSmall.data.json

$.widget is not a function

Place your widget.js after core.js, but before any other jquery that calls the widget.js file. (Example: draggable.js) Precedence (order) matters in what javascript/jquery can 'see'. Always position helper code before the code that uses the helper code.

Is it possible to use JavaScript to change the meta-tags of the page?

meta-tags are part of the dom and can be accessed and -i guess- changed, but search-engines (the main consumers of meta-tags) won't see the change as the javascript won't be executed. so unless you're changing a meta-tag (refresh comes to mind) which has implications in the browser, this might be of little use?

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Error: getaddrinfo ENOTFOUND in nodejs for get call

getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http:

var optionsget = {
    host : 'localhost',
    port : 3010,
    path : '/quote/random', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

Regarding learning resources, you won't go wrong if you start with http://www.nodebeginner.org/ and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js , but there's many out there.

Visual Studio Code Search and Replace with Regular Expressions

If you want ex. change all country codes in .json file from uppercase to lowercase:

ctrl+h
alt+r
alt+c

Find: ([A-Z]{2,})
Replace: $1

alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter

ex file:

[
 {"id": "PL", "name": "Poland"},
 {"id": "NZ", "name": "New Zealand"},
 ...
]

ASP.NET email validator regex

Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

How to set Java environment path in Ubuntu

open jdk once installed resides generally in your /usr/lib/java-6-openjdk As usual you would need to set the JAVA_HOME, calsspath and Path In ubuntu 11.04 there is a environment file available in /etc where you need to set all the three paths . And then you would need to restart your system for the changes to take effect..

Here is a site to help you around http://aliolci.blogspot.com/2011/05/ubuntu-1104-set-new-environment.html

line breaks in a textarea

Don't do nl2br when you save it to the database. Do nl2br when you're displaying the text in HTML. I can strongly recommend to not store any HTML formatting in the database (unless you're using a rich HTML editor as well, in which case it would be silly not to).

A newline \n will just become a newline in the textarea.

Exception in thread "main" java.util.NoSuchElementException

simply don't close in

remove in.close() from your code.

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

What does <T> (angle brackets) mean in Java?

Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects

ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();

You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.

How can I restart a Java application?

If you realy need to restart your app, you could write a separate app the start it...

This page provides many different examples for different scenarios:

http://www.rgagnon.com/javadetails/java-0014.html

Why doesn't C++ have a garbage collector?

What type? should it be optimised for embedded washing machine controllers, cell phones, workstations or supercomputers?
Should it prioritise gui responsiveness or server loading?
should it use lots of memory or lots of CPU?

C/c++ is used in just too many different circumstances. I suspect something like boost smart pointers will be enough for most users

Edit - Automatic garbage collectors aren't so much a problem of performance (you can always buy more server) it's a question of predicatable performance.
Not knowing when the GC is going to kick in is like employing a narcoleptic airline pilot, most of the time they are great - but when you really need responsiveness!

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

How to call a method in another class of the same package?

If it's a static method, you can call it by using the class name in place of an object.

TypeError: 'list' object cannot be interpreted as an integer

since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.

use this

for i in range(len(myList)):

with this, we get the singular integer value which can be used easily

Animate the transition between fragments

Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.

How to include Javascript file in Asp.Net page

If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:

<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>' 
type="text/javascript"></script>

Lightweight workflow engine for Java

This really depends on your requirements. First, see if you really need a workflow engine (this or other sources). Unless you really need it, probably you should avoid it.

If you really need what provides a workflow engine, I would pick one that is already built. People who works with jbpm or activiti have much more experience than you in building workflow engines, so it is probably already tunned to improve performance.

How to execute an .SQL script file using c#

Put the command to execute the sql script into a batch file then run the below code

string batchFileName = @"c:\batosql.bat";
string sqlFileName = @"c:\MySqlScripts.sql";
Process proc = new Process();
proc.StartInfo.FileName = batchFileName;
proc.StartInfo.Arguments = sqlFileName;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.ErrorDialog = false;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileName);
proc.Start();
proc.WaitForExit();
if ( proc.ExitCode!= 0 )

in the batch file write something like this (sample for sql server)

osql -E -i %1

How to Consolidate Data from Multiple Excel Columns All into One Column

Take a look at Blockspring - you do need to install the plugin, but then it's just another function you call like this:

=BLOCKSPRING("twodee-array-reduce","input_array",D5:F7)

The source code and other details are here. If this doesn't suit and/or you want to build off my solution, you can fork my function (Python) or use another supported scripting language (Ruby, R, JS, etc...).

Dataframe to Excel sheet

I tested the previous answers found here: Assuming that we want the other four sheets to remain, the previous answers here did not work, because the other four sheets were deleted. In case we want them to remain use xlwings:

import xlwings as xw
import pandas as pd

filename = "test.xlsx"

df = pd.DataFrame([
    ("a", 1, 8, 3),
    ("b", 1, 2, 5),
    ("c", 3, 4, 6),
    ], columns=['one', 'two', 'three', "four"])

app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["Sheet5"]

ws.clear()
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df

# If formatting of column names and index is needed as xlsxwriter does it, 
# the following lines will do it (if the dataframe is not multiindex).
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2

wb.save(filename)
app.quit()

Show a div with Fancybox

You just use this and it will be helpful for you

$("#btnForm").click(function (){

$.fancybox({
    'padding':  0,
    'width':    1087,
    'height':   610,
    'type':     'iframe',
    content:   $('#divForm').show();
        });

});

CMake output/build directory

Turning my comment into an answer:

In case anyone did what I did, which was start by putting all the build files in the source directory:

cd src
cmake .

cmake will put a bunch of build files and cache files (CMakeCache.txt, CMakeFiles, cmake_install.cmake, etc) in the src dir.

To change to an out of source build, I had to remove all of those files. Then I could do what @Angew recommended in his answer:

mkdir -p src/build
cd src/build
cmake ..

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

instead of using

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);

try using

ReactDOM.unmountComponentAtNode(document.getElementById('root'));

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

C# Ignore certificate errors?

Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

.Net core:

using (var httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }

        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
        return false;
    };
    using (var httpClient = new HttpClient(httpClientHandler))
    {
        var httpResponse = httpClient.GetAsync("https://example.com").Result;
    }
}

.Net framework:

System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
    object sender,
    X509Certificate cert,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        return true;   //Is valid
    }

    if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
    {
        return true;
    }

    return false;
};

Update:

How to get cert.GetCertHashString() value in Chrome:

Click on Secure or Not Secure in the address bar.

enter image description here

enter image description here

Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower().

enter image description here

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

How to override toString() properly in Java?

Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?

@Override
    public String toString() {
        return "ContractDTO{" +
                "contractId='" + contractId + '\'' +
                ", contractTemplateId='" + contractTemplateId + '\'' +
                '}';
    }

modal View controllers - how to display and dismiss

I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1

let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)

In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by

let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)

And in VC2, when close the view controller, as usual we can use:

self.dismiss(animated: true, completion: nil)

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

PowerShell and the -contains operator

You can use like:

"12-18" -like "*-*"

Or split for contains:

"12-18" -split "" -contains "-"

grep output to show only matching file

Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *

Access mysql remote database from command line

To directly login to a remote mysql console, use the below command:

mysql -u {username} -p'{password}' \
    -h {remote server ip or name} -P {port} \
    -D {DB name}

For example

mysql -u root -p'root' \
        -h 127.0.0.1 -P 3306 \
        -D local

no space after -p as specified in the documentation

It will take you to the mysql console directly by switching to the mentioned database.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:

SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;

How to add dividers and spaces between items in RecyclerView?

I think using simple divider will help you

To add divider to each item:
1- Add this to drawable directory line_divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
    android:width="1dp"
    android:height="1dp" />
<solid android:color="#999999" />
</shape>

2- Create SimpleDividerItemDecoration class
I used this example to define this class:
https://gist.github.com/polbins/e37206fbc444207c0e92

package com.example.myapp;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.example.myapp.R;

public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration{
private Drawable mDivider;

public SimpleDividerItemDecoration(Resources resources) {
    mDivider = resources.getDrawable(R.drawable.line_divider);
}

public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = parent.getChildAt(i);

        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

        int top = child.getBottom() + params.bottomMargin;
        int bottom = top + mDivider.getIntrinsicHeight();

        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
  }
}


3- In activity or fragment that using RecyclerView, inside onCreateView add this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
 RecyclerView myRecyclerView = (RecyclerView) layout.findViewById(R.id.my_recycler_view);
 myRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
 ....
 }


4- To add spacing between Items
you just need to add padding property to your item view

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="4dp"
>
..... item structure
</RelativeLayout>

SQL How to replace values of select return?

You can do something like this:

SELECT id,name, REPLACE(REPLACE(hide,0,"false"),1,"true") AS hide FROM your-table

Hope this can help you.

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

If this issue occurs, kindly check web.config in below section

Below section gives the version of particular dll used

after checking this section in web.config, open solution explorer and select reference from the project tree as shown . Solution Explorer->Reference

After expanding reference, find the dll which caused the error. Right click on the dll reference and check for version like shown in the image above.

If both config dll version and referenced dll is different you would get this exception. Make sure both are of same version which would help.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How can I work with command line on synology?

I use GateOne from the synocommunity.

Go into settings in Package Center and add http://packages.synocommunity.com/ as a package source. Then you should be able to add it easily via Package Center.

Create a simple 10 second countdown

A solution using Promises, includes both progress bar & text countdown.

_x000D_
_x000D_
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));_x000D_
_x000D_
function ProgressCountdown(timeleft, bar, text) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    var countdownTimer = setInterval(() => {_x000D_
      timeleft--;_x000D_
_x000D_
      document.getElementById(bar).value = timeleft;_x000D_
      document.getElementById(text).textContent = timeleft;_x000D_
_x000D_
      if (timeleft <= 0) {_x000D_
        clearInterval(countdownTimer);_x000D_
        resolve(true);_x000D_
      }_x000D_
    }, 1000);_x000D_
  });_x000D_
}
_x000D_
<div class="row begin-countdown">_x000D_
  <div class="col-md-12 text-center">_x000D_
    <progress value="10" max="10" id="pageBeginCountdown"></progress>_x000D_
    <p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get a list of resources from classpath directory

I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem it looks like you can treat the objects in that ZIP as a "regular" file.

In the linked documentation above:

Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.

Once you have an instance of a zip file system, you can invoke the methods of the [java.nio.file.FileSystem][3] and [java.nio.file.Path][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.

The documentation for the jdk.zipfs module in [Java 11 states][5]:

The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [FileSystems.newFileSystem][6] if installed.

Here is a contrived example I did using your example resources. Note that a .zip is a .jar, but you could adapt your code to instead use classpath resources:

Setup

cd /tmp
mkdir -p x/y/z
touch x/y/z/{a,b,c}.html
echo 'hello world' > x/y/z/d
zip -r example.zip x

Java

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.stream.Collectors;

public class MkobitZipRead {

  public static void main(String[] args) throws IOException {
    final URI uri = URI.create("jar:file:/tmp/example.zip");
    try (
        final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
    ) {
      Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
      System.out.println("-----");
      final String manifest = Files.readAllLines(
          zipfs.getPath("x", "y", "z").resolve("d")
      ).stream().collect(Collectors.joining(System.lineSeparator()));
      System.out.println(manifest);
    }
  }

}

Output

Files in zip:/
Files in zip:/x/
Files in zip:/x/y/
Files in zip:/x/y/z/
Files in zip:/x/y/z/c.html
Files in zip:/x/y/z/b.html
Files in zip:/x/y/z/a.html
Files in zip:/x/y/z/d
-----
hello world

Does JavaScript guarantee object property order?

Property order in normal Objects is a complex subject in Javascript.

While in ES5 explicitly no order has been specified, ES2015 has an order in certain cases. Given is the following object:

o = Object.create(null, {
  m: {value: function() {}, enumerable: true},
  "2": {value: "2", enumerable: true},
  "b": {value: "b", enumerable: true},
  0: {value: 0, enumerable: true},
  [Symbol()]: {value: "sym", enumerable: true},
  "1": {value: "1", enumerable: true},
  "a": {value: "a", enumerable: true},
});

This results in the following order (in certain cases):

Object {
  0: 0,
  1: "1",
  2: "2",
  b: "b",
  a: "a",
  m: function() {},
  Symbol(): "sym"
}
  1. integer-like keys in ascending order
  2. normal keys in insertion order
  3. Symbols in insertion order

Thus, there are three segments, which may alter the insertion order (as happened in the example). And integer-like keys don't stick to the insertion order at all.

The question is, for what methods this order is guaranteed in the ES2015 spec?

The following methods guarantee the order shown:

  • Object.assign
  • Object.defineProperties
  • Object.getOwnPropertyNames
  • Object.getOwnPropertySymbols
  • Reflect.ownKeys

The following methods/loops guarantee no order at all:

  • Object.keys
  • for..in
  • JSON.parse
  • JSON.stringify

Conclusion: Even in ES2015 you shouldn't rely on the property order of normal objects in Javascript. It is prone to errors. Use Map instead.

Apply jQuery datepicker to multiple instances

To change use of class instead of ID

<script type="text/javascript"> 
    $(function() { 
        $('.my_date1').datepicker(); 
        $('.my_date2').datepicker(); 
        $('.my_date3').datepicker(); 
        ... 
    }); 
</script>

Python: how to capture image from webcam on click using OpenCV

Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

You can see my github code here

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

Remove last 3 characters of string or number in javascript

Remove last 3 characters of a string

var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'

Remove last 3 digits of a number

var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995

jQuery get selected option value (not the text, but the attribute 'value')

It's working better. Try it.

let value = $("select#yourId option").filter(":selected").val();

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

Python not working in command prompt?

When you add the python directory to the path (Computer > Properties > Advanced System Settings > Advanced > Environmental Variables > System Variables > Path > Edit), remember to add a semicolon, then make sure that you are adding the precise directory where the file "python.exe" is stored (e.g. C:\Python\Python27 if that is where "python.exe" is stored). Then restart the command prompt.

How to convert all text to lowercase in Vim

  • Toggle case "HellO" to "hELLo" with g~ then a movement.
  • Uppercase "HellO" to "HELLO" with gU then a movement.
  • Lowercase "HellO" to "hello" with gu then a movement.

For examples and more info please read this: http://vim.wikia.com/wiki/Switching_case_of_characters

Execute PHP scripts within Node.js web server

Take a look here: https://github.com/davidcoallier/node-php

From their read me:

Inline PHP Server Running on Node.js

Be worried, be very worried. The name NodePHP takes its name from the fact that we are effectively turning a nice Node.js server into a FastCGI interface that interacts with PHP-FPM.

This is omega-alpha-super-beta-proof-of-concept but it already runs a few simple scripts. Mostly done for my talks on Node.js for PHP Developers this turns out to be quite an interesting project that we are most likely be going to use with Orchestra when we decide to release our Inline PHP server that allows people to run PHP without Apache, Nginx or any webserver.

Yes this goes against all ideas and concepts of Node.js but the idea is to be able to create a web-server directly from any working directory to allow developers to get going even faster than it was before. No need to create vhosts or server blocks ore modify your /etc/hosts anymore.

View more than one project/solution in Visual Studio

There is a way to store multiple solutions in one instance of VS.

Attempt the following steps:

  1. File > Open > Project/Solution
  2. This will bring up the open project window, notice at the bottom where it says options, select add to solution

Add to Solution

  1. Then select the file you want to add and click open
  2. This will then add the solution to your project. You still won't be able to run the same project in a single instance of VS, but you can have all your code organized in one place.

NOTE: This worked for Visual Studio 2013 Professional

How to pass table value parameters to stored procedure from .net code

Generic

   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
    {
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)
        {
            tbl.Rows.Add(selector.Invoke(item));

        }

        return tbl;

    }

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

How can I read command line parameters from an R script?

In bash, you can construct a command line like the following:

$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
 [1]  1  2  3  4  5  6  7  8  9 10
[1] 5.5
[1] 3.027650
$

You can see that the variable $z is substituted by bash shell with "10" and this value is picked up by commandArgs and fed into args[2], and the range command x=1:10 executed by R successfully, etc etc.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

How to select all columns, except one column in pandas?

Here is another way:

df[[i for i in list(df.columns) if i != '<your column>']]

You just pass all columns to be shown except of the one you do not want.

Specify an SSH key for git push for a given domain

From git 2.10 upwards it is also possible to use the gitconfig sshCommand setting. Docs state :

If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.

An usage example would be: git config core.sshCommand "ssh -i ~/.ssh/[insert_your_keyname]

In some cases this doesn't work because ssh_config overriding the command, in this case try ssh -i ~/.ssh/[insert_your_keyname] -F /dev/null to not use the ssh_config.

Convert a timedelta to days, hours and minutes

I don't understand

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

how about this

days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0

You get minutes and seconds of a minute as a float.

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

Copy rows from one table to another, ignoring duplicates

I realize this is old, but I got here from google and after reviewing the accepted answer I did my own statement and it worked for me hope someone will find it useful:

    INSERT IGNORE INTO destTable SELECT id, field2,field3... FROM origTable

Edit: This works on MySQL I did not test on MSSQL

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

How to extract epoch from LocalDate and LocalDateTime?

This is one way without using time a zone:

LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);

How to fit a smooth curve to my data in R?

LOESS is a very good approach, as Dirk said.

Another option is using Bezier splines, which may in some cases work better than LOESS if you don't have many data points.

Here you'll find an example: http://rosettacode.org/wiki/Cubic_bezier_curves#R

# x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
    {
    outx <- NULL
    outy <- NULL

    i <- 1
    for (t in seq(0, 1, length.out=n))
        {
        b <- bez(x, y, t)
        outx[i] <- b$x
        outy[i] <- b$y

        i <- i+1
        }

    return (list(x=outx, y=outy))
    }

bez <- function(x, y, t)
    {
    outx <- 0
    outy <- 0
    n <- length(x)-1
    for (i in 0:n)
        {
        outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
        outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
        }

    return (list(x=outx, y=outy))
    }

# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red")

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Comments in Android Layout xml

Unbelievably, in 2019 with Android studio 3.3 (I don't know exact version, at least 3.3), it is possible to use double slash comment to xml.

But if you use double slash comment in xml, IDE shows warning.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    // this works

    /* this works too */

    /*
    multi line comment
    multi line comment
    */

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World! yeah"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

How to center icon and text in a android button with width set to "fill parent"

I used LinearLayout instead of Button. The OnClickListener, which I need to use works fine also for LinearLayout.

<LinearLayout
    android:id="@+id/my_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selector"
    android:gravity="center"
    android:orientation="horizontal"
    android:clickable="true">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="15dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:src="@drawable/icon" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Text" />

</LinearLayout>

Finding the length of an integer in C

length of n:

length =  ( i==0 ) ? 1 : (int)log10(n)+1;

Parsing JSON object in PHP using json_decode

When you json decode , force it to return an array instead of object.

$data = json_decode($json, TRUE); -> // TRUE

This will return an array and you can access the values by giving the keys.

Java decimal formatting using String.format?

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

401 Unauthorized: Access is denied due to invalid credentials

In my case, what made it work was changing the Anonymous User identity from Specific user (IUSR) to Application Pool Identity. Weird enought because other sites are using the specific user IUSR and work fine.

How to make an HTTP POST web request

Why is this not totally trivial? Doing the request is not and especially not dealing with the results and seems like there are some .NET bugs involved as well - see Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

I ended up with this code:

static async Task<(bool Success, WebExceptionStatus WebExceptionStatus, HttpStatusCode? HttpStatusCode, string ResponseAsString)> HttpRequestAsync(HttpClient httpClient, string url, string postBuffer = null, CancellationTokenSource cts = null) {
    try {
        HttpResponseMessage resp = null;

        if (postBuffer is null) {
            resp = cts is null ? await httpClient.GetAsync(url) : await httpClient.GetAsync(url, cts.Token);

        } else {
            using (var httpContent = new StringContent(postBuffer)) {
                resp = cts is null ? await httpClient.PostAsync(url, httpContent) : await httpClient.PostAsync(url, httpContent, cts.Token);
            }
        }

        var respString = await resp.Content.ReadAsStringAsync();
        return (resp.IsSuccessStatusCode, WebExceptionStatus.Success, resp.StatusCode, respString);

    } catch (WebException ex) {
        WebExceptionStatus status = ex.Status;
        if (status == WebExceptionStatus.ProtocolError) {
            // Get HttpWebResponse so that you can check the HTTP status code.
            using (HttpWebResponse httpResponse = (HttpWebResponse)ex.Response) {
                return (false, status, httpResponse.StatusCode, httpResponse.StatusDescription);
            }
        } else {
            return (false, status, null, ex.ToString()); 
        }

    } catch (TaskCanceledException ex) {
        if (cts is object && ex.CancellationToken == cts.Token) {
            // a real cancellation, triggered by the caller
            return (false, WebExceptionStatus.RequestCanceled, null, ex.ToString());
        } else {
            // a web request timeout (possibly other things!?)
            return (false, WebExceptionStatus.Timeout, null, ex.ToString());
        }

    } catch (Exception ex) {
        return (false, WebExceptionStatus.UnknownError, null, ex.ToString());
    }
}

This will do a GET or POST depends if postBuffer is null or not

if Success is true the response will then be in ResponseAsString

if Success is false you can check WebExceptionStatus, HttpStatusCode and ResponseAsString to try to see what went wrong.

php_network_getaddresses: getaddrinfo failed: Name or service not known

in simple word your site has been blocked to access network. may be you have automated some script and it caused your whole website to be blocked. the better way to resolve this is contact that site and tell your issue. if issue is genuine they may consider unblocking

What HTTP status response code should I use if the request is missing a required parameter?

In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.

HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.

Reference: w3.org/Protocols/

So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.

Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.

In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409

How to use <DllImport> in VB.NET?

You can also try this

Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

I always use Declare Function instead of DllImport... Its more simply, its shorter and does the same

HTML Form: Select-Option vs Datalist-Option

Think of it as the difference between a requirement and a suggestion. For the select element, the user is required to select one of the options you've given. For the datalist element, it is suggested that the user select one of the options you've given, but he can actually enter anything he wants in the input.

Edit 1: So which one you use depends upon your requirements. If the user must enter one of your choices, use the select element. If the use can enter whatever, use the datalist element.

Edit 2: Found this tidbit in the HTML Living Standard: "Each option element that is a descendant of the datalist element...represents a suggestion."

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

How to add meta tag in JavaScript

Try

_x000D_
_x000D_
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'
_x000D_
_x000D_
_x000D_

cin and getline skipping input

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

My personal favourite for this if no characters past the newline are needed is cin.sync(). However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore(). Or make use of std::ws to remove leading whitespace if desirable:

int a;

cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
//discard characters until newline is found

//my method: cin.sync(); //discard unread characters

string s;
getline (cin, s); //newline is gone, so this executes

//other method: getline(cin >> ws, s); //remove all leading whitespace

Stop fixed position at footer

Here is the @Sang solution but without Jquery.

_x000D_
_x000D_
var socialFloat = document.querySelector('#social-float');_x000D_
var footer = document.querySelector('#footer');_x000D_
_x000D_
function checkOffset() {_x000D_
  function getRectTop(el){_x000D_
    var rect = el.getBoundingClientRect();_x000D_
    return rect.top;_x000D_
  }_x000D_
  _x000D_
  if((getRectTop(socialFloat) + document.body.scrollTop) + socialFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 10)_x000D_
    socialFloat.style.position = 'absolute';_x000D_
  if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))_x000D_
    socialFloat.style.position = 'fixed'; // restore when you scroll up_x000D_
  _x000D_
  socialFloat.innerHTML = document.body.scrollTop + window.innerHeight;_x000D_
}_x000D_
_x000D_
document.addEventListener("scroll", function(){_x000D_
  checkOffset();_x000D_
});
_x000D_
div.social-float-parent { width: 100%; height: 1000px; background: #f8f8f8; position: relative; }_x000D_
div#social-float { width: 200px; position: fixed; bottom: 10px; background: #777; }_x000D_
div#footer { width: 100%; height: 200px; background: #eee; }
_x000D_
<div class="social-float-parent">_x000D_
    <div id="social-float">_x000D_
        float..._x000D_
    </div>_x000D_
</div>_x000D_
<div id="footer">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ship an application with a database

Shipping the database inside the apk and then copying it to /data/data/... will double the size of the database (1 in apk, 1 in data/data/...), and will increase the apk size (of course). So your database should not be too big.

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

CSS opacity only to background color, not the text on it?

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
#block {_x000D_
  background: #CCC;_x000D_
  filter: alpha(opacity=60);_x000D_
  /* IE */_x000D_
  -moz-opacity: 0.6;_x000D_
  /* Mozilla */_x000D_
  opacity: 0.6;_x000D_
  /* CSS3 */_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="block"></div>_x000D_
  <div id="text">Test</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

Apply formula to the entire column

Found another solution:

  • Apply the formula to the first 3 or 4 cells of the column
  • Ctrl + C the formula in one of the last rows (if you copy the first line it won't work)
  • Click on the column header to select the whole column
  • Press Ctrl + V to paste it in all cells bellow

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

How to run Java program in terminal with external library JAR

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

Passing arguments forward to another javascript function

The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments object.

The arguments object contains one element for each actual parameter provided to the function. When you call a you supply three arguments: the numbers 1, 2, and, 3. So, arguments contains [1, 2, 3].

function a(args){
    console.log(arguments) // [1, 2, 3]
    b(arguments);
}

When you call b, however, you pass exactly one argument: a's arguments object. So arguments contains [[1, 2, 3]] (i.e. one element, which is a's arguments object, which has properties containing the original arguments to a).

function b(args){
    // arguments are lost?
    console.log(arguments) // [[1, 2, 3]]
}

a(1,2,3);

As @Nick demonstrated, you can use apply to provide a set arguments object in the call.

The following achieves the same result:

function a(args){
    b(arguments[0], arguments[1], arguments[2]); // three arguments
}

But apply is the correct solution in the general case.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This might be due to the maximum number of characters allowed for a specific column, like in sql one field might have following Data Type nvarchar(5) but the number of characters entered from the user is more than the specified, hence the error arises.

How to exit a function in bash

Use:

return [n]

From help return

return: return [n]

Return from a shell function.

Causes a function or sourced script to exit with the return value
specified by N.  If N is omitted, the return status is that of the
last command executed within the function or script.

Exit Status:
Returns N, or failure if the shell is not executing a function or script.

Facebook key hash does not match any stored key hashes

Just run command adb logcat | grep hash and look for something like Key hash ABCDEFGH1234= does not match any stored key. Now save this hash on your fb developer console.

'Incorrect SET Options' Error When Building Database Project

I found the solution for this problem:

  1. Go to the Server Properties.
  2. Select the Connections tab.
  3. Check if the ansi_padding option is unchecked.

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

Make docker use IPv4 for port binding

If you want your container ports to bind on your ipv4 address, just :

  • find the settings file
    • /etc/sysconfig/docker-network on RedHat alike
    • /etc/default/docker-network on Debian ans alike
  • edit the network settings
    • add DOCKER_NETWORK_OPTIONS=-ip=xx.xx.xx.xx
    • xx.xx.xx.xx being your real ipv4 (and not 0.0.0.0)
  • restart docker deamon

works for me on docker 1.9.1

AngularJS: How can I pass variables between controllers?

Second Approach :

angular.module('myApp', [])
  .controller('Ctrl1', ['$scope',
    function($scope) {

    $scope.prop1 = "First";

    $scope.clickFunction = function() {
      $scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
    };
   }
])
.controller('Ctrl2', ['$scope',
    function($scope) {
      $scope.prop2 = "Second";

        $scope.$on("update_Ctrl2_controller", function(event, prop) {
        $scope.prop = prop;

        $scope.both = prop + $scope.prop2; 
    });
  }
])

Html :

<div ng-controller="Ctrl2">
  <p>{{both}}</p>
</div>

<button ng-click="clickFunction()">Click</button>

For more details see plunker :

http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

input file appears to be a text format dump. Please use psql

If you have a full DB dump:

PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql

If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers. You can then use this:

cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin

On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump is incompatible with pg_restore. With some additional keys, however, it is. WTF?

Python can't find module in the same folder

If you are sure that all the modules, files you're trying to import are in the same folder and they should be picked directly just by giving the name and not the reference path then your editor or terminal should have opened the main folder where all the files/modules are present.

Either, try running from Terminal, make sure first you go to the correct directory.

cd path to the root folder where all the modules are

python script.py

Or if running [F5] from the editor i.e VsCode then open the complete folder there and not the individual files.

Change the background color of CardView programmatically

You can use below

cardview.setBackgroundColor(Color.parseColor("#EAEDED"));

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

Delete many rows from a table using id in Mysql

Hope it helps:

DELETE FROM tablename 
WHERE tablename.id = ANY (SELECT id FROM tablename WHERE id = id);

Intercept and override HTTP requests from WebView

You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest

Maybe this could help?

Switch php versions on commandline ubuntu 16.04

I think you should try this

From php5.6 to php7.1

sudo a2dismod php5.6
sudo a2enmod php7.1
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php7.1
sudo update-alternatives --set phar /usr/bin/phar7.1
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1

From php7.1 to php5.6

sudo a2dismod php7.1
sudo a2enmod php5.6
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

A corresponding cross for ✓ &#x2713; would be ✗ &#x2717; I think (Dingbats).

Swipe ListView item From right to left show delete button

Define a ViewPager in your layout .xml:

<android.support.v4.view.ViewPager
    android:id="@+id/example_pager"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/abc_action_bar_default_height" />

And then, in your activity / fragment, set a custom pager adapter:

In an activity:

protected void onCreate(Bundle savedInstanceState) {
    PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
    ViewPager pager = (ViewPager) findViewById(R.id.example_pager);

    pager.setAdapter(adapter);
    // pager.setOnPageChangeListener(this); // You can set a page listener here
    pager.setCurrentItem(0);
}

In a fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, container, false);

    if (view != null) {
        PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
        ViewPager pager = (ViewPager) view.findViewById(R.id.example_pager);

        pager.setAdapter(adapter);
        // pager.setOnPageChangeListener(this); // You can set a page listener here
        pager.setCurrentItem(0);
    }

    return view;
}

Create our custom pager class:

// setup your PagerAdapter which extends FragmentPagerAdapter
class PagerAdapter extends FragmentPagerAdapter {
    public static final int NUM_PAGES = 2;
    private CustomFragment[] mFragments = new CustomFragment[NUM_PAGES];
    public PagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }
    @ Override
    public int getCount() {
        return NUM_PAGES;
    }
    @ Override
    public Fragment getItem(int position) {
        if (mFragments[position] == null) {
               // this calls the newInstance from when you setup the ListFragment
            mFragments[position] = new CustomFragment();
        }
        return mFragments[position];
    }
}

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

jQuery Toggle Text?

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    var text = $('#show-background').text();
    $('#show-background').text(
        text == "Show Background" ? "Show Text" : "Show Background");
});

Toggle hides or shows elements. You could achieve the same effect using toggle by having 2 links and toggling them when either is clicked.

Match exact string

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you would want to use \b (word boundaries):

_x000D_
_x000D_
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
_x000D_
_x000D_

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Disable Transaction Log

There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.

To do so,

USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;

To change it back:

USE master ;
ALTER DATABASE model SET RECOVERY FULL ;

In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Cannot call getSupportFragmentManager() from activity

I used FragmentActivity

TabAdapter = new TabPagerAdapter(((FragmentActivity) getActivity()).getSupportFragmentManager());

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

How to make a simple popup box in Visual C#?

Try this:

string text = "My text that I want to display";
MessageBox.Show(text);

R not finding package even after package installation

I had this problem and the issue was that I had the package loaded in another R instance. Simply closing all R instances and installing on a fresh instance allowed for the package to be installed.

Generally, you can also install if every remaining instance has never loaded the package as well (even if it installed an old version).

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

My which pip shows the following path:

$ which pip
/home/kmario23/anaconda3/bin/pip

So, whatever package I install using pip install <package-name> will have to be reflected in the list of packages when the list is exported using:

$ conda list --export > conda_list.txt

But, I don't. So, instead I used the following command as suggested by several others:

# get environment name by
$ conda-env list

# get list of all installed packages by (conda, pip, etc.,)
$ conda-env export -n <my-environment-name> > all_packages.yml
# if you haven't created any specific env, then just use 'root'

Now, I can see all the packages in my all-packages.yml file.

How to change indentation in Visual Studio Code?

Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.

That's what this vscode extension is doing for you

enter image description here

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

ab load testing

I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.

the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".

the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!

but did anyone think to "localhost" on any apache server for example www.apachefriends.org?

you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".

and then: benchmark it!

bench.php

<?php

for($i=1;$i<50000;$i++){
    print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>

void.php

<?php
?>

on your Desktop you should use a .bat file(in Windows) like this:

bench.bat

"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause

Now if you pay attention closely ...

the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!

here i got :

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/void.php
Document Length:        0 bytes

Concurrency Level:      1
Time taken for tests:   11.219 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2150000 bytes
HTML transferred:       0 bytes
Requests per second:    891.34 [#/sec] (mean)
Time per request:       1.122 [ms] (mean)
Time per request:       1.122 [ms] (mean, across all concurrent requests)
Transfer rate:          187.15 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:     0    1   0.9      1      17
Waiting:        0    1   0.9      1      17
Total:          0    1   0.9      1      17

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      2
  98%      2
  99%      3
 100%     17 (longest request)

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/bench.php
Document Length:        1799964 bytes

Concurrency Level:      1
Time taken for tests:   177.006 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      18001600000 bytes
HTML transferred:       17999640000 bytes
Requests per second:    56.50 [#/sec] (mean)
Time per request:       17.701 [ms] (mean)
Time per request:       17.701 [ms] (mean, across all concurrent requests)
Transfer rate:          99317.00 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:    12   17   3.2     17      90
Waiting:        0    1   1.1      1      26
Total:         13   18   3.2     18      90

Percentage of the requests served within a certain time (ms)
  50%     18
  66%     19
  75%     19
  80%     20
  90%     21
  95%     22
  98%     23
  99%     26
 100%     90 (longest request)

c:\xampp\htdocs\bench>pause
Press any key to continue . . .

90-17= 73 the result i expect !

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

simply use cookies to store your visited page list.

and apply some if else.

EDIT: also use ServerVariables HTTP_REFERER.

Logical operator in a handlebars.js {{#if}} conditional

You can do it simply by using the logical operator like this shown below:

{{#if (or(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/if}}

{{#if (and(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/if}}

Before closing if you can write your business logic

Awaiting multiple Tasks with different results

You can store them in tasks, then await them all:

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

await Task.WhenAll(catTask, houseTask, carTask);

Cat cat = await catTask;
House house = await houseTask;
Car car = await carTask;

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

Adding items to a JComboBox

create a new class called ComboKeyValue.java

    public class ComboKeyValue {
        private String key;
        private String value;
    
        public ComboKeyValue(String key, String value) {
            this.key = key;
            this.value = value;
        }
        
        @Override
        public String toString(){
            return key;
        }
    
        public String getKey() {
            return key;
        }
    
        public String getValue() {
            return value;
        }
}

when you want to add a new item, just write the code as below

 DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new ComboKeyValue("key", "value"));
    properties.setModel(model);

ImportError: No module named 'pygame'

go to python/scripts folder, open a command window to this path, type the following:

C:\python34\scripts> python -m pip install pygame

To test it, open python IDE and type

import pygame

print (pygame.ver)

It worked for me...

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

Best way to parse command line arguments in C#?

The WPF TestApi library comes with one of the nicest command line parsers for C# development. I highly recommend looking into it, from Ivo Manolov's blog on the API:

// EXAMPLE #2:
// Sample for parsing the following command-line:
// Test.exe /verbose /runId=10
// This sample declares a class in which the strongly-
// typed arguments are populated
public class CommandLineArguments
{
   bool? Verbose { get; set; }
   int? RunId { get; set; }
}

CommandLineArguments a = new CommandLineArguments();
CommandLineParser.ParseArguments(args, a);

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

filter_input(INPUT_POST, 'var_name') instead of $_POST['var_name']
filter_input_array(INPUT_POST) instead of $_POST

How to while loop until the end of a file in Python without checking for empty line?

I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Before importing the project, it should be converted into eclipse project mvn eclipse: eclipse Then i found the following error. An internal error occurred during: "Importing Maven projects".Unsupported IClasspathEntry kind=4

Where is the value kind = "var" that M2E does not recognize and therefore throws the error.

Now type this. mvn eclipse: clean

Now refresh the project in eclipse or re-import.

Where in memory are my variables stored in C?

I am referring to these variables only from the C perspective.

From the perspective of the C language, all that matters is extent, scope, linkage, and access; exactly how items are mapped to different memory segments is up to the individual implementation, and that will vary. The language standard doesn't talk about memory segments at all. Most modern architectures act mostly the same way; block-scope variables and function arguments will be allocated from the stack, file-scope and static variables will be allocated from a data or code segment, dynamic memory will be allocated from a heap, some constant data will be stored in read-only segments, etc.

What's the difference between a POST and a PUT HTTP REQUEST?

Actually there's no difference other than their title. There's actually a basic difference between GET and the others. With a "GET"-Request method, you send the data in the url-address-line, which are separated first by a question-mark, and then with a & sign.

But with a "POST"-request method, you can't pass data through the url, but you have to pass the data as an object in the so called "body" of the request. On the server side, you have then to read out the body of the received content in order to get the sent data. But there's on the other side no possibility to send content in the body, when you send a "GET"-Request.

The claim, that "GET" is only for getting data and "POST" is for posting data, is absolutely wrong. Noone can prevent you from creating new content, deleting existing content, editing existing content or do whatever in the backend, based on the data, that is sent by the "GET" request or by the "POST" request. And nobody can prevent you to code the backend in a way, that with a "POST"-Request, the client asks for some data.

With a request, no matter which method you use, you call a URL and send or don't send some data to specify, which information you want to pass to the server to deal with your request, and then the client gets an answer from the server. The data can contain whatever you want to send, the backend is allowed to do whatever it wants with the data and the response can contain any information, that you want to put in there.

There are only these two BASIC METHODS. GET and POST. But it's their structure, which makes them different and not what you code in the backend. In the backend you can code whatever you want to, with the received data. But with the "POST"-request you have to send/retrieve the data in the body and not in the url-addressline, and with a "GET" request, you have to send/retrieve data in the url-addressline and not in the body. That's all.

All the other methods, like "PUT", "DELETE" and so on, they have the same structure as "POST".

The POST Method is mainly used, if you want to hide the content somewhat, because whatever you write in the url-addressline, this will be saved in the cache and a GET-Method is the same as writing a url-addressline with data. So if you want to send sensitive data, which is not always necessarily username and password, but for example some ids or hashes, which you don't want to be shown in the url-address-line, then you should use the POST method.

Also the URL-Addressline's length is limited to 1024 symbols, whereas the "POST"-Method is not restricted. So if you have a bigger amount of data, you might not be able to send it with a GET-Request, but you'll need to use the POST-Request. So this is also another plus point for the POST-request.

But dealing with the GET-request is way easier, when you don't have complicated text to send. Otherwise, and this is another plus point for the POST method, is, that with the GET-method you need to url-encode the text, in order to be able to send some symbols within the text or even spaces. But with a POST method you have no restrictions and your content doesn't need to be changed or manipulated in any way.

Using ChildActionOnly in MVC

The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. An action method doesn’t need to have this attribute to be used as a child action, but we tend to use this attribute to prevent the action methods from being invoked as a result of a user request. Having defined an action method, we need to create what will be rendered when the action is invoked. Child actions are typically associated with partial views, although this is not compulsory.

  1. [ChildActionOnly] allowing restricted access via code in View

  2. State Information implementation for specific page URL. Example: Payment Page URL (paying only once) razor syntax allows to call specific actions conditional

How to install Guest addition in Mac OS as guest and Windows machine as host

You can use SSH and SFTP as suggested here.

  1. In the Guest OS (Mac OS X), open System Preferences > Sharing, then activate Remote Login; note the ip address specified in the Remote Login instructions, e.g. ssh [email protected]
  2. In VirtualBox, open Devices > Network > Network Settings > Advanced > Port Forwarding and specify Host IP = 127.0.0.1, Host Port 2222, Guest IP 10.0.2.15, Guest Port 22
  3. On the Host OS, run the following command sftp -P 2222 [email protected]; if you prefer a graphical interface, you can use FileZilla

Replace user and 10.0.2.15 with the appropriate values relevant to your configuration.

Joining three tables using MySQL

Use this:

SELECT s.name AS Student, c.name AS Course 
FROM student s 
  LEFT JOIN (bridge b CROSS JOIN course c) 
    ON (s.id = b.sid AND b.cid = c.id);

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


EDIT:

Just came across this post which provides a rather long comparison of the speeds of these methods.

Algorithm to find Largest prime factor of a number

Python Iterative approach by removing all prime factors from the number

def primef(n):
    if n <= 3:
        return n
    if n % 2 == 0:
        return primef(n/2)
    elif n % 3 ==0:
        return primef(n/3)
    else:
        for i in range(5, int((n)**0.5) + 1, 6):
            #print i
            if n % i == 0:
                return primef(n/i)
            if n % (i + 2) == 0:
                return primef(n/(i+2))
    return n

how to query child objects in mongodb

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})

How to display line numbers in 'less' (GNU)

The command line flags -N or --LINE-NUMBERS causes a line number to be displayed at the beginning of each line in the display.

You can also toggle line numbers without quitting less by typing -N<return>. It it possible to toggle any of less's command line options in this way.

HTTP requests and JSON parsing in Python

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

HTTPS connections over proxy servers

as far as i can remember, you need to use a HTTP CONNECT query on the proxy. this will convert the request connection to a transparent TCP/IP tunnel.

so you need to know if the proxy server you use support this protocol.

How to reenable event.preventDefault?

You can re-activate the actions by adding

this.delegateEvents();  // Re-activates the events for all the buttons

If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

How do I redirect users after submit button click?

Why don't you use plain html?

<form action="login.php" method="post" name="form1" id="form1">
...
</form>

In your login.php you can then use the header() function.

header("Location: welcome.php");