Programs & Examples On #Apache commons dbcp

Apache-commons-dbcp provides an efficient implementation of the Database Connection Pool under the Apache license.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Bro, you can also write code as below:

import java.sql.*;
import java.io.*;
public class InsertDatabase {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try
    {  
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection(  
        "jdbc:mysql://localhost:3306/Maulik","root","root");  

        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from Employee");  
        while(rs.next())  
        System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
        con.close();
    }

    catch(Exception e)
    {
        System.out.println(e);
    }

        }  

}

Connection pooling options with JDBC: DBCP vs C3P0

Here are some articles that show that DBCP has significantly higher performance than C3P0 or Proxool. Also in my own experience c3p0 does have some nice features, like prepared statement pooling and is more configurable than DBCP, but DBCP is plainly faster in any environment I have used it in.

Difference between dbcp and c3p0? Absolutely nothing! (A Sakai developers blog) http://blogs.nyu.edu/blogs/nrm216/sakaidelic/2007/12/difference_between_dbcp_and_c3.html

See also the like to the JavaTech article "Connection Pool Showdown" in the comments on the blog post.

How to create CSV Excel file C#?

I added ExportToStream so the csv didn't have to save to the hard drive first.

public Stream ExportToStream()
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(Export(true));
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How to capitalize the first character of each word in a string

This might be useful if you need to capitalize titles. It capitalizes each substring delimited by " ", except for specified strings such as "a" or "the". I haven't ran it yet because it's late, should be fine though. Uses Apache Commons StringUtils.join() at one point. You can substitute it with a simple loop if you wish.

private static String capitalize(String string) {
    if (string == null) return null;
    String[] wordArray = string.split(" "); // Split string to analyze word by word.
    int i = 0;
lowercase:
    for (String word : wordArray) {
        if (word != wordArray[0]) { // First word always in capital
            String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
            for (String word2 : lowercaseWords) {
                if (word.equals(word2)) {
                    wordArray[i] = word;
                    i++;
                    continue lowercase;
                }
            }
        }
        char[] characterArray = word.toCharArray();
        characterArray[0] = Character.toTitleCase(characterArray[0]);
        wordArray[i] = new String(characterArray);
        i++;
    }
    return StringUtils.join(wordArray, " "); // Re-join string
}

How do I use a custom Serializer with Jackson?

You can put @JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.

public class CustomDateSerializer extends SerializerBase<Date> {

    public CustomDateSerializer() {
        super(Date.class, true);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
        String format = formatter.format(value);
        jgen.writeString(format);
    }

}

Convert SQL Server result set into string

Assign a value when declaring the variable.

DECLARE @result VARCHAR(1000) ='';

SELECT @result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz

How to pop an alert message box using PHP?

This .php file content will generate valid html with alert (you can even remove <?php...?>)

<!DOCTYPE html><html><title>p</title><body onload="alert('<?php echo 'Hi' ?>')">

C++ Array Of Pointers

What you want is:

Foo *array[10]; // array of 10 Foo pointers

Not to be confused with:

Foo (*array)[10]; // pointer to array of 10 Foos

In either case, nothing will be automatically initialized because these represent pointers to Foos that have yet to be assigned to something (e.g. with new).

I finally "got" pointer/array declaration syntax in C when I realized that it describes how you access the base type. Foo *array[5][10]; means that *array[0..4][0..9] (subscript on an array of 5 items, then subscript on an array of 10 items, then dereference as a pointer) will access a Foo object (note that [] has higher precedence than *).

This seems backwards. You would think that int array[5][10]; (a.k.a. int (array[5])[10];) is an array of 10 int array[5]. Suppose this were the case. Then you would access the last element of the array by saying array[9][4]. Doesn't that look backwards too? Because a C array declaration is a pattern indicating how to get to the base type (rather than a composition of array expressions like one might expect), array declarations and code using arrays don't have to be flipflopped.

Is there a simple way to delete a list element by value?

Overwrite the list by indexing everything except the elements you wish to remove

>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]

More generally,

>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]

Calling JavaScript Function From CodeBehind

You can use literal:

this.Controls.Add(new LiteralControl("<script type='text/javascript'>myFunction();</script>"));

How to convert comma-separated String to List?

Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));

Or, using Guava:

List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));

Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

How do I install g++ on MacOS X?

Installing XCode requires:

  • Enrolling on the Apple website (not fun)
  • Downloading a 4.7G installer

To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:

https://github.com/kennethreitz/osx-gcc-installer

The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.

The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.

invalid_client in google oauth2

Set/change your product name, I had this issue until I created a product name as same as project name.

The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.

How to use Oracle's LISTAGG function with a unique filter?

create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');
commit;

select group_id, 
       (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
  select group_id, collect(distinct name) as coll_names 
    from demotable
    group by group_id 
)

GROUP_ID    NAMES
1   Alan,David,John
2   Charles,Julie

CSS "color" vs. "font-color"

I would think that one reason could be that the color is applied to things other than font. For example:

div {
    border: 1px solid;
    color: red;
}

Yields both a red font color and a red border.

Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

Call a Javascript function every 5 seconds continuously

Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();

How to create a zip file in Java

Look at this example:

StringBuilder sb = new StringBuilder();
sb.append("Test String");

File f = new File("d:\\test.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("mytext.txt");
out.putNextEntry(e);

byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();

out.close();

This will create a zip in the root of D: named test.zip which will contain one single file called mytext.txt. Of course you can add more zip entries and also specify a subdirectory like this:

ZipEntry e = new ZipEntry("folderName/mytext.txt");

You can find more information about compression with Java here.

How do I count a JavaScript object's attributes?

Use underscore library, very useful: _.keys(obj).length.

Using routes in Express-js

You could also organise them into modules. So it would be something like.

./
controllers
    index.js
    indexController.js
app.js

and then in the indexController.js of the controllers export your controllers.

//indexController.js
module.exports = function(){
//do some set up

var self = {
     indexAction : function (req,res){
       //do your thing
}
return self;
};

then in index.js of controllers dir

exports.indexController = require("./indexController");

and finally in app.js

var controllers = require("./controllers");

app.get("/",controllers.indexController().indexAction);

I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.

How to get single value from this multi-dimensional PHP array

The first element of $myarray is the array of values you want. So, right now,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

$myarray = $myarray[0];

Now, $myarray['email'] etc. will output as expected.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

A simple version that will work for the format mentioned, but not all the others as per @Espos:

(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) 

List directory tree structure in python?

import os

def fs_tree_to_dict(path_):
    file_token = ''
    for root, dirs, files in os.walk(path_):
        tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs}
        tree.update({f: file_token for f in files})
        return tree  # note we discontinue iteration trough os.walk

If anybody is interested - that recursive function returns nested structure of dictionaries. Keys are file system names (of directories and files), values are either:

  • sub dictionaries for directories
  • strings for files (see file_token)

The strings designating files are empty in this example. They can also be e.g. given file contents or its owner info or privileges or whatever object different than a dict. Unless it's a dictionary it can be easily distinguished from a "directory type" in further operations.

Having such a tree in a filesystem:

# bash:
$ tree /tmp/ex
/tmp/ex
+-- d_a
¦   +-- d_a_a
¦   +-- d_a_b
¦   ¦   +-- f1.txt
¦   +-- d_a_c
¦   +-- fa.txt
+-- d_b
¦   +-- fb1.txt
¦   +-- fb2.txt
+-- d_c

The result will be:

# python 2 or 3:
>>> fs_tree_to_dict("/tmp/ex")
{
    'd_a': {
        'd_a_a': {},
        'd_a_b': {
            'f1.txt': ''
        },
        'd_a_c': {},
        'fa.txt': ''
    },
    'd_b': {
        'fb1.txt': '',
        'fb2.txt': ''
    },
    'd_c': {}
}

If you like that, I've already created a package (python 2 & 3) with this stuff (and a nice pyfakefs helper): https://pypi.org/project/fsforge/

Alter MySQL table to add comments on columns

try:

 ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'  

The import org.apache.commons cannot be resolved in eclipse juno

Look for "poi-3.17.jar"!!!

  1. Download from "https://poi.apache.org/download.html".
  2. Click the one Binary Distribution -> poi-bin-3.17-20170915.tar.gz
  3. Unzip the file download and look for this "poi-3.17.jar".

Problem solved and errors disappeared.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

A bit off topic for this post, but searching for this error message brought me here.

If you are building through team system and getting this error, the build definition process tab has a "MSBuild Platform" setting. If this is set to "Auto", you may experience this problem. Changing it to "X86" can also resolve the error.

How do I copy an object in Java?

Yes. You need to Deep Copy your object.

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

How do you reinstall an app's dependencies using npm?

Follow this step to re install node modules and update them

works even if node_modules folder does not exist. now execute the following command synchronously. you can also use "npm update" but I think this'd preferred way

npm outdated // not necessary to run this command, but this will show outdated dependencies

npm install -g npm-check-updates // to install the "ncu" package

ncu -u --packageFile=package.json // to update dependencies version in package.json...don't run this command if you don't need to update the version

npm install: will install dependencies in your package.json file.

if you're okay with the version of your dependencies in your package.json file, no need to follow those steps just run

 npm install

Change remote repository credentials (authentication) on Intellij IDEA 14

Linux users (tested on ubuntu 14.04)

by default (on linux and mac) pycharm uses the OS's password manager. To access the passwords on ubuntu open the program "Passwords and Keys".

icon for password manager

Once open filter on "idea" and edit the relevant passwords.

pict of password editor dialog box

No need to restart pycharm for me.
Using pycharm 17.2

How can I sharpen an image in OpenCV?

One general procedure is laid out in the Wikipedia article on unsharp masking:

You use a Gaussian smoothing filter and subtract the smoothed version from the original image (in a weighted way so the values of a constant area remain constant).

To get a sharpened version of frame into image: (both cv::Mat)

cv::GaussianBlur(frame, image, cv::Size(0, 0), 3);
cv::addWeighted(frame, 1.5, image, -0.5, 0, image);

The parameters there are something you need to adjust for yourself.

There's also Laplacian sharpening, you should find something on that when you google.

MySQL - Replace Character in Columns

If you have "something" and need 'something', use replace(col, "\"", "\'") and viceversa.

Disabled UIButton not faded or grey

Swift 4+

extension UIButton {
    override open var isEnabled: Bool {
        didSet {
            DispatchQueue.main.async {
                if self.isEnabled {
                    self.alpha = 1.0
                }
                else {
                    self.alpha = 0.6
                }
            }
        }
    }
}

How to use

myButton.isEnabled = false

HTTP POST Returns Error: 417 "Expectation Failed."

If you are using "HttpClient", and you don't want to use global configuration to affect all you program you can use:

 HttpClientHandler httpClientHandler = new HttpClientHandler();
 httpClient.DefaultRequestHeaders.ExpectContinue = false;

I you are using "WebClient" I think you can try to remove this header by calling:

 var client = new WebClient();
 client.Headers.Remove(HttpRequestHeader.Expect);

Null or empty check for a string variable

declare @sexo as char(1)

select @sexo='F'

select * from pessoa

where isnull(Sexo,0) =isnull(@Sexo,0)

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

Difference between ApiController and Controller in ASP.NET MVC

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}

Running bash script from within python

Making sleep.sh executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "sleep.sh" to "./sleep.sh".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

Can HTML be embedded inside PHP "if" statement?

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).

Better is to use heredoc syntax. It is the same concept as in other languages (like bash).

 <?php
 if ($condition) {
   echo <<< END_OF_TEXT
     <b>lots of html</b> <i>$variable</i>
     lots of text...
 many lines possible, with any indentation, until the closing delimiter...
 END_OF_TEXT;
 }
 ?>

END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.

Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).

Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

Can I use git diff on untracked files?

Not 100% to the point, but if for some reason you don't want to add your files to the index as suggested by the accepted answer, here is another option:

If the files are untracked, obviously the diff is the whole file, so you can just view them with less:

less $(git ls-files --others --exclude-standard)

Navigate between them with :n and :p for next and previous..

Update from the comments: If you need a patch format you can also combine it with git diff:

git ls-files --others --exclude-standard | xargs -n 1 git --no-pager diff /dev/null | less

You can also redirect the output to a file or use an other diff command in this case.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

It could be that the gradle-2.1 distribution specified by the wrapper was not downloaded properly. This was the root cause of the same problem in my environment.

Look into this directory:

ls -l ~/.gradle/wrapper/dists/

In there you should find a gradle-2.1 folder. Delete it like so:

rm -rf ~/.gradle/wrapper/dists/gradle-2.1-bin/

Restart IntelliJ, after that it will restart the download from the beginning and hopefully work.

Thanks, Ioannis

List all tables in postgresql information_schema

For private schema 'xxx' in postgresql :

SELECT table_name FROM information_schema.tables 
 WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'

Without table_type = 'BASE TABLE' , you will list tables and views

How to get the return value from a thread in python?

FWIW, the multiprocessing module has a nice interface for this using the Pool class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool class as a drop-in replacement.

def foo(bar, baz):
  print 'hello {0}'.format(bar)
  return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo

# do some other stuff in the main process

return_val = async_result.get()  # get the return value from your function.

How does strcmp() work?

It uses the byte values of the characters, returning a negative value if the first string appears before the second (ordered by byte values), zero if they are equal, and a positive value if the first appears after the second. Since it operates on bytes, it is not encoding-aware.

For example:

strcmp("abc", "def") < 0
strcmp("abc", "abcd") < 0 // null character is less than 'd'
strcmp("abc", "ABC") > 0 // 'a' > 'A' in ASCII
strcmp("abc", "abc") == 0

More precisely, as described in the strcmp Open Group specification:

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.

Note that the return value may not be equal to this difference, but it will carry the same sign.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

There are four abstract function types, you can use them separately when you know your function will take an argument(s) or not, will return a data or not.

export declare type fEmptyVoid = () => void;
export declare type fEmptyReturn = () => any;
export declare type fArgVoid = (...args: any[]) => void;
export declare type fArgReturn = (...args: any[]) => any;

like this:

public isValid: fEmptyReturn = (): boolean => true;
public setStatus: fArgVoid = (status: boolean): void => this.status = status;

For use only one type as any function type we can combine all abstract types together, like this:

export declare type fFunction = fEmptyVoid | fEmptyReturn | fArgVoid | fArgReturn;

then use it like:

public isValid: fFunction = (): boolean => true;
public setStatus: fFunction = (status: boolean): void => this.status = status;

In the example above everything is correct. But the usage example in bellow is not correct from the point of view of most code editors.

// you can call this function with any type of function as argument
public callArgument(callback: fFunction) {

    // but you will get editor error if call callback argument like this
    callback();
}

Correct call for editors is like this:

public callArgument(callback: fFunction) {

    // pay attention in this part, for fix editor(s) error
    (callback as fFunction)();
}

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

How to get Django and ReactJS to work together?

The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.

This tutorial well explains this. In particular:

I see the following patterns (which are common to almost every web framework):

-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)

-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)

-Mix and match: mini React apps inside Django templates (difficulty: simple)

possible EventEmitter memory leak detected

This is explained in the node eventEmitter documentation

What version of Node is this? What other code do you have? That isn't normal behavior.

In short, its: process.setMaxListeners(0);

Also see: node.js - request - How to “emitter.setMaxListeners()”?

Matrix multiplication using arrays

Try this,

public static Double[][] multiplicar(Double A[][],Double B[][]){
    Double[][] C= new Double[2][2];
    int i,j,k;
     for (i = 0; i < 2; i++) {
         for (j = 0; j < 2; j++) {
             C[i][j] = 0.00000;
         }
     }
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            for (k=0;k<2;k++){
                  C[i][j]+=(A[i][k]*B[k][j]);

            }

        }
    }
    return C;
}

Bootstrap onClick button event

If, like me, you had dynamically created buttons on your page, the

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow here and here.

How do you launch the JavaScript debugger in Google Chrome?

Windows: CTRL-SHIFT-J OR F12

Mac: ?-?-J

Also available through the wrench menu (Tools > JavaScript Console):

JavaScript Console Menu

How to measure elapsed time in Python?

In addition to %timeit in ipython you can also use %%timeit for multi-line code snippets:

In [1]: %%timeit
   ...: complex_func()
   ...: 2 + 2 == 5
   ...:
   ...:

1 s ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Also it can be used in jupyter notebook the same way, just put magic %%timeit at the beginning of cell.

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

Converting double to string

double priceG = Double.parseDouble(priceGal.getText().toString());
double valG = Double.parseDouble(volGal.toString());

One of those is throwing the exception. You need to add some logging/printing to see what's in volGal and priceGal - it's not what you think.

Call angularjs function using jquery/javascript

You can use following:

angular.element(domElement).scope() to get the current scope for the element

angular.element(domElement).injector() to get the current app injector

angular.element(domElement).controller() to get a hold of the ng-controller instance.

Hope that might help

applying css to specific li class

You are defining the color: #C1C1C1; for all the a elements with #sub-nav-container a.

Doing it again in li.sub-navigation-home-news won't do anything, as it is a parent of the a element.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Keras, how do I predict after I trained a model?

You must use the same Tokenizer you used to build your model!

Else this will give different vector to each word.

Then, I am using:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

ActiveRecord OR query

If you want to use arrays as arguments, the following code works in Rails 4:

query = Order.where(uuid: uuids, id: ids)
Order.where(query.where_values.map(&:to_sql).join(" OR "))
#=> Order Load (0.7ms)  SELECT "orders".* FROM "orders" WHERE ("orders"."uuid" IN ('5459eed8350e1b472bfee48375034103', '21313213jkads', '43ujrefdk2384us') OR "orders"."id" IN (2, 3, 4))

More information: OR queries with arrays as arguments in Rails 4.

How to dynamic filter options of <select > with jQuery?

Example HTML:

_x000D_
_x000D_
//jQuery extension method:_x000D_
jQuery.fn.filterByText = function(textbox) {_x000D_
  return this.each(function() {_x000D_
    var select = this;_x000D_
    var options = [];_x000D_
    $(select).find('option').each(function() {_x000D_
      options.push({_x000D_
        value: $(this).val(),_x000D_
        text: $(this).text()_x000D_
      });_x000D_
    });_x000D_
    $(select).data('options', options);_x000D_
_x000D_
    $(textbox).bind('change keyup', function() {_x000D_
      var options = $(select).empty().data('options');_x000D_
      var search = $.trim($(this).val());_x000D_
      var regex = new RegExp(search, "gi");_x000D_
_x000D_
      $.each(options, function(i) {_x000D_
        var option = options[i];_x000D_
        if (option.text.match(regex) !== null) {_x000D_
          $(select).append(_x000D_
            $('<option>').text(option.text).val(option.value)_x000D_
          );_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
};_x000D_
_x000D_
// You could use it like this:_x000D_
_x000D_
$(function() {_x000D_
  $('select').filterByText($('input'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
  <option value="hello">hello</option>_x000D_
  <option value="world">world</option>_x000D_
  <option value="lorem">lorem</option>_x000D_
  <option value="ipsum">ipsum</option>_x000D_
  <option value="lorem ipsum">lorem ipsum</option>_x000D_
</select>_x000D_
<input type="text">
_x000D_
_x000D_
_x000D_

Live demo here: http://www.lessanvaezi.com/filter-select-list-options/

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

Convert nullable bool? to bool

You can use Nullable{T} GetValueOrDefault() method. This will return false if null.

 bool? nullableBool = null;

 bool actualBool = nullableBool.GetValueOrDefault();

Conda command not found

To initialize your shell run the below code

source ~/anaconda3/etc/profile.d/conda.sh
conda activate Your_env

It's Worked for me, I got the solution from the below link
https://www.codegrepper.com/code-[“CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.][1]examples/shell/CommandNotFoundError%3A+Your+shell+has+not+been+properly+configured+to+use+%27conda+activate%27.+To+initialize+your+shell%2C+run

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to reset form body in bootstrap modal box?

This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:

var stylesString = $('#DefaultModal .modal-body').html();

Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).

$("#btnStyles").click(function () {
    //pass the data in the modal body adding html elements
    $('#DefaultModal .modal-body').html(stylesString);
 $('#DefaultModal').modal('show');
})

If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.

Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:

<div class="modal-body" id="modalbody">


    <div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>

How to export settings?

Often there are questions about the java settings in vsCode. This is a big question and can involve advanced user knowledge to accmplish. But there is simple way to get the existing java settings from vsCode and copy these setting for use on another PC. This post is using recent versions of vsCode and JDK in mid-December 2020.

There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.

First things first, open vsCode and either open an existing java folder-file or create a new java file in vsCode. Then look at the lower right corner of vsCode (on the blue command bar). The vsCode should be displaying an icon showing the version of the Java Standard Edition ( Java SE ) being used. The version being on this PC today is JavaSE-15. (link 1)

Click on that icon (JAVASE-15) which then opens a new window named "java.configuration.runtimes". There should be two tabs below this name: User and Workspace. Below these tabs is a link named, "Edit in settings.json". Click on that link. (link 2)

Two json files should then open: Default settings and settings.json. This post only focuses on the "settings.json" file. The settings.json file shows various settings used for coding different programming languages (Python, R, and java). Near the bottom of the settings.json file shows the settings this User uses in vsCode for programming java.

These java settings are the settings that can be "backed up" - meaning these settings get copied and pasted to another PC for creating a java programming environment similar to the java programming environment on this PC. (link 3)

link 1

link 2

link 3

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done

HTTP URL Address Encoding in Java

The java.net.URI class can help; in the documentation of URL you find

Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI

Use one of the constructors with more than one argument, like:

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/first book.pdf",
    null);
URL url = uri.toURL();
//or String request = uri.toString();

(the single-argument constructor of URI does NOT escape illegal characters)


Only illegal characters get escaped by above code - it does NOT escape non-ASCII characters (see fatih's comment).
The toASCIIString method can be used to get a String only with US-ASCII characters:

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/é",
    null);
String request = uri.toASCIIString();

For an URL with a query like http://www.google.com/ig/api?weather=São Paulo, use the 5-parameter version of the constructor:

URI uri = new URI(
        "http", 
        "www.google.com", 
        "/ig/api",
        "weather=São Paulo",
        null);
String request = uri.toASCIIString();

python capitalize first letter only

This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that

What are these ^M's that keep showing up in my files in emacs?

^M is 0x0d, i.e. the carriage return character. If your display looks like

line 1^M
line 2^M

then the file must have come from Windows because the standard newline sequence on Windows is CR LF (0x0d 0x0a) whereas the standard newline sequence consists solely of LF on Unices.

If the file had come from a Mac OS 9 or earlier system, you would see it as

line 1^Mline 2^M

because there would be no line feeds following the carriage returns.

Add days to JavaScript Date

I created these extensions last night:
you can pass either positive or negative values;

example:

var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);


Date.prototype.addDays = function (num) {
    var value = this.valueOf();
    value += 86400000 * num;
    return new Date(value);
}

Date.prototype.addSeconds = function (num) {
    var value = this.valueOf();
    value += 1000 * num;
    return new Date(value);
}

Date.prototype.addMinutes = function (num) {
    var value = this.valueOf();
    value += 60000 * num;
    return new Date(value);
}

Date.prototype.addHours = function (num) {
    var value = this.valueOf();
    value += 3600000 * num;
    return new Date(value);
}

Date.prototype.addMonths = function (num) {
    var value = new Date(this.valueOf());

    var mo = this.getMonth();
    var yr = this.getYear();

    mo = (mo + num) % 12;
    if (0 > mo) {
        yr += (this.getMonth() + num - mo - 12) / 12;
        mo += 12;
    }
    else
        yr += ((this.getMonth() + num - mo) / 12);

    value.setMonth(mo);
    value.setYear(yr);
    return value;
}

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Java: random long number in 0 <= x < n range

From the page on Random:

The method nextLong is implemented by class Random as if by:

public long nextLong() {
   return ((long)next(32) << 32) + next(32);
}

Because class Random uses a seed with only 48 bits, this algorithm will not return all possible long values.

So if you want to get a Long, you're already not going to get the full 64 bit range.

I would suggest that if you have a range that falls near a power of 2, you build up the Long as in that snippet, like this:

next(32) + ((long)nextInt(8) << 3)

to get a 35 bit range, for example.

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Swift UIView background color opacity

You can set background color of view to the UIColor with alpha, and not affect view.alpha:

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

or

view.backgroundColor = UIColor.red.withAlphaComponent(0.5)

Python basics printing 1 to 100

The first line defines the variable. The second line loops it to 100, the third adds 1 to a and the 4th divides a by 3 and if there is no remainder (0) it will print that number otherwise it will print a blank line.

 a = (0)

for i in range(0,100):
     a = a + 1
if a % 3 == 0:
    print(a)
else:
    print("")

Mysql service is missing

I have done it by the following way

  1. Start cmd
  2. Go to the "C:\Program Files\MySQL\MySQL Server 5.6\bin"
  3. type mysqld --install

Like the following image. See for more information.

enter image description here

Disable color change of anchor tag when visited

a {
    color: orange !important;
}

!important has the effect that the property in question cannot be overridden unless another !important is used. It is generally considered bad practice to use !important unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited using CSS only.

In php, is 0 treated as empty?

Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:

$myVar = '';
if (empty($myVar))
{
  echo "Its empty";
}
echo "<br/>";

if ($myVar===0)
{
  echo "also zero!";
}

just for notice $myVar==0 act like empty function.

How to pass value from <option><select> to form action

you can simply use your own code but add name for the select tag

<form method="POST" action="index.php?action=contact_agent&agent_id=">
    <select name="agent_id">
        <option value="1">Agent Homer</option>
        <option value="2">Agent Lenny</option>
        <option value="3">Agent Carl</option>
    </select>

then you can access it like this

String agent=request.getparameter("agent_id");

Session 'app': Error Installing APK

You have to enable Developer options and enable USB Debugging:

  1. Go to the settings menu, and scroll down to "About phone." Tap it.
  2. Scroll down to the bottom again, where you see "Build number." (Your build number may vary from ours here.)
  3. Tap it seven (7) times. After the third tap, you'll see a playful dialog that says you're four taps away from being a developer. (If only it were that simple, eh?) Keep on tapping, and poof, you've got the developer settings back.

http://www.androidcentral.com/how-enable-developer-settings-android-42

Inside Developer Options, enable USB Debugging

enter image description here

Stack array using pop() and push()

Because you initialized the top variable to -1 in your constructor, you need to increment the top variable in your push() method before you access the array. Note that I've changed the assignment to use ++top:

public void push(int i) 
{
    if (top == stack.length)
    {
        extendStack();
    }

    stack[++top]= i;
}

That will fix the ArrayIndexOutOfBoundsException you posted about. I can see other issues in your code, but since this is a homework assignment I'll leave those as "an exercise for the reader." :)

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

angular2 submit form by pressing enter without submit button

Maybe you add keypress or keydown to the input fields and assign the event to function that will do the submit when enter is clicked.

Your template would look like this

    <form (keydown)="keyDownFunction($event)">
      <input type="text" />
    </form

And you function inside the your class would look like this

    keyDownFunction(event) {
      if (event.keyCode === 13) {
        alert('you just pressed the enter key');
        // rest of your code
      }
    }

Business logic in MVC

As a couple of answers have pointed out, I believe there is some some misunderstanding of multi tier vs MVC architecture.

Multi tier architecture involves breaking your application into tiers/layers (e.g. presentation, business logic, data access)

MVC is an architectural style for the presentation layer of an application. For non trivial applications, business logic/business rules/data access should not be placed directly into Models, Views, or Controllers. To do so would be placing business logic in your presentation layer and thus reducing reuse and maintainability of your code.

The model is a very reasonable choice choice to place business logic, but a better/more maintainable approach is to separate your presentation layer from your business logic layer and create a business logic layer and simply call the business logic layer from your models when needed. The business logic layer will in turn call into the data access layer.

I would like to point out that it is not uncommon to find code that mixes business logic and data access in one of the MVC components, especially if the application was not architected using multiple tiers. However, in most enterprise applications, you will commonly find multi tier architectures with an MVC architecture in place within the presentation layer.

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

You simply need to install Crystal Report Report Run Time downloads on Deployment Server. If problem still appears, then place check asp_client folder in your project main folder.

Is mongodb running?

You can use the below command, to check MongoDB status, e.g: sudo service MongoDB status which displays the status of MongoDB service as like the screenshot:

MongoDB status

How to copy a huge table data into another table in SQL Server

If your focus is Archiving (DW) and are dealing with VLDB with 100+ partitioned tables and you want to isolate most of these resource intensive work on a non production server (OLTP) here is a suggestion (OLTP -> DW) 1) Use backup / Restore to get the data onto the archive server (so now, on Archive or DW you will have Stage and Target database) 2) Stage database: Use partition switch to move data to corresponding stage table
3) Use SSIS to transfer data from staged database to target database for each staged table on both sides 4) Target database: Use partition switch on target database to move data from stage to base table Hope this helps.

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

var ttt = "aa ///\\\\\\";

Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

because you had to show a message to user that user can't give a name which has (\) character.

I think the scenario is like:

var user_input_name = document.getElementById('the_name').value;

Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

If you want to simulate, you code must be valid at first place.

var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.

alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?

Now, you only need to do is

var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
  alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
  do_something_else();
  }

Edit: I used [] to quote text to be shown, so it would be less confused than using "".

YouTube embedded video: set different thumbnail

Just copy and paste the code in HTML file. and enjoy the happy coding. Using Youtube api to manage the thumbnail of youtube embedded video.

<!DOCTYPE html>
<html>
<body>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: 'M7lc1UVf-VE',
                events: {
                    'onReady': onPlayerReady,
                }
            });
        }

        function onPlayerReady(event) {
            $('#play_vid').click(function() {
                event.target.playVideo();
            });
        }

        $(document).ready(function() {
            $('#player').hide();
            $('#play_vid').click(function() {
                $('#player').show();
                $('#play_vid').hide();
            });
        });
    </script>

    <div id="player"></div>
    <img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>

How to access a value defined in the application.properties file in Spring Boot

I had this problem too. But there is very simple solution. Just declare your variable in constructor.

My example:

application.propperties:

#Session
session.timeout=15

SessionServiceImpl class:

private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;

@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
                          SessionRepository sessionRepository) {
    this.SESSION_TIMEOUT = sessionTimeout;
    this.sessionRepository = sessionRepository;
}

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Beyond the problematic use of async as pointed out by @Servy, the other issue is that you need to explicitly get T from Task<T> by calling Task.Result. Note that the Result property will block async code, and should be used carefully.

Try:

private async void button1_Click(object sender, EventArgs e)
{
    var s = await methodAsync();
    MessageBox.Show(s.Result);
}

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Importing CSV data using PHP/MySQL

Database Connection:

 try {
        $conn = mysqli_connect($servername, $username, $password, $db);
        //echo "Connected successfully"; 
    } catch (exception $e) {
        echo "Connection failed: " . $e->getMessage();
    }

Code to read CSV file and upload to table in database.

   $file = fopen($filename, "r");
            while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
                $sql = "INSERT into db_table 
                   values ('','" . $getData[1] . "','" . $getData[2] . "','" . $getData[3] . "','" . $getData[4] . "','" . $getData[5] . "','" . $getData[6] . "')";
                $result = mysqli_query($conn, $sql);
                if (!isset($result)) {
                    echo "<script type=\"text/javascript\">
                            alert(\"Invalid File:Please Upload CSV File. 
                            window.location = \"home.do\"
                          </script>";
                } else {
                    echo "<script type=\"text/javascript\">
                        alert(\"CSV File has been successfully Imported.\");
                        window.location = \"home.do\"
                    </script>";
                }
            }
            fclose($file);

Determine if Python is running inside virtualenv

You can do which python and see if its pointing to the one in virtual env.

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

Capturing image from webcam in java?

This JavaCV implementation works fine.

Code:

import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;

import java.io.File;

import static org.bytedeco.opencv.global.opencv_core.cvFlip;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;

public class Test implements Runnable {
    final int INTERVAL = 100;///you may use interval
    CanvasFrame canvas = new CanvasFrame("Web Cam");

    public Test() {
        canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
    }

    public void run() {

        new File("images").mkdir();

        FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera
        OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
        IplImage img;
        int i = 0;
        try {
            grabber.start();

            while (true) {
                Frame frame = grabber.grab();

                img = converter.convert(frame);

                //the grabbed frame will be flipped, re-flip to make it right
                cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise

                //save
                cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);

                canvas.showImage(converter.convert(img));

                Thread.sleep(INTERVAL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Test gs = new Test();
        Thread th = new Thread(gs);
        th.start();
    }
}

There is also post on configuration for JavaCV

You can modify the codes and be able to save the images in regular interval and do rest of the processing you want.

return query based on date

If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...

First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)

db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt

Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime() returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date() constructor.

db.things.find({
        createdAt: {
            $gte: new Date(new Date().getTime()-60*5*1000).toISOString()
         }
     })
     .count()

Explanation for new Date(new Date().getTime()-60*5*1000).toISOString() is as follows:

First we calculate "5 minutes ago":

  1. new Date().getTime() gives us current time in milliseconds
  2. We want to subtract 5 minutes (in ms) from that: 5*60*1000 -- I just multiply by 60 seconds so its easy to change. I can just change 5 to 120 if I want 2 hours (120 minutes).
  3. new Date().getTime()-60*5*1000 gives us 1484383878676 (5 minutes ago in ms)

Now we need to feed that into a new Date() constructor to get the ISO string format required by MongoDB timestamps.

  1. { $gte: new Date(resultFromAbove).toISOString() } (mongodb .find() query)
  2. Since we can't have variables we do it all in one shot: new Date(new Date().getTime()-60*5*1000)
  3. ...then convert to ISO string: .toISOString()
  4. new Date(new Date().getTime()-60*5*1000).toISOString() gives us 2017-01-14T08:53:17.586Z

Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.

What are the differences between ArrayList and Vector?

Differences

  • Vectors are synchronized, ArrayLists are not.
  • Data Growth Methods

Use ArrayLists if there is no specific requirement to use Vectors.

Synchronization

If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.

Collections.synchronizedList is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.

Reference

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Reference

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

Getting the name of a variable as a string

Whenever I have to do it, mostly while communicating json schema and constants with the frontend I define a class as follows

class Param:
    def __init__(self, name, value):
        self.name = name
        self.value = value

Then define the variable with name and value.

frame_folder_count = Param({'name':'frame_folder_count', 'value':10})

Now you can access the name and value using the object.

>>> frame_folder_count.name
'frame_folder_count'

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

PostgreSQL - query from bash script as database user 'postgres'

Once you're logged in as postgres, you should be able to write:

psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'

to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:

testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"

To handle the logging in as postgres, I recommend using sudo. You can give a specific user the permission to run

sudo -u postgres /path/to/this/script.sh

so that they can run just the one script as postgres.

Mysql Compare two datetime fields

You can use the following SQL to compare both date and time -

Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');

Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-

enter image description here

It should work perfect.

Global keyboard capture in C# application

Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

How can I detect window size with jQuery?

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
<script>
    var WindowsSize=function(){
        var h=$(window).height(),
            w=$(window).width();
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
    };
   $(document).ready(WindowsSize); 
   $(window).resize(WindowsSize); 
</script>

Here is a snippet:

_x000D_
_x000D_
var WindowsSize=function(){_x000D_
     var h=$(window).height(),_x000D_
      w=$(window).width();_x000D_
     $("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
 };_x000D_
 $(document).ready(WindowsSize); _x000D_
 $(window).resize(WindowsSize); 
_x000D_
#winSize{_x000D_
  position:fixed;_x000D_
  bottom:1%;_x000D_
  right:1%;_x000D_
  border:rgba(0,0,0,0.8) 3px solid;_x000D_
  background:rgba(0,0,0,0.6);_x000D_
  padding:5px 10px;_x000D_
  color:#fff;_x000D_
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
  z-index:9999_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="winSize"></div>
_x000D_
_x000D_
_x000D_

Of course, adapt it to fit your needs! ;)

What is __stdcall?

It has to do with how the function is called- basically the order in which things are put on the the stack and who is responsible for cleanup.

Here's the documentation, but it doesn't mean much unless you understand the first part:
http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx

How to use JavaScript with Selenium WebDriver Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

Java String new line

Try:

System.out.println("I\nam\na\nboy");

How to check if a file exists in the Documents directory in Swift?

It's pretty user friendly. Just work with NSFileManager's defaultManager singleton and then use the fileExistsAtPath() method, which simply takes a string as an argument, and returns a Bool, allowing it to be placed directly in the if statement.

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory = paths[0] as! String
let myFilePath = documentDirectory.stringByAppendingPathComponent("nameOfMyFile")

let manager = NSFileManager.defaultManager()
if (manager.fileExistsAtPath(myFilePath)) {
    // it's here!!
}

Note that the downcast to String isn't necessary in Swift 2.

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

jquery loop on Json data using $.each

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});

$.each(data, function(i, item) {
    alert(item.PageName);
});

these two options work well, unless you have something like:

var data.result = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data.result, function(i, item) {
    alert(data.result[i].PageName);
});

EDIT:

try with this and describes what the result

$.get('/Cms/GetPages/123', function(data) {
  alert(data);
});

FOR EDIT 3:

this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.

$.get('/Cms/GetPages/123', function(data) {
  $.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
   alert(item.PageName);
  });
});

How to add icons to React Native app

I wrote a generator to automatically generate icons for your react native app from a single icon file. It generates your assets and it also adds them correctly to your ios and android project:

Update (04/09/2019)

We revamped our generator to be up to date with the ecosystem standards. You can now use @bam.tech/react-native-make.

You can install it using: yarn add @bam.tech/react-native-make in the react-native project

To use it react-native set-icon --path <path_to_png> --background <icon_background_color> --platform <android|ios>

And... that's it! Hope it can be useful for others :)

Recommendations:

Here are some improvements over the previous tool:

  • No Yeoman dependency, it is now a react-native-cli plugin
  • No Image Magick dependency
  • Creates Adaptive icons for Android
  • Adds missing icons sizes for iOS

How to close activity and go back to previous activity in android

This closes the entire application:

this.finish();

C: scanf to array

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}

C++ template constructor

There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:

Foo<int> f = Foo<int>();

The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the constructor template's argument list to go.

Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.

Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

how to kill hadoop jobs

Depending on the version, do:

version <2.3.0

Kill a hadoop job:

hadoop job -kill $jobId

You can get a list of all jobId's doing:

hadoop job -list

version >=2.3.0

Kill a hadoop job:

yarn application -kill $ApplicationId

You can get a list of all ApplicationId's doing:

yarn application -list

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

Replacing a fragment with another fragment inside activity group

You Can Use This code

((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();

or You Can This Use Code

YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);

        if (fragments==null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
        }

RichTextBox (WPF) does not have string property "Text"

string GetString(RichTextBox rtb)
{
    var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
    return textRange.Text;
}

Checking if form has been submitted - PHP

if ($_SERVER['REQUEST_METHOD'] == 'POST').

How to jump back to NERDTree from file in tab?

The top answers here mention using T to open a file in a new tab silently, or Ctrl+WW to hop back to nerd-tree window after file is opened normally.

IF WORKING WITH BUFFERS: use go to open a file in a new buffer, silently, meaning your focus will remain on nerd-tree.

Use this to open multiple files fast :)

How to write a confusion matrix in Python?

You should map from classes to a row in your confusion matrix.

Here the mapping is trivial:

def row_of_class(classe):
    return {1: 0, 2: 1}[classe]

In your loop, compute expected_row, correct_row, and increment conf_arr[expected_row][correct_row]. You'll even have less code than what you started with.

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

Calculate median in c#

Is there a function in the .net Math library?

No.

It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.

How to import module when module name has a '-' dash or hyphen in it?

Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path

For example if your structure is like this:

foo-bar
+-- barfoo.py
+-- __init__.py

import sys
sys.path.append('foo-bar')

import barfoo

How to re-render flatlist?

I solved this problem by adding extraData={this.state} Please check code below for more detail

render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.arr}
          extraData={this.state}
          renderItem={({ item }) => <Text style={styles.item}>{item}</Text>}
        />
      </View>
    );
  }

Recommendation for compressing JPG files with ImageMagick

I use always:

  • quality in 85
  • progressive (comprobed compression)
  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
  • Strip any comment or EXIF metadata

in imagemagick should be

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

or in the newer version:

magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg

Source.

From @Fordi in the comments (Don't forget to upvote him if you like this): If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

Composer Warning: openssl extension is missing. How to enable in WAMP

C:\laravel-master>composer create-project laravel/laravel Installing laravel/laravel (v4.0.6) - Installing laravel/laravel (v4.0.6) [RuntimeException] You must enable the openssl extension to download files via https

I'm using EasyPhp (WAMP type). In the EasyPHP Icon in the taskbar, right click and select configuration then select PHP. I will open the PHP.ini file configuration in a Notepad, search-find or CTRL+F in notepad for the word OPENSSL you will find this ;extension=php_openssl.dll just remove the ; and the extension=php_openssl.dll is active.

C:\laravel-master>composer create-project laravel/laravel Installing laravel/laravel (v4.0.6) - Installing laravel/laravel (v4.0.6) Downloading: 100% Created project in C:\laravel-master\laravel Loading composer repositories with package information Installing dependencies (including require-dev)

What is the best way to check for Internet connectivity using .NET?

public static bool Isconnected = false;

public static bool CheckForInternetConnection()
{
    try
    {
        Ping myPing = new Ping();
        String host = "google.com";
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions pingOptions = new PingOptions();
        PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
        if (reply.Status == IPStatus.Success)
        {
            return true;
        }
        else if (reply.Status == IPStatus.TimedOut)
        {
            return Isconnected;
        }
        else
        {
            return false;
        }
    }
    catch (Exception)
    {
        return false;
    }
}

public static void CheckConnection()
{
    if (CheckForInternetConnection())
    {
        Isconnected = true;
    }
    else
    {
        Isconnected = false;
    }
}

Where does SVN client store user authentication data?

I know I'm uprising a very old topic, but after a couple of hours struggling with this very problem and not finding a solution anywhere else, I think this is a good place to put an answer.

We have some Build Servers WindowsXP based and found this very problem: svn command line client is not caching auth credentials.

We finally found out that we are using Cygwin's svn client! not a "native" Windows. So... this client stores all the auth credentials in /home/<user>/.subversion/auth

This /home directory in Cygwin, in our installation is in c:\cygwin\home. AND: the problem was that the Windows user that is running svn did never ever "logged in" in Cygwin, and so there was no /home/<user> directory.

A simple "bash -ls" from a Windows command terminal created the directory, and after the first access to our SVN server with interactive prompting for access credentials, alás, they got cached.

So if you are using Cygwin's svn client, be sure to have a "home" directory created for the local Windows user.

Razor View throwing "The name 'model' does not exist in the current context"

In my case I was missing @ at the beginning of the foreach

    @foreach (var item in Model)
    {
        <tr class="clickable-row">
            <td class="clickable-field">
                @Html.DisplayFor(modelItem => item.Label)
            </td>
            <td class="clickable-field hidden-xs">
                @Html.DisplayFor(modelItem => item.Value)
            </td>
        </tr>
    }

PHP function to make slug (URL string)

Update

Since this answer is getting some attention, I'm adding some explanation.

The solution provided will essentially replace everything except A-Z, a-z, 0-9, & - (hyphen) with - (hyphen). So, it won't work properly with other unicode characters (which are valid characters for a URL slug/string). A common scenario is when the input string contains non-English characters.

Only use this solution if you're confident that the input string won't have unicode characters which you might want to be a part of output/slug.

Eg. "???? ?????" will become "----------" (all hyphens) instead of "????-?????" (valid URL slug).

Original Answer

How about...

$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));

?

How to read numbers separated by space using scanf

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

nvm keeps "forgetting" node in new terminal session

If you also have SDKMAN...

Somehow SDKMAN was conflicting with my NVM. If you're at your wits end with this and still can't figure it out, I just fixed it by ignoring the "THIS MUST BE AT THE END OF THE FILE..." from SDKMAN and putting the NVM lines after it.

#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="/Users/myname/.sdkman"
[[ -s "/Users/myname/.sdkman/bin/sdkman-init.sh" ]] && source "/Users/myname/.sdkman/bin/sdkman-init.sh"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

How do I calculate someone's age based on a DateTime type birthday?

An easy to understand and simple solution.

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.

Show and hide a View with a slide up/down animation

Easiest solution: set android:animateLayoutChanges="true" on the container holding your views.

To put it into some context: If you have a layout like below, all visibility changes to the views in this container will be animated automatically.

<LinearLayout android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    >

    <Views_which_change_visibility>

</LinearLayout>

You can find more details about this on Animating Layout Changes - Android Developer

Switch focus between editor and integrated terminal in Visual Studio Code

Actually, in VS Code 1.48.1, there is a toggleTerminal command; I don't know if it was available in previous versions ;) You can utilize it in the keybindings.json file.

This worked for me on Windows, and should also works on Linux.

{
    "key": "ctrl+alt+right",
    "command": "workbench.action.terminal.toggleTerminal",
    "when": "editorTextFocus || terminalFocus"
}

JSON.stringify doesn't work with normal Javascript array

JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.

The JSON array data type cannot have named keys on an array.

When you pass a JavaScript array to JSON.stringify the named properties will be ignored.

If you want named properties, use an Object, not an Array.

_x000D_
_x000D_
const test = {}; // Object_x000D_
test.a = 'test';_x000D_
test.b = []; // Array_x000D_
test.b.push('item');_x000D_
test.b.push('item2');_x000D_
test.b.push('item3');_x000D_
test.b.item4 = "A value"; // Ignored by JSON.stringify_x000D_
const json = JSON.stringify(test);_x000D_
console.log(json);
_x000D_
_x000D_
_x000D_

Windows batch script to move files

This is exactly how it worked for me. For some reason the above code failed.

This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y

:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup

WPF loading spinner

This repo on github seems to do the job quite well:

https://github.com/blackspikeltd/Xaml-Spinners-WPF

The spinners are all light weight and can easily be placed wherever needed. There is a sample project included in the repo that shows how to use them.

No nasty code-behinds with a bunch of logic either. If MVVM support is needed, one can just take these and throw them in a Grid with a Visibility binding.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to add empty spaces into MD markdown readme on GitHub?

Markdown gets converted into HTML/XHMTL.

John Gruber created the Markdown language in 2004 in collaboration with Aaron Swartz on the syntax, with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format, and optionally convert it to structurally valid HTML (or XHTML).

HTML is completely based on using &nbsp; for adding extra spaces if it doesn't externally define/use JavaScript or CSS for elements.

Markdown is a lightweight markup language with plain text formatting syntax. It is designed so that it can be converted to HTML and many other formats using a tool by the same name.


If you want to use »

  1. only one space » either use &nbsp; or just hit Spacebar (2nd one is good choice in this case)

  2. more than one space » use &nbsp;+space (for 2 consecutive spaces)


eg. If you want to add 10 spaces contiguously then you should use

&nbsp;   &nbsp;   &nbsp;   &nbsp;   &nbsp;  

&nbsp;space&nbsp;space&nbsp;space&nbsp;space&nbsp;space

instead of using 10 &nbsp; one after one as the below one

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;


For more details check

  1. Adding multiple spaces between text in Markdown,
  2. How to create extra space in HTML or web page.

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

Copy a file in a sane, safe and efficient way

With C++17 the standard way to copy a file will be including the <filesystem> header and using:

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to);

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,
                std::filesystem::copy_options options);

The first form is equivalent to the second one with copy_options::none used as options (see also copy_file).

The filesystem library was originally developed as boost.filesystem and finally merged to ISO C++ as of C++17.

Not Able To Debug App In Android Studio

Restart the adb server, from android studio: Tools -> "Troubleshhot Device Connection"

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

File upload from <input type="file">

If you have a complex form with multiple files and other inputs here is a solution that plays nice with ngModel.

It consists of a file input component that wraps a simple file input and implements the ControlValueAccessor interface to make it consumable by ngModel. The component exposes the FileList object to ngModel.

This solution is based on this article.

The component is used like this:

<file-input name="file" inputId="file" [(ngModel)]="user.photo"></file-input>
<label for="file"> Select file </label>

Here's the component code:

import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => FileInputComponent),
    multi: true
};

@Component({
  selector: 'file-input',
  templateUrl: './file-input.component.html',
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class FileInputComponent {

  @Input()
  public name:string;

  @Input()
  public inputId:string;

  private innerValue:any;

  constructor() { }

  get value(): FileList {
    return this.innerValue;
  };

  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: FileList) => void = noop;

  set value(v: FileList) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChangeCallback(v);
    }
  }

  onBlur() {
    this.onTouchedCallback();
  }

  writeValue(value: FileList) {
    if (value !== this.innerValue) {
      this.innerValue = value;
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  changeFile(event) {
    this.value = event.target.files;
  }
}

And here's the component template:

<input type="file" name="{{ name }}" id="{{ inputId }}" multiple="multiple" (change)="changeFile($event)"/>

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

Best way to unselect a <select> in jQuery?

Use removeAttr...

$("option:selected").removeAttr("selected");

Or Prop

$("option:selected").prop("selected", false)

Perform commands over ssh with Python

First: I'm surprised that no one has mentioned fabric yet.

Second: For exactly those requirements you describe I've implemented an own python module named jk_simpleexec. It's purpose: Making running commands easy.

Let me explain a little bit about it for you.

The 'executing a command locally' problem

My python module jk_simpleexec provides a function named runCmd(..) that can execute a shell (!) command locally or remotely. This is very simple. Here is an example for local execution of a command:

import jk_simpleexec

cmdResult = jk_simpleexec.runCmd(None, "cd / ; ls -la")

NOTE: Be aware that the returned data is trimmed automatically by default to remove excessive empty lines from STDOUT and STDERR. (Of course this behavior can be deactivated, but for the purpose you've in mind exactly that behavior is what you will want.)

The 'processing the result' problem

What you will receive is an object that contains the return code, STDOUT and STDERR. Therefore it's very easy to process the result.

And this is what you want to do as the command you execute might exist and is launched but might fail in doing what it is intended to do. In the most simple case where you're not interested in STDOUT and STDERR your code will likely look something like this:

cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

For debugging purposes you want to output the result to STDOUT at some time, so for this you can do just this:

cmdResult.dump()

If you would want to process STDOUT it's simple as well. Example:

for line in cmdResult.stdOutLines:
    print(line)

The 'executing a command remotely' problem

Now of course we might want to execute this command remotely on another system. For this we can use the same function runCmd(..) in exactly the same way but we need to specify a fabric connection object first. This can be done like this:

from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = "mypwd"
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(c, "cd / ; ls -la")

# ... process the result stored in cmdResult ...

c.close()

Everything remains exactly the same, but this time we run this command on another host. This is intended: I wanted to have a uniform API where there are no modifications required in the software if you at some time decide to move from the local host to another host.

The password input problem

Now of course there is the password problem. This has been mentioned above by some users: We might want to ask the user executing this python code for a password.

For this problem I have created an own module quite some time ago. jk_pwdinput. The difference to regular password input is that jk_pwdinput will output some stars instead of just printing nothing. So for every password character you type you will see a star. This way it's more easy for you to enter a password.

Here is the code:

import jk_pwdinput

# ... define other 'constants' such as REMOTE_LOGIN, REMOTE_HOST ...

REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")

(For completeness: If readpwd(..) returned None the user canceled the password input with Ctrl+C. In a real world scenario you might want to act on this appropriately.)

Full example

Here is a full example:

import jk_simpleexec
import jk_pwdinput
from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(
    c = c,
    command = "cd / ; ls -la"
)
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

c.close()

Final notes

So we have the full set:

  • Executing a command,
  • executing that command remotely via the same API,
  • creating the connection in an easy and secure way with password input.

The code above solves the problem quite well for me (and hopefully for you as well). And everything is open source: Fabric is BSD-2-Clause, and my own modules are provided under Apache-2.

Modules used:

Happy coding! ;-)

What is float in Java?

The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:

float b = 3.6f;

Trouble setting up git with my GitHub Account error: could not lock config file

Just use the following command if you wanna set configuration in system level:

$ sudo git config --system user.name "my_name"

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

#include <sys/types.h>
#include <sys/stat.h>

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

Optional Parameters in Go?

No -- neither. Per the Go for C++ programmers docs,

Go does not support function overloading and does not support user defined operators.

I can't find an equally clear statement that optional parameters are unsupported, but they are not supported either.

How to get Chrome to allow mixed content?

You could use cors anywhere for testing purposes. But its note recommend for production environments.

https://cors-anywhere.herokuapp.com/

something like: https://cors-anywhere.herokuapp.com/http://yourdomain.com/api

How to save a list to a file and read it as a list type?

errorlist = ['aaaa', 'bbbb', 'cccc', 'dddd']

f = open("filee.txt", "w")
f.writelines(nthstring + '\n' for nthstring in errorlist)

f = open("filee.txt", "r")
cont = f.read()
contentlist = cont.split()
print(contentlist)

correct quoting for cmd.exe for multiple arguments

Note the "" at the beginning and at the end!

Run a program and pass a Long Filename

cmd /c write.exe "c:\sample documents\sample.txt"

Spaces in Program Path

cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in Program Path + parameters

cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

Spaces in Program Path + parameters with spaces

cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch Demo1 and then Launch Demo2

cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

CMD.exe (Command Shell)

Comparing two columns, and returning a specific adjacent cell in Excel

I would advise you to swap B and C columns for the reason that I will explain. Then in D2 type: =VLOOKUP(A2, B2:C4, 2, FALSE)

Finally, copy the formula for the remaining cells.

Explanation: VLOOKUP will first find the value of A2 in the range B2 to C4 (second argument). NOTE: VLOOKUP always searches the first column in this range. This is the reason why you have to swap the two columns before doing anything.

Once the exact match is found, it will return the value in the adjacent cell (third argument).

This means that, if you put 1 as the third argument, the function will return the value in the first column of the range (which will be the same value you were looking for). If you put 2, it will return the value from the second column in the range (the value in the adjacent cell-RIGHT SIDE of the found value).

FALSE indicates that you are finding the exact match. If you put TRUE, you will be searching for the approximate match.

How can I check for NaN values?

All the methods to tell if the variable is NaN or None:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

How to extract the hostname portion of a URL in JavaScript

I know this is a bit late, but I made a clean little function with a little ES6 syntax

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

It could also be writen in ES5 like

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.

How to assign Php variable value to Javascript variable?

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

How do I create delegates in Objective-C?

The approved answer is great, but if you're looking for a 1 minute answer try this:

MyClass.h file should look like this (add delegate lines with comments!)

#import <BlaClass/BlaClass.h>

@class MyClass;             //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject>   //define delegate protocol
    - (void) myClassDelegateMethod: (MyClass *) sender;  //define delegate method to be implemented within another class
@end //end protocol

@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate

@end

MyClass.m file should look like this

#import "MyClass.h"
@implementation MyClass 
@synthesize delegate; //synthesise  MyClassDelegate delegate

- (void) myMethodToDoStuff {
    [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
}

@end

To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:

#import "MyClass.h"
@interface MyVC:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}

MyVC.m:

myClass.delegate = self;          //set its delegate to self somewhere

Implement delegate method

- (void) myClassDelegateMethod: (MyClass *) sender {
    NSLog(@"Delegates are great!");
}

Calling a class function inside of __init__

You must declare parse_file like this; def parse_file(self). The "self" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class. Then you can call the function from any method inside the class using self.parse_file

your final program is going to look like this:

class MyClass():
  def __init__(self, filename):
      self.filename = filename 

      self.stat1 = None
      self.stat2 = None
      self.stat3 = None
      self.stat4 = None
      self.stat5 = None
      self.parse_file()

  def parse_file(self):
      #do some parsing
      self.stat1 = result_from_parse1
      self.stat2 = result_from_parse2
      self.stat3 = result_from_parse3
      self.stat4 = result_from_parse4
      self.stat5 = result_from_parse5

Iterating Through a Dictionary in Swift

Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

var largest = 0
var whichKind: String? = nil

for (kind, numbers) in interestingNumbers {
    for number in numbers {
    if number > largest {
        whichKind = kind
        largest = number
    }
  }
}

print(whichKind)
print(largest)

OUTPUT:
Optional("Square")
25

How to add local .jar file dependency to build.gradle file?

The Question already has been answered in detail. I still want to add something that seems very surprising to me:

The "gradle dependencies" task does not list any file dependencies. Even though you might think so, as they have been specified in the "dependencies" block after all..

So don't rely on the output of this to check whether your referenced local lib files are working correctly.

TCPDF Save file to folder?

nick's example saves it to your localhost.
But you can also save it to your local drive.
if you use doublebackslashes:

 $filename= "Invoice.pdf"; 
 $filelocation = "C:\\invoices";  

 $fileNL = $filelocation."\\".$filename;
 $pdf->Output($fileNL,'F');

 $pdf->Output($filename,'D'); // you cannot add file location here

P.S. In Firefox (optional) Tools> Options > General tab> Download >Always ask me where to save files

C# Create New T()

Why hasn't anyone suggested Activator.CreateInstance ?

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

T obj = (T)Activator.CreateInstance(typeof(T));

Close Bootstrap modal on form submit

Neither adding data-dismiss="modal" nor using $("#modal").modal("hide") in javascript worked for me. Sure they closed the modal but the ajax request is not sent either.

Instead, I rendered the partial containing the modals again after ajax is successful (I'm using ruby on rails). I also had to remove "modal-open" class from the body tag too. This basically resets the modals. I think something similar, with a callback upon successful ajax request to remove and add back the modals should work in other framework too.

Best practice to validate null and empty collection in Java

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

if(CollectionUtils.isEmpty(...)) {...}

PHP class: Global variable as property in class

What about using constructor?

class myClass {

   $myNumber = NULL;

   public function __construct() {
      global myNumber;

      $this->myNumber = &myNumber; 
   }

   public function foo() {
      echo $this->myNumber;
   }

}

Or much better this way (passing the global variable as parameter when inicializin the object - read only)

class myClass {

   $myNumber = NULL;

   public function __construct($myNumber) {
      $this->myNumber = $myNumber; 
   }

   public function foo() {
      echo $this->myNumber;
   }

}
$instance = new myClass($myNumber);

Disable a textbox using CSS

**just copy paste this code and run you can see the textbox disabled **

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title> 

<style>.container{float:left;width:200px;height:25px;position:relative;}
       .container input{float:left;width:200px;height:25px;}
       .overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;} 
</style>
 </head>
<body>
      <div class="container">
       <input type="text" value="[email protected]" />
       <div class="overlay">
        </div>
       </div> 
</body>
</html>

Twitter Bootstrap Modal Form Submit

Simple

<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>

IN vs OR in the SQL WHERE Clause

I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN clearly wins)

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

How to "select distinct" across multiple data frame columns in pandas?

I think use drop duplicate sometimes will not so useful depending dataframe.

I found this:

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

And work for me!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

How to show Snackbar when Activity starts?

call this method in onCreate

Snackbar snack = Snackbar.make(
                    (((Activity) context).findViewById(android.R.id.content)),
                    message + "", Snackbar.LENGTH_SHORT);
snack.setDuration(Snackbar.LENGTH_INDEFINITE);//change Duration as you need
            //snack.setAction(actionButton, new View.OnClickListener());//add your own listener
            View view = snack.getView();
            TextView tv = (TextView) view
                    .findViewById(android.support.design.R.id.snackbar_text);
            tv.setTextColor(Color.WHITE);//change textColor

            TextView tvAction = (TextView) view
                    .findViewById(android.support.design.R.id.snackbar_action);
            tvAction.setTextSize(16);
            tvAction.setTextColor(Color.WHITE);

            snack.show();

Sleep for milliseconds

#include <windows.h>

Syntax:

Sleep (  __in DWORD dwMilliseconds   );

Usage:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

What causes the Broken Pipe Error?

Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?

Edit:

The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.

Static array vs. dynamic array in C++

static arrary meens with giving on elements in side the array

dynamic arrary meens without giving on elements in side the array

example:

     char a[10]; //static array
       char a[];  //dynamic array

Multi-threading in VBA

'speed up thread
     dim lpThreadId as long
     dim test as long
     dim ptrt as long
'initparams
     ptrt=varptr(lpThreadId)
     Add = CODEPTR(thread)
'opensocket(191.9.202.255) change depending on configuration
     numSock = Sock.Connect("191.9.202.255", 1958)    
'port recieving
     numSock1=sock.open(5963)
'create thread
     hThread= CreateThread (byval 0&,byval 16384, Add , byval 0&, ByVal 1958, ptrt )
     edit3.text=str$(hThread)


' use 
Declare Function CreateThread Lib "kernel32" Alias "CreateThread" (lpThreadAttributes As long, ByVal dwStackSize As Long, lpStartAddress As Long, lpParameter As long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long

Find duplicate lines in a file and count how many time each line was duplicated?

Via :

awk '{dups[$1]++} END{for (num in dups) {print num,dups[num]}}' data

In awk 'dups[$1]++' command, the variable $1 holds the entire contents of column1 and square brackets are array access. So, for each 1st column of line in data file, the node of the array named dups is incremented.

And at the end, we are looping over dups array with num as variable and print the saved numbers first then their number of duplicated value by dups[num].

Note that your input file has spaces on end of some lines, if you clear up those, you can use $0 in place of $1 in command above :)

Cannot read property 'map' of undefined

The error occur mainly becuase the array isnt found. Just check if you have mapped to the correct array. Check the array name or declaration.

Is it possible to display my iPhone on my computer monitor?

Many screencasts displaying an iPhone application simply use the iPhone Simulator, which is one option.

You can also take screenshots on the phone by quickly pressing the menu and the power/sleep button at the same time. The image is then saved to your "Camera Roll" and easily transferable to the computer

The other way is only possible with a Jailbroken phone - Veency is a VNC server for the iPhone, which you can connect to with a regular VNC client.

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

Missing maven .m2 folder

Is there some command to create this folder?

If smb face this issue again, you should know the most simple way to create .m2 folder.
If you unzipped maven and set up maven path variable - just try mvn clean command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.

How to access the php.ini from my CPanel?

If you're on a shared hosting environment you won't have access to the php.ini to make these changes, if you need access, a virtual private server (VPS) or a dedicated server may be a better option if you're confident in managing it yourself.

Alternatively if you create a new file called .htaccess in your root of your web directory (Ensure it doesn't contain a .txt extension if using notepad to create the file) and copy something like this inside.

php_value settingToChange 6000

This will only work if your hosting provider let's you override the certain config value. Best to ask if it doesn't work after trying.

Convert String To date in PHP

Use the strtotime function:

Example:

 $date = "25 december 2009";
 $my_date = date('m/d/y', strtotime($date));
 echo $my_date;

What is Unicode, UTF-8, UTF-16?

Originally, Unicode was intended to have a fixed-width 16-bit encoding (UCS-2). Early adopters of Unicode, like Java and Windows NT, built their libraries around 16-bit strings.

Later, the scope of Unicode was expanded to include historical characters, which would require more than the 65,536 code points a 16-bit encoding would support. To allow the additional characters to be represented on platforms that had used UCS-2, the UTF-16 encoding was introduced. It uses "surrogate pairs" to represent characters in the supplementary planes.

Meanwhile, a lot of older software and network protocols were using 8-bit strings. UTF-8 was made so these systems could support Unicode without having to use wide characters. It's backwards-compatible with 7-bit ASCII.

How do I convert a number to a numeric, comma-separated formatted string?

Although formatting belongs to the Presentation layer, SQL Server 2012 and above versions provide FORMAT() function which provides one of the quickest and easiest way to format output. Here are some tips & examples:

Syntax: Format( value, format [, culture ] )

Returns: Format function returns NVarchar string formatted with the specified format and with optional culture. (Returns NULL for invalid format-string.)

Note: The Format() function is consistent across CLR / all .NET languages and provides maximum flexibility to generate formatted output.

Following are few format types that can be achieved using this function:

  • Numeric/Currency formatting - 'C' for currency, 'N' number without currency symbol, 'x' for Hexa-decimals.

  • Date/Time formatting - 'd' short date, 'D' long date, 'f' short full date/time, 'F' long full date/time, 't' short time, 'T' long time, 'm' month+day, 'y' year+month.

  • Custom formatting - you can form your own-custom format using certain symbols/characters, such as dd, mm, yyyy etc. (for Dates). hash (#) currency symbols (£ $ etc.), comma(,) and so on. See examples below.

Examples:

Examples of Built-in Numeric/Currency Formats:

?   select FORMAT(1500350.75, 'c', 'en-gb') --> £1,500,350.75
?   select FORMAT(1500350.75, 'c', 'en-au') --> $1,500,350.75
?   select FORMAT(1500350.75, 'c', 'en-in') --> ? 15,00,350.75

Examples of Built-in Date Formats:

?   select FORMAT(getdate(), 'd', 'en-gb') --> 20/06/2017
?   select FORMAT(getdate(), 'D', 'fr-fr') --> mardi 20 juin 2017
?   select FORMAT(getdate(), 'F', 'en-us') --> Tuesday, June 20, 2017 10:41:39 PM
?   select FORMAT(getdate(), 'T', 'en-gb') --> 22:42:29

Examples of Custom Formatting:

?   select FORMAT(GETDATE(), 'ddd  dd/MM/yyyy')  --> Tue 20/06/2017
?   select FORMAT(GETDATE(), 'dddd dd-MMM-yyyy') --> Tuesday 20-Jun-2017
?   select FORMAT(GETDATE(), 'dd.MMMM.yyyy HH:mm:ss') --> 20.June.2017 22:47:20
?   select FORMAT(123456789.75,'$#,#.00')  --> $123,456,789.75
?   select FORMAT(123456789.75,'£#,#.0')   --> £123,456,789.8

See MSDN for more information on FORMAT() function.

For SQL Server 2008 or below convert the output to MONEY first then to VARCHAR (passing "1" for the 3rd argument of CONVERT() function to specify the "style" of output-format), e.g.:

?   select CONVERT(VARCHAR, CONVERT(MONEY, 123456789.75), 1)    --> 123,456,789.75