Programs & Examples On #Nstextstorage

Import/Index a JSON file into Elasticsearch

  • If you are using the elastic search 7.7 or above version then follow below command.

    curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk? pretty&refresh" --data-binary @"/Users/waseem.khan/waseem/elastic/account.json"

  • On above file path is /Users/waseem.khan/waseem/elastic/account.json.

  • If you are using elastic search 6.x version then you can use the below command.

curl -X POST localhost:9200/bank/_bulk?pretty&refresh --data-binary @"/Users/waseem.khan/waseem/elastic/account.json" -H 'Content-Type: application/json'

Note: Make sure in your .json file at the end you will add the one empty line otherwise you will be getting below exception.

"error" : {
"root_cause" : [
  {
    "type" : "illegal_argument_exception",
    "reason" : "The bulk request must be terminated by a newline [\n]"
  }
],
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
},
`enter code here`"status" : 400

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

How to add screenshot to READMEs in github repository?

The markdown syntax for displaying images is indeed:

![image](https://{url})

BUT: How to provide the url ?

  • You probably do not want to clutter your repo with screenshots, they have nothing to do with code
  • you might not want either to deal with the hassle of making your image available on the web... (upload it to a server... ).

So... you can use this awesome trick to make github host your image file. TDLR:

  1. create an issue on the issue list of your repo
  2. drag and drop your screenshot on this issue
  3. copy the markdown code that github has just created for you to display your image
  4. paste it on your readme (or wherever you want)

http://solutionoptimist.com/2013/12/28/awesome-github-tricks/

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

Eclipse, regular expression search and replace

Yes, ( ) captures a group. You can use it again with $i where i is the i'th capture group.

So:

search: (\w+\.someMethod\(\))

replace: ((TypeName)$1)

Hint: Ctrl + Space in the textboxes gives you all kinds of suggestions for regular expression writing.

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

How do you decrease navbar height in Bootstrap 3?

 .navbar-nav > li > a {padding-top:7px !important; padding-bottom:7px !important;}
.navbar {min-height:32px !important;} 
.navbar-brand{padding-top:7px !important; max-height: 24px;  }
.navbar .navbar-toggle {  margin-top: 0px; margin-bottom: 0px; padding: 8px 9px; }

Better way to sum a property value in an array

I'm not sure this has been mentioned yet. But there is a lodash function for that. Snippet below where value is your attribute to sum is 'value'.

_.sumBy(objects, 'value');
_.sumBy(objects, function(o) { return o.value; });

Both will work.

How to write to a CSV line by line?

What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

how to avoid extra blank page at end while printing?

.print:last-child{
    page-break-after: avoid;
    page-break-inside: avoid;
    margin-bottom: 0px;
}

This worked for me.

How can I post an array of string to ASP.NET MVC Controller without a form?

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{ Values : ["1", "2", "3"] }

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

"unrecognized import path" with go get

Because GFW forbidden you to access golang.org ! And when i use the proxy , it can work well.

you can look at the information using command go get -v -u golang.org/x/oauth2

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

How to change identity column values programmatically?

You need to

set identity_insert YourTable ON

Then delete your row and reinsert it with different identity.

Once you have done the insert don't forget to turn identity_insert off

set identity_insert YourTable OFF

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]

jquery: change the URL address without redirecting?

See here - http://my.opera.com/community/forums/topic.dml?id=1319992&t=1331393279&page=1#comment11751402

Essentially:

history.pushState('data', '', 'http://your-domain/path');

You can manipulate the history object to make this work.

It only works on the same domain, but since you're satisfied with using the hash tag approach, that shouldn't matter.

Obviously would need to be cross-browser tested, but since that was posted on the Opera forum I'm safe to assume it would work in Opera, and I just tested it in Chrome and it worked fine.

Change :hover CSS properties with JavaScript

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

How can I find the first occurrence of a sub-string in a python string?

def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

Using malloc for allocation of multi-dimensional arrays with different row lengths

Equivalent memory allocation for char a[10][20] would be as follows.

char **a;

a=(char **) malloc(10*sizeof(char *));

for(i=0;i<10;i++)
    a[i]=(char *) malloc(20*sizeof(char));

I hope this looks simple to understand.

AngularJs event to call after content is loaded

Angular < 1.6.X

angular.element(document).ready(function () {
    console.log('page loading completed');
});

Angular >= 1.6.X

angular.element(function () {
    console.log('page loading completed');
});

How to position background image in bottom right corner? (CSS)

for more exactly positioning:

      background-position: bottom 5px right 7px;

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

If You using Android 9.0 with legacy jar than you have to use. in your mainfest file.

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Microsoft.ACE.OLEDB.12.0 is not registered

Just install 32bit version of ADBE in passive mode:

run cmd in administrator mode and run this code:

AccessDatabaseEngine.exe /passive

http://www.microsoft.com/en-us/download/details.aspx?id=13255

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

Illegal Escape Character "\"

do two \'s

"\\"

it's because it's an escape character

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

Did you try this simple solution? Only 2 clicks away!

At the query window,

  1. set query options to "Results to Grid", run your query
  2. Right click on the results tab at the grid corner, save results as any files

You will get all the text you want to see in the file!!! I can see 130,556 characters for my result of a varchar(MAX) field

Results in a file

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Batch files - number of command line arguments

The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

@echo off
setlocal

set argc_=1
set arg0_=%0
set argv_=

:_LOOP
set arg_=%1
if defined arg_ (
  set arg%argc_%_=%1
  set argv_=%argv_% %1
  set /a argc_+=1
  shift
  goto _LOOP
)
::dont count arg0
set /a argc_-=1
echo %argc_% arg(s)

for /L %%i in (0,1,%argc_%) do (
  call :_SHOW_ARG arg%%i_ %%arg%%i_%%
)

echo converted to local args
call :_LIST_ARGS %argv_%
exit /b


:_LIST_ARGS
setlocal
set argc_=0
echo arg0=%0

:_LOOP_LIST_ARGS
set arg_=%1
if not defined arg_ exit /b
set /a argc_+=1
call :_SHOW_ARG arg%argc_% %1
shift
goto _LOOP_LIST_ARGS


:_SHOW_ARG
echo %1=%2
exit /b

The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.

Count words in a string method?

public static int countWords(String str){
        if(str == null || str.isEmpty())
            return 0;

        int count = 0;
        for(int e = 0; e < str.length(); e++){
            if(str.charAt(e) != ' '){
                count++;
                while(str.charAt(e) != ' ' && e < str.length()-1){
                    e++;
                }
            }
        }
        return count;
    }

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

How can I count the number of matches for a regex?

matcher.find() does not find all matches, only the next match.

Solution for Java 9+

long matches = matcher.results().count();

Solution for Java 8 and older

You'll have to do the following. (Starting from Java 9, there is a nicer solution)

int count = 0;
while (matcher.find())
    count++;

Btw, matcher.groupCount() is something completely different.

Complete example:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Handling overlapping matches

When counting matches of aa in aaaa the above snippet will give you 2.

aaaa
aa
  aa

To get 3 matches, i.e. this behavior:

aaaa
aa
 aa
  aa

You have to search for a match at index <start of last match> + 1 as follows:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

How do you use math.random to generate random ints?

you are importing java.util package. That's why its giving error. there is a random() in java.util package too. Please remove the import statement importing java.util package. then your program will use random() method for java.lang by default and then your program will work. remember to cast it i.e

int x = (int)(Math.random()*100);

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

How do you divide each element in a list by an int?

I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.

  arrayint=np.array(myInt)
  newList = myList / arrayint

This a comparison of all answers above

import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)

What are ABAP and SAP?

See http://en.wikipedia.org/wiki/SAP_AG.

In short, SAP is a modular based application that sits on top of a database (as many applications do). Many people mistake SAP as being a database, but in fact it is just the application.

By 'modular based application' I mean that 'SAP Netweaver' is a bit like 'Microsoft Office' in that it is an application or set of applications that contains many components/modules. With SAP you can add modules (such as Finance, HR, Banking, Logistics, etc.) to meet your business requirements.

ABAP is a bespoke programming language that is used within SAP. SAP also now has components that are purely ABAP based, purely JAVA based or a mixture of the two. SAP can also integrate with other technologies such as .net and PHP.

Loop through all nested dictionary values?

These answers work for only 2 levels of sub-dictionaries. For more try this:

nested_dict = {'dictA': {'key_1': 'value_1', 'key_1A': 'value_1A','key_1Asub1': {'Asub1': 'Asub1_val', 'sub_subA1': {'sub_subA1_key':'sub_subA1_val'}}},
                'dictB': {'key_2': 'value_2'},
                1: {'key_3': 'value_3', 'key_3A': 'value_3A'}}

def print_dict(dictionary):
    dictionary_array = [dictionary]
    for sub_dictionary in dictionary_array:
        if type(sub_dictionary) is dict:
            for key, value in sub_dictionary.items():
                print("key=", key)
                print("value", value)
                if type(value) is dict:
                    dictionary_array.append(value)



print_dict(nested_dict)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

I got this error when trying to install a python package in a Docker container. For me, the issue was that the docker image did not have a locale configured. Adding the following code to the Dockerfile solved the problem for me.

# Avoid ascii errors when reading files in Python
RUN apt-get install -y locales && locale-gen en_US.UTF-8
ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' LC_ALL='en_US.UTF-8'

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

Why do I need to override the equals and hashCode methods in Java?

It is useful when using Value Objects. The following is an excerpt from the Portland Pattern Repository:

Examples of value objects are things like numbers, dates, monies and strings. Usually, they are small objects which are used quite widely. Their identity is based on their state rather than on their object identity. This way, you can have multiple copies of the same conceptual value object.

So I can have multiple copies of an object that represents the date 16 Jan 1998. Any of these copies will be equal to each other. For a small object such as this, it is often easier to create new ones and move them around rather than rely on a single object to represent the date.

A value object should always override .equals() in Java (or = in Smalltalk). (Remember to override .hashCode() as well.)

How to enable multidexing with the new Android Multidex support library

Multi_Dex.java

public class Multi_Dex extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

How to get key names from JSON using jq

You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"

Making interface implementations async

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

Get properties and values from unknown object

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

Present and dismiss modal view controller

The easiest way to do it is using Storyboard and a Segue.

Just create a Segue from the FirstViewController (not the Navigation Controller) of your TabBarController to a LoginViewController with the login UI and name it "showLogin".

Create a method that returns a BOOL to validate if the user logged in and/or his/her session is valid... preferably on the AppDelegate. Call it isSessionValid.

On your FirstViewController.m override the method viewDidAppear as follows:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if([self isSessionValid]==NO){
        [self performSegueWithIdentifier:@"showLogin" sender:self];
    }
}

Then if the user logged in successfully, just dismiss or pop-out the LoginViewController to show your tabs.

Works 100%!

Hope it helps!

Call apply-like function on each row of dataframe with multiple arguments from each row

A data.frame is a list, so ...

For vectorized functions do.call is usually a good bet. But the names of arguments come into play. Here your testFunc is called with args x and y in place of a and b. The ... allows irrelevant args to be passed without causing an error:

do.call( function(x,z,...) testFunc(x,z), df )

For non-vectorized functions, mapply will work, but you need to match the ordering of the args or explicitly name them:

mapply(testFunc, df$x, df$z)

Sometimes apply will work - as when all args are of the same type so coercing the data.frame to a matrix does not cause problems by changing data types. Your example was of this sort.

If your function is to be called within another function into which the arguments are all passed, there is a much slicker method than these. Study the first lines of the body of lm() if you want to go that route.

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

What is the best way to tell if a character is a letter or number in Java without using regexes?

 import java.util.Scanner;
 public class v{
 public static void main(String args[]){
 Scanner in=new Scanner(System.in);
    String str;
    int l;
    int flag=0;
    System.out.println("Enter the String:");
    str=in.nextLine();
    str=str.toLowerCase();
    str=str.replaceAll("\\s","");
    char[] ch=str.toCharArray();
    l=str.length();
    for(int i=0;i<l;i++){
        if ((ch[i] >= 'a' && ch[i]<= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')){
        flag=0;
        }
        else

        flag++;
        break;
        } 
if(flag==0)
    System.out.println("Onlt char");


}
}

How do I build a graphical user interface in C++?

There are plenty of free portable GUI libraries, each with its own strengths and weaknesses:

Especially Qt has nice tutorials and tools which help you getting started. Enjoy!

Note, however, that you should avoid platform specific functionality such as the Win32 API or MFC. That ties you unnecessarily on a specific platform with almost no benefits.

Installing Tomcat 7 as Service on Windows Server 2008

There are a lot of answers here, but many overlook a few points. I ran into the same issue and it was likely due to a combination of being a complete neophyte when it comes to tomcat. Even more I am rather new to web servers in general. I consider myself somewhat proficient user of windows, but I guess not proficient enough. In particular I don't work with services too much.

I did not have a startup.bat or any bat files. I only downloaded the 32-bit/64-bit Windows Service Installer. The bin that is created for that download is small - only 4 files. My colleagues were surprised that I did not have a catalina.bat etc... and I was too. Only the below four files in the bin. And no %CATALINA_HOME% or %TOMCAT_HOME% etc...

bootstrap.jar
tomcat-juli.jar
Tomcat7.exe
Tomcat7w.exe

With this setup I had some frustrations as setting parameters is done via the gui widget - very helpful I might add.

So nearly all the answers I have perused were not immediately applicable as many said, "go to bin and issue the startup.bat file" I am a neophyte but not so much to not be able to look into the bin and start such a file it is existed!

For my simple purposes (again remember that I am a neophyte at tomcat and even web servers) all I wanted to do was to be able to startup and shutdown the tomcat server from a cmd prompt window. Nothing too heavy duty. I am embarrassed to say how simple it is. It is probably evident to anyone with a shred of experience with services and such.

To Start server: <Tomcat Root>/bin>Tomcat7.exe start
To Stop server: <Tomcat Root>/bin>Tomcat7.exe stop

Found here - http://crunchify.com/how-to-start-stop-apache-tomcat-server-via-command-line-setup-as-windows-service/

I did not realize there was a separate download the 64-bit Windows zip file that has a tomcat server and all the standard array of cmd line tomcat management tools. This zip file has all the common startup/shutdown scripts, batch files for windows, including catalina.bat/.sh etc... Then all the above answers make sense and are rather trivial.

Remember I am a neophyte when it comes to tomcat and web servers. It appears these two downloads are somewhat mutually exclusive in the sense that if I download and install the 32-bit/64-bit Windows Service Installer version and the 64-bit Windows zip file the startup.bat file in the 64-bit Windows zip file version will not run or interact with the 32-bit/64-bit Windows Service Installer tomcat instance. But I am not sure about this point.

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

How can I check if a JSON is empty in NodeJS?

You can use this:

var isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
}

or this:

function isEmpty(obj) {
  return !Object.keys(obj).length > 0;
}

You can also use this:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
      return false;
  }

  return true;
}

If using underscore or jQuery, you can use their isEmpty or isEmptyObject calls.

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

How to define dimens.xml for every different screen size in android?

You have to create Different values folder for different screens . Like

values-sw720dp          10.1” tablet 1280x800 mdpi

values-sw600dp          7.0”  tablet 1024x600 mdpi

values-sw480dp          5.4”  480x854 mdpi 
values-sw480dp          5.1”  480x800 mdpi 

values-xxhdpi           5.5"  1080x1920 xxhdpi
values-xxxhdpi           5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7”   1280x720 xhdpi 
values-xhdpi            4.65”  720x1280 xhdpi 

values-hdpi             4.0” 480x800 hdpi
values-hdpi             3.7” 480x854 hdpi

values-mdpi             3.2” 320x480 mdpi

values-ldpi             3.4” 240x432 ldpi
values-ldpi             3.3” 240x400 ldpi
values-ldpi             2.7” 240x320 ldpi

enter image description here

For more information you may visit here

Different values folders in android

http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html

Edited By @humblerookie

You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

The requested URL /about was not found on this server

I deleted the previous .htaccess file and created new one by clicking on save button in Settings->Permalinks

and now that pages started working fine...

How can I disable ARC for a single file in a project?

Please Just follow the screenshot and enter -fno-objc-arc .

enter image description here

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

jQuery select all except first

My answer is focused to a extended case derived from the one exposed at top.

Suppose you have group of elements from which you want to hide the child elements except first. As an example:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>
  1. We want to hide all .child elements on every group. So this will not help because will hide all .child elements except visible#1:

    $('.child:not(:first)').hide();
    
  2. The solution (in this extended case) will be:

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });
    

Simplest way to detect a pinch

Hammer.js all the way! It handles "transforms" (pinches). http://eightmedia.github.com/hammer.js/

But if you wish to implement it youself, i think that Jeffrey's answer is pretty solid.

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

How do I make curl ignore the proxy?

I assume curl is reading the proxy address from the environment variable http_proxy and that the variable should keep its value. Then in a shell like bash, export http_proxy=''; before a command (or in a shell script) would temporarily change its value.

(See curl's manual for all the variables it looks at, under the ENVIRONMENT heading.)

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

What does the fpermissive flag do?

Right from the docs:

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Bottom line: don't use it unless you know what you are doing!

Python - Check If Word Is In A String

find returns an integer representing the index of where the search item was found. If it isn't found, it returns -1.

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print 'Needle found.'
else:
  print 'Needle not found.'

SqlServer: Login failed for user

Just in case any one else is using creating test users with their automation....

We had this same error and it was because we had recreated the user (as part of the test process). This caused the underlying SID to change which meant that SQL couldn't properly authenticate the user.

We fixed it by adding a drop login command to our testing scripts to ensure that a previously created user (with the same user name) was no longer present on the instance.

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

How to create a GUID/UUID using iOS

Reviewing the Apple Developer documentation I found the CFUUID object is available on the iPhone OS 2.0 and later.

Returning JSON object as response in Spring Boot

As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.

And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001

If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.

How to find the size of an int[]?

Assuming you merely want to know the size of an array whose type you know (int) but whose size, obviously, you don't know, it is suitable to verify whether the array is empty, otherwise you will end up with a division by zero (causing a Float point exception).

int array_size(int array[]) {
    if(sizeof(array) == 0) {
        return 0;
    }
    return sizeof(array)/sizeof(array[0]);
 }

How to make JQuery-AJAX request synchronous

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

Declare a dictionary inside a static class

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

How to insert tab character when expandtab option is on in Vim

You can use <CTRL-V><Tab> in "insert mode". In insert mode, <CTRL-V> inserts a literal copy of your next character.

If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:

:inoremap <S-Tab> <C-V><Tab>

Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q> rather than <CTRL-V>.

Open multiple Eclipse workspaces on the Mac

One another way is just to duplicate only the "Eclipse.app" file instead of making multiple copies of entire eclipse directory. Right-Click on the "Eclipse.app" file and click the duplicate option to create a duplicate.

Extract a single (unsigned) integer from a string

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

How to set header and options in axios?

I have face this issue in post request. I have changed like this in axios header. It works fine.

axios.post('http://localhost/M-Experience/resources/GETrends.php',
      {
        firstName: this.name
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });

What Are Some Good .NET Profilers?

If Licensing is an issue you could try WINDBG for memory profiling

How to HTML encode/escape a string? Is there a built-in?

You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.

In your controller:

@stuff = "<b>Hello World!</b>"

In your view:

<%=h @stuff %>

If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as &lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

Gulp 4.0 has changed the way that tasks should be defined if the task depends on another task to execute. The list parameter has been deprecated.

An example from your gulpfile.js would be:

// Starts a BrowerSync instance
gulp.task('server', ['build'], function(){
  browser.init({server: './_site', port: port});
});

Instead of the list parameter they have introduced gulp.series() and gulp.parallel().

This task should be changed to something like this:

// Starts a BrowerSync instance
gulp.task('server', gulp.series('build', function(){
  browser.init({server: './_site', port: port});
}));

I'm not an expert in this. You can see a more robust example in the gulp documentation for running tasks in series or these following excellent blog posts by Jhey Thompkins and Stefan Baumgartner

https://codeburst.io/switching-to-gulp-4-0-271ae63530c0

https://fettblog.eu/gulp-4-parallel-and-series/

C# Iterating through an enum? (Indexing a System.Array)

Old question, but a slightly cleaner approach using LINQ's .Cast<>()

var values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

foreach(var val in values)
{
    Console.WriteLine("Member: {0}",val.ToString());     
}

CSS change button style after click

Each link has five different states: link, hover, active, focus and visited.

Link is the normal appearance, hover is when you mouse over, active is the state when it's clicked, focus follows active and visited is the state you end up when you unfocus the recently clicked link.

I'm guessing you want to achieve a different style on either focus or visited, then you can add the following CSS:

a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }

A recommended order in your CSS to not cause any trouble is the following:

a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }

You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

Why does Java have an "unreachable statement" compiler error?

It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.

How can I convert ticks to a date format?

    private void button1_Click(object sender, EventArgs e)
    {
        long myTicks = 633896886277130000;
        DateTime dtime = new DateTime(myTicks);
        MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
    }

Gives

September 27, 2009

Is that what you need?

I don't see how that format is necessarily easy to work with in SQL queries, though.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

Using margin / padding to space <span> from the rest of the <p>

Add this style to your span:

position:relative; 
top: 10px;

Demo: http://jsfiddle.net/BqTUS/3/

Define a fixed-size list in Java

This should work pretty nicely. It will never grow beyond the initial size. The toList method will give you the entries in the correct chronological order. This was done in groovy - but converting it to java proper should be pretty easy.

static class FixedSizeCircularReference<T> {
    T[] entries
    FixedSizeCircularReference(int size) {
        this.entries = new Object[size] as T[]
        this.size = size
    }
    int cur = 0
    int size
    void add(T entry) {
        entries[cur++] = entry
        if (cur >= size) {
            cur = 0
        }
    }
    List<T> asList() {
        List<T> list = new ArrayList<>()
        int oldest = (cur == size - 1) ? 0 : cur
        for (int i = 0; i < this.entries.length; i++) {
            def e = this.entries[oldest + i < size ? oldest + i : oldest + i - size]
            if (e) list.add(e)
        }
        return list
    }
}

FixedSizeCircularReference<String> latestEntries = new FixedSizeCircularReference(100)
latestEntries.add('message 1') 
// .....
latestEntries.add('message 1000') 
latestEntries.asList() //Returns list of '100' messages

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

oracle sql: update if exists else insert

merge into MY_TABLE tgt
using (select [expressions]
         from dual ) src
   on (src.key_condition = tgt.key_condition)
when matched then 
     update tgt
        set tgt.column1 = src.column1 [,...]
when not matched then 
     insert into tgt
        ([list of columns])
     values
        (src.column1 [,...]);

Extract month and year from a zoo::yearmon object

Use the format() method for objects of class "yearmon". Here is your example date (properly created!)

date1 <- as.yearmon("Mar 2012", "%b %Y")

Then we can extract the date parts as required:

> format(date1, "%b") ## Month, char, abbreviated
[1] "Mar"
> format(date1, "%Y") ## Year with century
[1] "2012"
> format(date1, "%m") ## numeric month
[1] "03"

These are returned as characters. Where appropriate, wrap in as.numeric() if you want the year or numeric month as a numeric variable, e.g.

> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012

See ?yearmon and ?strftime for details - the latter explains the placeholder characters you can use.

The remote host closed the connection. The error code is 0x800704CD

One can reproduce the error with the code below:

public ActionResult ClosingTheConnectionAction(){
   try
   {
      //we need to set buffer to false to
      //make sure data is written in chunks
      Response.Buffer = false;  
      var someText = "Some text here to make things happen ;-)";
      var content = GetBytes( someText );

      for(var i=0; i < 100; i++)
      {
         Response.OutputStream.Write(content, 0, content.Length);
      }

      return View();
   }
   catch(HttpException hex)
   {
      if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
            {
                //react on remote host closed the connection exception.
                var msg = hex.Message;
            }  
   }
   catch(Exception somethingElseHappened)
   {
      //handle it with some other code
   }

   return View();
} 

Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

As other answers suggest... Some guy (for whatever reason) decided that your old code should not work when you upgrade your PHP, because he knows better than you and don't care about what your code does or how simple it is for you to upgrade.

Well, if you can't upgrade your project overnight you can

downgrade your version of PHP to whatever version that worked

or...

use a shim (kind of polyfill) such as https://github.com/dshafik/php7-mysql-shim or https://github.com/dotpointer/mysql-shim, and then find a place for include_once("choice_shim.php"); somewhere in your code

That will keep your old PHP code up and running until you are in a mood to update...

REST API using POST instead of GET

Think about it. When your client makes a GET request to an URI X, what it's saying to the server is: "I want a representation of the resource located at X, and this operation shouldn't change anything on the server." A PUT request is saying: "I want you to replace whatever is the resource located at X with the new entity I'm giving you on the body of this request". A DELETE request is saying: "I want you to delete whatever is the resource located at X". A PATCH is saying "I'm giving you this diff, and you should try to apply it to the resource at X and tell me if it succeeds." But a POST is saying: "I'm sending you this data subordinated to the resource at X, and we have a previous agreement on what you should do with it."

If you don't have it documented somewhere that the resource expects a POST and does something with it, it doesn't make sense to send a POST to it expecting it to act like a GET.

REST relies on the standardized behavior of the underlying protocol, and POST is precisely the method used for an action that isn't standardized. The result of a GET, PUT and DELETE requests are clearly defined in the standard, but POST isn't. The result of a POST is subordinated to the server, so if it's not documented that you can use POST to do something, you have to assume that you can't.

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How to split an integer into an array of digits?

Maybe join+split:

>>> a=12345
>>> list(map(int,' '.join(str(a)).split()))
[1, 2, 3, 4, 5]
>>> [int(i) for i in ' '.join(str(a)).split()]
[1, 2, 3, 4, 5]
>>> 

str.join + str.split is your friend, also we use map or list comprehension to get a list, (split what we join :-)).

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

single and easy js function for calc time meridian in real time

JS

   function convertTime24to12(time24h) {
                var timex = time24h.split(':');

                if(timex[0] !== undefined && timex [1] !== undefined)
                 {
                     var hor = parseInt(timex[0]) > 12 ? (parseInt(timex[0])-12) : timex[0] ;
                     var minu = timex[1];
                     var merid = parseInt(timex[0]) < 12 ? 'AM' : 'PM';

                     var res = hor+':'+minu+' '+merid;

                     document.getElementById('timeMeridian').innerHTML=res.toString();
                 }
            }

Html

 <label for="end-time">Hour <i id="timeMeridian"></i> </label>
            <input type="time" name="hora" placeholder="Hora" id="end-time" class="form-control" onkeyup="convertTime24to12(this.value)">

No notification sound when sending notification from firebase in android

Try this

{
    "to" : "DEVICE-TOKEN",

    "notification" : {
      "body"  : "NOTIFICATION BODY",
      "title" : "NOTIFICATION TITILE",
      "sound" : "default"
    }
  }

@note for custom notification sound:-> "sound" : "MyCustomeSound.wav"

C++ Remove new line from multiline string

Here is one for DOS or Unix new line:

    void chomp( string &s)
    {
            int pos;
            if((pos=s.find('\n')) != string::npos)
                    s.erase(pos);
    }

Check synchronously if file/directory exists in Node.js

updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.

Sync solution:

fs.existsSync('filePath') also see docs here.

Returns true if the path exists, false otherwise.

Async Promise solution

In an async context you could just write the async version in sync method with using the await keyword. You can simply turn the async callback method into an promise like this:

function fileExists(path){
  return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK, 
    (err, result) => err ? fail(err) : resolve(result))
  //F_OK checks if file is visible, is default does no need to be specified.

}

async function doSomething() {
  var exists = await fileExists('filePath');
  if(exists){ 
    console.log('file exists');
  }
}

the docs on access().

How to convert string representation of list to a list?

If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).

>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one on the pyparsing wiki, which will handle tuples, lists, ints, floats, and quoted strings. Will work with Python versions back to 2.4.

How might I schedule a C# Windows Service to perform a task daily?

The way I accomplish this is with a timer.

Run a server timer, have it check the Hour/Minute every 60 seconds.

If it's the right Hour/Minute, then run your process.

I actually have this abstracted out into a base class I call OnceADayRunner.

Let me clean up the code a bit and I'll post it here.

    private void OnceADayRunnerTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (NDC.Push(GetType().Name))
        {
            try
            {
                log.DebugFormat("Checking if it's time to process at: {0}", e.SignalTime);
                log.DebugFormat("IsTestMode: {0}", IsTestMode);

                if ((e.SignalTime.Minute == MinuteToCheck && e.SignalTime.Hour == HourToCheck) || IsTestMode)
                {
                    log.InfoFormat("Processing at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                    OnceADayTimer.Enabled = false;
                    OnceADayMethod();
                    OnceADayTimer.Enabled = true;

                    IsTestMode = false;
                }
                else
                {
                    log.DebugFormat("Not correct time at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                }
            }
            catch (Exception ex)
            {
                OnceADayTimer.Enabled = true;
                log.Error(ex.ToString());
            }

            OnceADayTimer.Start();
        }
    }

The beef of the method is in the e.SignalTime.Minute/Hour check.

There are hooks in there for testing, etc. but this is what your elapsed timer could look like to make it all work.

Convert a string to datetime in PowerShell

You need to specify the format it already has, in order to parse it:

$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)

Now you can output it in the format you need:

$InvoiceDate.ToString('yyyy-MM-dd')

or

'{0:yyyy-MM-dd}' -f $InvoiceDate

The given key was not present in the dictionary. Which key?

You can try this code

Dictionary<string,string> AllFields = new Dictionary<string,string>();  
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

If the key is not present, it simply returns a null value.

How to restrict the selectable date ranges in Bootstrap Datepicker?

The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.

Example:

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

MVC razor form with multiple different submit buttons?

Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):

On HTML:

<form action="" method="post" role="form">
<table>
@for (var i = 0; i < Model.List.Count(); i++)
{
    <tr>
        <td>@Model.List[i].ItemDescription</td>
        <td>
            <input type="submit" value="REMOVE" class="btn btn-xs btn-danger" 
             asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="@Model.List[i].idForDeleteItem" />
        </td>
    </tr>
}
</table>
</form>

On Controller:

[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
    ///delete with param id goes here
}

Don't forget to use [Route("[controller]")] BEFORE the class declaration - on controller.

System.loadLibrary(...) couldn't find native library in my case

To root cause (and maybe solve your issue in the same time), here is what you can do:

  1. Remove the jni folder and all the .mk files. You don't need these nor the NDK if you aren't compiling anything.

  2. Copy your libcalculate.so file inside <project>/libs/(armeabi|armeabi-v7a|x86|...) . When using Android Studio, it's <project>/app/src/main/jniLibs/(armeabi|armeabi-v7a|x86|...), but I see you're using eclipse.

  3. Build your APK and open it as a zip file, to check that your libcalculate.so file is inside lib/(armeabi|armeabi-v7a|x86|...).

  4. Remove and install your application

  5. Run dumpsys package packages | grep yourpackagename to get the nativeLibraryPath or legacyNativeLibraryDir of your application.

  6. Run ls on the nativeLibraryPath you had or on legacyNativeLibraryDir/armeabi, to check if your libcalculate.so is indeed there.

  7. If it's there, check if it hasn't been altered from your original libcalculate.so file: is it compiled against the right architecture, does it contain the expected symbols, are there any missing dependencies. You can analyze libcalculate.so using readelf.

In order to check step 5-7, you can use my application instead of command lines and readelf: Native Libs Monitor

PS: It's easy to get confused on where .so files should be put or generated by default, here is a summary:

  • libs/CPU_ABI inside an eclipse project

  • jniLibs/CPU_ABI inside an Android Studio project

  • jni/CPU_ABI inside an AAR

  • lib/CPU_ABI inside the final APK

  • inside the app's nativeLibraryPath on a <5.0 device, and inside the app's legacyNativeLibraryDir/CPU_ARCH on a >=5.0 device.

Where CPU_ABI is any of: armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, mips64. Depending on which architectures you're targeting and your libs have been compiled for.

Note also that libs aren't mixed between CPU_ABI directories: you need the full set of what you're using, a lib that is inside the armeabi folder will not be installed on a armeabi-v7a device if there are any libs inside the armeabi-v7a folder from the APK.

Convert Long into Integer

In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0

MySQL does not start when upgrading OSX to Yosemite or El Capitan

Execute the following commands from command line...

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

and then start the mysql server using

sudo /usr/local/mysql/support-files/mysql.server start

Raising a number to a power in Java

^ is not the operator you want. You are looking for the pow function of java.lang.Math.

You can use Math.pow(value, power).

Example:

Math.pow(23, 5); // 23 to the fifth power

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

Python: Split a list into sub-lists based on index ranges

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

How line ending conversions work with git core.autocrlf between different operating systems

The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:

  1. The repo may have different files with different EOLs
  2. Some files in the repo may have mixed EOL, e.g. a combination of CRLF and LF in the same file.

How this happens is not the issue here, but it does happen.

I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:

                 | Resulting conversion when       | Resulting conversion when 
                 | committing files with various   | checking out FROM repo - 
                 | EOLs INTO repo and              | with mixed files in it and
                 |  core.autocrlf value:           | core.autocrlf value:           
--------------------------------------------------------------------------------
File             | true       | input      | false | true       | input | false
--------------------------------------------------------------------------------
Windows-CRLF     | CRLF -> LF | CRLF -> LF | as-is | as-is      | as-is | as-is
Unix -LF         | as-is      | as-is      | as-is | LF -> CRLF | as-is | as-is
Mac  -CR         | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF    | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF+CR | as-is      | as-is      | as-is | as-is      | as-is | as-is

As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.

Upon checkout (3 right columns), there is only 1 case where conversion happens when:

  1. core.autocrlf is true and
  2. the file in the repo has the LF EOL.

Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF+LF get normalized.

Note also that "old" Mac EOLs of CR only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLFs+LFs, by just converting LFs to CRLFs, then it will leave the file in a mixed mode with "lonely" CRs wherever a CRLF was converted to CRCRLF.
Git will then not convert anything, even in true mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.

I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input or false mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Environment variables in Eclipse

I've created an eclipse plugin for this, because I had the same problem. Feel free to download it and contribute to it.

It's still in early development, but it does its job already for me.

https://github.com/JorisAerts/Eclipse-Environment-Variables

enter image description here

What is the difference between .text, .value, and .value2?

target.Value will give you a Variant type

target.Value2 will give you a Variant type as well but a Date is coerced to a Double

target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

The safest thing to do is something like

Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2

And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

Passing a callback function to another class

You could change your code in this way:

public delegate void CallbackHandler(string str);

public class ServerRequest
{
    public void DoRequest(string request, CallbackHandler callback)
    {
        // do stuff....
        callback("asdf");
    }
}

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

How do I change a TCP socket to be non-blocking?

Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2), poll(2) or some other system calls available on your system.

See The C10K problem for the comparison of approaches to scalable IO multiplexing.

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

Check cell for a specific letter or set of letters

Some options without REGEXMATCH, since you might want to be case insensitive and not want say blast or ablative to trigger a YES. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:

First very similar to @user1598086's answer:

=FIND("bla",A1)

Is case sensitive but returns #VALUE! rather than NO and a number rather than YES (both of which can however be changed to NO/YES respectively).

=SEARCH("bla",A1)  

Case insensitive, so treats Black and black equally. Returns as above.

The former (for the latter equivalent) to indicate whether bla present after the first three characters in A1:

=FIND("bla",A1,4)  

Returns a number for blazer, black but #VALUE! for blazer, blue.

To find Bla only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):

=SEARCH(" Bla ",A1) 

Since the return in all cases above is either a number ("found", so YES preferred) or #VALUE! we can use ISERROR to test for #VALUE! within an IF formula, for instance taking the first example above:

 =if(iserror(FIND("bla",A1)),"NO","YES")  

Longer than the regexmatch but the components are easily adjustable.

How can I keep Bootstrap popovers alive while being hovered?

Test with code snippet below:

Small modification (From the solution provided by vikas) to suit my use case.

  1. Open popover on hover event for the popover button
  2. Keep popover open when hovering over the popover box
  3. Close popover on mouseleave for either the popover button, or the popover box.

_x000D_
_x000D_
$(".pop").popover({
    trigger: "manual",
    html: true,
    animation: false
  })
  .on("mouseenter", function() {
    var _this = this;
    $(this).popover("show");
    $(".popover").on("mouseleave", function() {
      $(_this).popover('hide');
    });
  }).on("mouseleave", function() {
    var _this = this;
    setTimeout(function() {
      if (!$(".popover:hover").length) {
        $(_this).popover("hide");
      }
    }, 300);
  });
_x000D_
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
  <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>

  <link rel="stylesheet" href="style.css" />

</head>

<body>
  <h2 class='text-primary'>Another Great "KISS" Bootstrap Popover example!</h2>
  <p class='text-muted'>KISS = Keep It Simple S....</p>

  <p class='text-primary'>Goal:</p>
  <ul>
    <li>Open popover on hover event for the popover button</li>
    <li>Keep popover open when hovering over the popover box</li>
    <li>Close popover on mouseleave for either the popover button, or the popover box.</li>
  </ul>

  <button type="button" class="btn btn-danger pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME
    </button>
  <br><br>
  <button type="button" class="btn btn-info pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME... Again!
    </button><br><br>
  <button type="button" class="btn btn-success pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    Okay one more time... !
    </button>
  <br><br>
  <p class='text-info'>Hope that helps you... Drove me crazy for a while</p>
  <script src="script.js"></script>
</body>

</html>
_x000D_
_x000D_
_x000D_

Uninstall mongoDB from ubuntu

use sudo with the command:

sudo apt-get remove --purge mongodb  
apt-get autoremove --purge mongodb  

Proxy Error 502 : The proxy server received an invalid response from an upstream server

I had this issue once. It turned out to be database query issue. After re-create tables and index it has been fixed.

Although it says proxy error, when you look at server log, it shows execute query timeout. This is what I had before and how I solved it.

Is Laravel really this slow?

I found that biggest speed gain with Laravel 4 you can achieve choosing right session drivers;

Sessions "driver" file;

Requests per second:    188.07 [#/sec] (mean)
Time per request:       26.586 [ms] (mean)
Time per request:       5.317 [ms] (mean, across all concurrent requests)


Session "driver" database;

Requests per second:    41.12 [#/sec] (mean)
Time per request:       121.604 [ms] (mean)
Time per request:       24.321 [ms] (mean, across all concurrent requests)

Hope that helps

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

How do I get the path of the current executed file in Python?

My solution is:

import os
print(os.path.dirname(os.path.abspath(__file__)))

Delete multiple rows by selecting checkboxes using PHP

You should treat it as an array like this,

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">

Then only, you can take its count and loop it for deletion.

You also need to pass the database connection to the query.

$result = mysqli_query($dbc, $sql);

Yours did not include it:

$result = mysqli_query($sql);

How to install a package inside virtualenv?

I had the same issue and the --no-site-packages did not work for me. I discovered on this older mailing list archive that you are able to force an installation in the virtualenv using the -U flag for pip, eg pip -U ipython. You may verify this works using the bash command which ipython while in the virtualenv.

source: https://mail.python.org/pipermail/python-list/2010-March/571663.html

Using PHP with Socket.io

If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.

https://github.com/walkor/phpsocket.io

https://github.com/RickySu/phpsocket.io

Exmaple codes for the first repository like this.

use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
  $socket->on('chat message', function($msg)use($io){
    $io->emit('chat message', $msg);
  });
});

Why doesn't list have safe "get" method like dictionary?

This guy worked for me:

list_get = lambda l, x: l[x:x+1] and l[x] or 0

lambdas are great for one liner helper functions like this

Border color on default input style

If I understand your question correctly this should solve it:

http://jsfiddle.net/wvk2mnsf/

HTML - create a simple input field.

<input type="text" id="giraffe" />

CSS - clear out the native outline so you can set your own and it doesn't look weird with a bluey red outline.

input:focus {
    outline: none;
}
.error-input-border {
    border: 1px solid #FF0000;
}

JS - on typing in the field set red border class declared in the CSS

document.getElementById('giraffe').oninput = function() { this.classList.add('error-input-border'); }

This has a lot of information on the latest standards too: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

Including dependencies in a jar with Maven

There's the shade maven plugin. It can be used to package and rename dependencies (to omit dependency problems on the classpath).

Count unique values in a column in Excel

With the Dynamic Array formulas(as of this posting only available to Office 365 Insiders):

=COUNTA(UNIQUE(A:A))

Get all LI elements in array

You can get a NodeList to iterate through by using getElementsByTagName(), like this:

var lis = document.getElementById("navbar").getElementsByTagName("li");

You can test it out here. This is a NodeList not an array, but it does have a .length and you can iterate over it like an array.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

linux script to kill java process

You can simply use pkill -f like this:

pkill -f 'java -jar'

EDIT: To kill a particular java process running your specific jar use this regex based pkill command:

pkill -f 'java.*lnwskInterface'

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

What is the difference between baud rate and bit rate?

Bits per second is straightforward. It is exactly what it sounds like. If I have 1000 bits and am sending them at 1000 bps, it will take exactly one second to transmit them.

Baud is symbols per second. If these symbols — the indivisible elements of your data encoding — are not bits, the baud rate will be lower than the bit rate by the factor of bits per symbol. That is, if there are 4 bits per symbol, the baud rate will be ¼ that of the bit rate.

This confusion arose because the early analog telephone modems weren't very complicated, so bps was equal to baud. That is, each symbol encoded one bit. Later, to make modems faster, communications engineers invented increasingly clever ways to send more bits per symbol.¹

Analogy

System 1, bits: Imagine a communication system with a telescope on the near side of a valley and a guy on the far side holding up one hand or the other. Call his left hand "0" and his right hand "1," and you have a system for communicating one binary digit — one bit — at a time.

System 2, baud: Now imagine that the guy on the far side of the valley is holding up playing cards instead of his bare hands. He is using a subset of the cards, ace through 8 in each suit, for a total of 32 cards. Each card — each symbol — encodes 5 bits: 00000 through 11111 in binary.²

Analysis

The System 2 guy can convey 5 bits of information per card in the same time it takes the System 1 guy to convey one bit by revealing one of his bare hands.

You see how the analogy seems to break down: finding a particular card in a deck and showing it takes longer than simply deciding to show your left or right hand. But, that just provides an opportunity to extend the analogy profitably.

A communications system with many bits per symbol faces a similar difficulty, because the encoding schemes required to send multiple bits per symbol are much more complicated than those that send only one bit at a time. To extend the analogy, then, the guy showing playing cards could have several people behind him sharing the work of finding the next card in the deck, handing him cards as fast as he can show them. The helpers are analogous to the more powerful processors required to produce the many-bits-per-baud encoding schemes.

That is to say, by using more processing power, System 2 can send data 5 times faster than the more primitive System 1.

Historical Vignette

What shall we do with our 5-bit code? It seems natural to an English speaker to use 26 of the 32 available code points for the English alphabet. We can use the remaining 6 code points for a space character and a small set of control codes and symbols.

Or, we could just use Baudot code, a 5-bit code invented by Émile Baudot, after whom the unit "baud" was coined.³


Footnotes and Digressions:

  1. For example, the V.34 standard defined a 3,429 baud mode at 8.4 bits per symbol to achieve 28.8 kbit/sec throughput.

    That standard only talks about the POTS side of the modem. The RS-232 side remains a 1 bit per symbol system, so you could also correctly call it a 28.8k baud modem. Confusing, but technically correct.

  2. I've purposely kept things simple here.

    One thing you might think about is whether the absence of a playing card conveys information. If it does, that implies the existence of some clock or latch signal, so that you can tell the information-carrying absence of a card from the gap between the display of two cards.

    Also, what do you do with the cards left over in a poker deck, 9 through King, and the Jokers? One idea would be to use them as special flags to carry metadata. For example, you'll need a way to indicate a short trailing block. If you need to send 128 bits of information, you're going to need to show 26 cards. The first 25 cards convey 5×25=125 bits, with the 26th card conveying the trailing 3 bits. You need some way to signal that the last two bits in the symbol should be disregarded.

  3. This is why the early analog telephone modems were specified in terms of baud instead of bps: communications engineers had been using that terminology since the telegraph days. They weren't trying to confuse bps and baud; it was simply a fact, in their minds, that these modems were transmitting one bit per symbol.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

Does overflow:hidden applied to <body> work on iPhone Safari?

It does apply, but it only applies to certain elements within the DOM. for example, it won't work on a table, td, or some other elements, but it will work on a <DIV> tag.
eg:

<body>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

Only tested in iOS 4.3.

A minor edit: you may be better off using overflow:scroll so two finger-scrolling does work.

How to create a project from existing source in Eclipse and then find it?

If you creating a new project based on an existing Maven structure :

Create the project using a general project wizard and give the project the same name as just created.

If you try to create the project as a Maven project via m2e will receive an error that project/pom already exists.

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Accessing Objects in JSON Array (JavaScript)

Use a loop

for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

PHP GuzzleHttp. How to make a post request with params?

Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);

Request with POST files

$response = $client->request('POST', 'http://www.example.com/files/post', [
    'multipart' => [
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'csv_header',
            'contents' => 'First Name, Last Name, Username',
            'filename' => 'csv_header.csv'
        ]
    ]
]);

REST verbs usage with params

// PUT
$client->put('http://www.example.com/user/4', [
    'body' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    'timeout' => 5
]);

// DELETE
$client->delete('http://www.example.com/user');

Async POST data

Usefull for long server operations.

$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

Set headers

According to documentation, you can set headers :

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

More information for debugging

If you want more details information, you can use debug option like this :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    // If you want more informations during request
    'debug' => true
]);

Documentation is more explicits about new possibilities.

How to generate java classes from WSDL file

You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.

It creates the complete source files that you would need.

How to change Jquery UI Slider handle

If you should need to replace the handle with something else entirely, rather than just restyling it:

You can specify custom handle elements by creating and appending the elements and adding the ui-slider-handle class before initialization.

Working Example

_x000D_
_x000D_
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
  range: "min",_x000D_
  value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
  background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
  width: 14px;_x000D_
  height: 18px;_x000D_
  margin-left: -5px;_x000D_
  top: -4px;_x000D_
  border: none;_x000D_
  background: none;_x000D_
}_x000D_
.slider {_x000D_
  height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
_x000D_
_x000D_

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

C# string replace

You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:

string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));

StringBuilder builder = new StringBuilder(contents);

builder.Replace("[Name]", Name);

StringReader sr = new StringReader(builder.ToString());

Restoring MySQL database from physical files

I once copied these files to the database storage folder for a mysql database which was working, started the db and waited for it to "repair" the files, then extracted them with mysqldump.

Equals(=) vs. LIKE

The equals (=) operator is a "comparison operator compares two values for equality." In other words, in an SQL statement, it won't return true unless both sides of the equation are equal. For example:

SELECT * FROM Store WHERE Quantity = 200;

The LIKE operator "implements a pattern match comparison" that attempts to match "a string value against a pattern string containing wild-card characters." For example:

SELECT * FROM Employees WHERE Name LIKE 'Chris%';

LIKE is generally used only with strings and equals (I believe) is faster. The equals operator treats wild-card characters as literal characters. The difference in results returned are as follows:

SELECT * FROM Employees WHERE Name = 'Chris';

And

SELECT * FROM Employees WHERE Name LIKE 'Chris';

Would return the same result, though using LIKE would generally take longer as its a pattern match. However,

SELECT * FROM Employees WHERE Name = 'Chris%';

And

SELECT * FROM Employees WHERE Name LIKE 'Chris%';

Would return different results, where using "=" results in only results with "Chris%" being returned and the LIKE operator will return anything starting with "Chris".

Hope that helps. Some good info can be found here.

Primitive type 'short' - casting in Java

What language are you using?

Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

Rails - controller action name to string

This snippet works for Rails 3

class ReportsController < ApplicationController

  def summary
    logger.debug self.class.to_s + "." + self.action_name
  end

end

will print

. . .
ReportsController.summary
. . .

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

The probably shortest answer is

val==null || val==''

if you change rigth side to val==='' then empty array will give false. Proof

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val==null || val==''_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

More details about == (source here)

Enter image description here

BONUS: Reason why === is more clear than ==

Enter image description here

To write clear and easy understandable code, use explicite list of accepted values

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

Make a td fixed size (width,height) while rest of td's can expand

This will take care of the empty td:

<td style="min-width: 20px;"></td>

Checking for empty or null List<string>

What about using an extension method?

public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
  if (source != null && source.Any())
    return true;
  else
    return false;
}

How can you use optional parameters in C#?

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

How to create full path with node's fs.mkdirSync?

This version works better on Windows than the top answer because it understands both / and path.sep so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd).

/**
 * Creates a folder and if necessary, parent folders also. Returns true
 * if any folders were created. Understands both '/' and path.sep as 
 * path separators. Doesn't try to create folders that already exist,
 * which could cause a permissions error. Gracefully handles the race 
 * condition if two processes are creating a folder. Throws on error.
 * @param targetDir Name of folder to create
 */
export function mkdirSyncRecursive(targetDir) {
  if (!fs.existsSync(targetDir)) {
    for (var i = targetDir.length-2; i >= 0; i--) {
      if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
        mkdirSyncRecursive(targetDir.slice(0, i));
        break;
      }
    }
    try {
      fs.mkdirSync(targetDir);
      return true;
    } catch (err) {
      if (err.code !== 'EEXIST') throw err;
    }
  }
  return false;
}

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Send data through routing paths in Angular

In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-

this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});

but it showing some error like below:

Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
  Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'

.

Solution: we have to write like this:

this.Router.navigate(['componentname'],{state: {customerkey:response.key}});

How to change the display name for LabelFor in razor in mvc3?

You can change the labels' text by adorning the property with the DisplayName attribute.

[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }

Or, you could write the raw HTML explicitly:

<label for="SomekingStatus" class="control-label">Someking Status</label>

How can I tell when a MySQL table was last updated?

Not sure if this would be of any interest. Using mysqlproxy in between mysql and clients, and making use of a lua script to update a key value in memcached according to interesting table changes UPDATE,DELETE,INSERT was the solution which I did quite recently. If the wrapper supported hooks or triggers in php, this could have been eaiser. None of the wrappers as of now does this.

Error: Unexpected value 'undefined' imported by the module

I fix it by delete all index export file, include pipe, service. then all file import path is specific path. eg.

import { AuthService } from './_common/services/auth.service';

replace

import { AuthService } from './_common/services';

besides, don't export default class.

Why does JPA have a @Transient annotation?

In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.

example:

Im saving the Object to the database using the jpa repository built in save method as so:

userRoleJoinRepository.save(user2);

Convert a string to an enum in C#

BEWARE:

enum Example
{
    One = 1,
    Two = 2,
    Three = 3
}

Enum.(Try)Parse() accepts multiple, comma-separated arguments, and combines them with binary 'or' |. You cannot disable this and in my opinion you almost never want it.

var x = Enum.Parse("One,Two"); // x is now Three

Even if Three was not defined, x would still get int value 3. That's even worse: Enum.Parse() can give you a value that is not even defined for the enum!

I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.

Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.

I suggest the following:

    public static bool TryParse<T>(string value, out T result)
        where T : struct
    {
        var cacheKey = "Enum_" + typeof(T).FullName;

        // [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.
        // [Implementation off-topic.]
        var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);

        return enumDictionary.TryGetValue(value.Trim(), out result);
    }

    private static Dictionary<string, T> CreateEnumDictionary<T>()
    {
        return Enum.GetValues(typeof(T))
            .Cast<T>()
            .ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);
    }

.NET String.Format() to add commas in thousands place for a number

If you want culture specific, you might want to try this:

(19950000.0).ToString("N",new CultureInfo("en-US")) = 19,950,000.00

(19950000.0).ToString("N",new CultureInfo("is-IS")) = 19.950.000,00

Note: Some cultures use , to mean decimal rather than . so be careful.

Is it possible to break a long line to multiple lines in Python?

It works in Python too:

>>> 1+\
      2+\
3
6
>>> (1+
          2+
 3)
6

Is it possible to select the last n items with nth-child?

If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

$('ul li:nth-last-child(1)').addClass('last');

And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

log4j:WARN No appenders could be found for logger in web.xml

You may get this error when your log4j.properties are not present in the classpath.

This means you have to move the log4j.properties into the src folder and set the output to the bin folder so that at run time log4j.properties will read from the bin folder and your error will be resolved easily.

How to use OpenSSL to encrypt/decrypt files?

To Encrypt:

$ openssl bf < arquivo.txt > arquivo.txt.bf

To Decrypt:

$ openssl bf -d < arquivo.txt.bf > arquivo.txt

bf === Blowfish in CBC mode

Access images inside public folder in laravel

Just use public_path() it will find public folder and address it itself.

<img src=public_path().'/images/imagename.jpg' >

Setting selected option in laravel form

use this package and check the docs:

https://laravelcollective.com/docs/5.2/html#drop-down-lists

form you html , you need use this mark

{!! Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S'); !!}

Ignore self-signed ssl cert using Jersey Client

For Jersey 2.* (Tested on 2.7) and java 8:

import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager; 

public static Client ignoreSSLClient() throws Exception {

    SSLContext sslcontext = SSLContext.getInstance("TLS");

    sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
    }}, new java.security.SecureRandom());

    return ClientBuilder.newBuilder()
                        .sslContext(sslcontext)
                        .hostnameVerifier((s1, s2) -> true)
                        .build();
}

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

How to find server name of SQL Server Management Studio

There are many ways mentioned above. But I use rather simple way (well not simple as SELECT @@SERVERNAME). When you start SQL server management studio you will prompt below GUI

enter image description here

In there Server name is your server name (There may have multiple servers according to you dev environment choose correct one). Hope this helps :)

HTML5 textarea placeholder not appearing

I know this post has been (very well) answered by Aquarelle but just in case somebody is having this issue with other tag forms with no text such as inputs i'll leave this here:

If you have an input in your form and placeholder is not showing because a white space at the beginning, this may be caused for you "value" attribute. In case you are using variables to fill the value of an input check that there are no white spaces between the commas and the variables.

example using twig for php framework symfony :

<input type="text" name="subject" value="{{ subject }}" placeholder="hello" />       <-- this is ok
<input type="text" name="subject" value" {{ subject }} " placeholder="hello" />      <-- this will not show placeholder 

In this case the tag between {{ }} is the variable, just make sure you are not leaving spaces between the commas because white space is also a valid character.

Convert timedelta to total seconds

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

Python's most efficient way to choose longest string in list?

def LongestEntry(lstName):
  totalEntries = len(lstName)
  currentEntry = 0
  longestLength = 0
  while currentEntry < totalEntries:
    thisEntry = len(str(lstName[currentEntry]))
    if int(thisEntry) > int(longestLength):
      longestLength = thisEntry
      longestEntry = currentEntry
    currentEntry += 1
  return longestLength

best way to get the key of a key/value javascript object

Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr1 = Object.keys(obj);

Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr2 = Object.values(obj);

For more please go here

How best to determine if an argument is not sent to the JavaScript function

Why not using the !! operator? This operator, placed before the variable, turn it to a boolean (if I've understood well), so !!undefined and !!null (and even !!NaN, which can be quite interesting) will return false.

Here is an exemple:

function foo(bar){
    console.log(!!bar);
}

foo("hey") //=> will log true

foo() //=> will log false

upstream sent too big header while reading response header from upstream

upstream sent too big header while reading response header from upstream is nginx's generic way of saying "I don't like what I'm seeing"

  1. Your upstream server thread crashed
  2. The upstream server sent an invalid header back
  3. The Notice/Warnings sent back from STDERR overflowed their buffer and both it and STDOUT were closed

3: Look at the error logs above the message, is it streaming with logged lines preceding the message? PHP message: PHP Notice: Undefined index: Example snippet from a loop my log file:

2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
... // 20 lines of same
PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undef
2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "ta_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Firstname

you can see in the 3rd line from the bottom that the buffer limit was hit, broke, and the next thread wrote in over it. Nginx then closed the connection and returned 502 to the client.

2: log all the headers sent per request, review them and make sure they conform to standards (nginx does not permit anything older than 24 hours to delete/expire a cookie, sending invalid content length because error messages were buffered before the content counted...). getallheaders function call can usually help out in abstracted code situations php get all headers

examples include:

<?php
//expire cookie
setcookie ( 'bookmark', '', strtotime('2012-01-01 00:00:00') );
// nginx will refuse this header response, too far past to accept
....
?>

and this:

<?php
header('Content-type: image/jpg');
?>

<?php   //a space was injected into the output above this line
header('Content-length: ' . filesize('image.jpg') );
echo file_get_contents('image.jpg');
// error! the response is now 1-byte longer than header!!
?>

1: verify, or make a script log, to ensure your thread is reaching the correct end point and not exiting before completion.

Calling virtual functions inside constructors

Other answers have already explained why virtual function calls don't work as expected when called from a constructor. I'd like to instead propose another possible work around for getting polymorphic-like behavior from a base type's constructor.

By adding a template constructor to the base type such that the template argument is always deduced to be the derived type it's possible to be aware of the derived type's concrete type. From there, you can call static member functions for that derived type.

This solution does not allow non-static member functions to be called. While execution is in the base type's constructor, the derived type's constructor hasn't even had time to go through it's member initialization list. The derived type portion of the instance being created hasn't begun being initialized it. And since non-static member functions almost certainly interact with data members it would be unusual to want to call the derived type's non-static member functions from the base type's constructor.

Here is a sample implementation :

#include <iostream>
#include <string>

struct Base {
protected:
    template<class T>
    explicit Base(const T*) : class_name(T::Name())
    {
        std::cout << class_name << " created\n";
    }

public:
    Base() : class_name(Name())
    {
        std::cout << class_name << " created\n";
    }


    virtual ~Base() {
        std::cout << class_name << " destroyed\n";
    }

    static std::string Name() {
        return "Base";
    }

private:
    std::string class_name;
};


struct Derived : public Base
{   
    Derived() : Base(this) {} // `this` is used to allow Base::Base<T> to deduce T

    static std::string Name() {
        return "Derived";
    }
};

int main(int argc, const char *argv[]) {

    Derived{};  // Create and destroy a Derived
    Base{};     // Create and destroy a Base

    return 0;
}

This example should print

Derived created
Derived destroyed
Base created
Base destroyed

When a Derived is constructed, the Base constructor's behavior depends on the actual dynamic type of the object being constructed.

C# ListView Column Width Auto

I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:

Creating Event Handlers on the Windows Forms Designer

Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:

  1. Click the form or control that you want to create an event handler for.
  2. In the Properties window, click the Events button
  3. In the list of available events, click the event that you want to create an event handler for.
  4. In the box to the right of the event name, type the name of the handler and press ENTER