Programs & Examples On #Acm.graphics

If using maven, usually you put log4j.properties under java or resources?

Just putting it in src/main/resources will bundle it inside the artifact. E.g. if your artifact is a JAR, you will have the log4j.properties file inside it, losing its initial point of making logging configurable.

I usually put it in src/main/resources, and set it to be output to target like so:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${project.build.directory}</targetPath>
            <includes>
                <include>log4j.properties</include>
            </includes>
        </resource>
    </resources>
</build>

Additionally, in order for log4j to actually see it, you have to add the output directory to the class path. If your artifact is an executable JAR, you probably used the maven-assembly-plugin to create it. Inside that plugin, you can add the current folder of the JAR to the class path by adding a Class-Path manifest entry like so:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.your-package.Main</mainClass>
            </manifest>
            <manifestEntries>
                <Class-Path>.</Class-Path>
            </manifestEntries>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Now the log4j.properties file will be right next to your JAR file, independently configurable.

To run your application directly from Eclipse, add the resources directory to your classpath in your run configuration: Run->Run Configurations...->Java Application->New select the Classpath tab, select Advanced and browse to your src/resources directory.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

Wait until a process ends

Like Jon Skeet says, use the Process.Exited:

proc.StartInfo.FileName = exportPath + @"\" + fileExe;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inProcess = true;

while (inProcess)
{
    proc.Refresh();
    System.Threading.Thread.Sleep(10);
    if (proc.HasExited)
    {
        inProcess = false;
    }
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
    inProcess = false;
    Console.WriteLine("Exit time:    {0}\r\n" +
      "Exit code:    {1}\r\n", proc.ExitTime, proc.ExitCode);
}

Stopword removal with NLTK

There is an in-built stopword list in NLTK made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html

>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop] 
['foo', 'bar', 'sentence']

I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for linux and specifically Ubuntu 20:04. First ensure you have Java installed before proceeding:

1. java -version
2. sudo apt-get update
3. sudo apt-get install openjdk-8-jdk

Open .bashrc

vim $HOME/.bashrc 

Set Java environment variables.

export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export JRE_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre"

Visit Gradle's website and identify the version you would like to install. Replace version 6.5.1 with the version number you would like to install.

 1. sudo apt-get update
 2. cd /tmp && curl -L -O https://services.gradle.org/distributions/gradle-6.5.1-bin.zip
 3. sudo mkdir /opt/gradle
 4. sudo unzip -d /opt/gradle /tmp/gradle-6.5.1-bin.zip

To setup Gradle's environment variables use nano or vim or gedit editors to create a new file:

sudo vim /etc/profile.d/gradle.sh

Add the following lines to gradle.sh

export GRADLE_HOME="/opt/gradle/gradle-6.5.1/"
export PATH=${GRADLE_HOME}/bin:${PATH}

Run the following commands to make gradle.sh executable and to update your bash terminal with the environment variables you set as well as check the installed version.

1. sudo chmod +x /etc/profile.d/gradle.sh
3. source /etc/profile.d/gradle.sh
4. gradle -v

Using FFmpeg in .net?

You can use this nuget package:

Install-Package Xabe.FFmpeg

I'm trying to make easy to use, cross-platform FFmpeg wrapper.

You can find more information about this at Xabe.FFmpeg

More info in documentation

Conversion is simple:

IConversionResult result = await Conversion.ToMp4(Resources.MkvWithAudio, output).Start();

What port is a given program using?

You may already have Process Explorer (from Sysinternals, now part of Microsoft) installed. If not, go ahead and install it now -- it's just that cool.

In Process Explorer: locate the process in question, right-click and select the TCP/IP tab. It will even show you, for each socket, a stack trace representing the code that opened that socket.

How to get textLabel of selected row in swift?

This will work:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!

When is layoutSubviews called?

I tracked the solution down to Interface Builder's insistence that springs cannot be changed on a view that has the simulated screen elements turned on (status bar, etc.). Since the springs were off for the main view, that view could not change size and hence was scrolled down in its entirety when the in-call bar appeared.

Turning the simulated features off, then resizing the view and setting the springs correctly caused the animation to occur and my method to be called.

An extra problem in debugging this is that the simulator quits the app when the in-call status is toggled via the menu. Quit app = no debugger.

require is not defined? Node.js

To supplement what everyone else has said above, your js file is being read on the client side when you have a path to it in your HTML file. At least that was the problem for me. I had it as a script in my tag in my index.html Hope this helps!

What does %w(array) mean?

Instead of %w() we should use %w[]

According to Ruby style guide:

Prefer %w to the literal array syntax when you need an array of words (non-empty strings without spaces and special characters in them). Apply this rule only to arrays with two or more elements.

# bad
STATES = ['draft', 'open', 'closed']

# good
STATES = %w[draft open closed]

Use the braces that are the most appropriate for the various kinds of percent literals.

[] for array literals(%w, %i, %W, %I) as it is aligned with the standard array literals.

# bad
%w(one two three)
%i(one two three)

# good
%w[one two three]
%i[one two three]

For more read here.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

How can I get enum possible values in a MySQL database?

I have a codeigniter version for you. It also strips the quotes from the values.

function get_enum_values( $table, $field )
{
    $type = $this->db->query( "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'" )->row( 0 )->Type;
    preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
    $enum = explode("','", $matches[1]);
    return $enum;
}

Add alternating row color to SQL Server Reporting services report

My matrix data had missing values in it, so I wasn't able to get ahmad's solution to work, but this solution worked for me

Basic idea is to create a child group and field on your innermost group containing the color. Then set the color for each cell in the row based on that field's value.

How to keep the spaces at the end and/or at the beginning of a String?

use "" with the string resource value.

Example :

<string>"value with spaces"</string>

OR

use \u0020 code for spaces.

Pygame Drawing a Rectangle

Have you tried this:

PyGame Drawing Basics

Taken from the site:

pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

It stands for Java Naming and Directory Interface.

What is its basic use?

JNDI allows distributed applications to look up services in an abstract, resource-independent way.

When it is used?

The most common use case is to set up a database connection pool on a Java EE application server. Any application that's deployed on that server can gain access to the connections they need using the JNDI name java:comp/env/FooBarPool without having to know the details about the connection.

This has several advantages:

  1. If you have a deployment sequence where apps move from devl->int->test->prod environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don't have to change as they migrate between environments.
  2. You can minimize the number of folks who need to know the credentials for accessing a production database. Only the Java EE app server needs to know if you use JNDI.

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

jQuery remove options from select

When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)

$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I was also facing the same issue when I was trying to get JPA entity manager configured in Tomcat 8. First I has an issue with the SystemException class not being found and hence the entityManagerFactory was not being created. I removed the hibernate entity manager dependency and then my entityManagerFactory was not able to lookup for the persistence provider. After going thru a lot of research and time got to know that hibernate entity manager is must to lookup for some configuration. Then put back the entity manager jar and then added JTA Api as a dependency and it worked fine.

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Deny all, allow only one IP through htaccess

You can have more than one IP or even some other kind of allow like user, hostname, ... more info here https://www.askapache.com/htaccess/setenvif/

SetEnvIf remote_addr ^123.123.123.1$ allowedip=1
SetEnvIf remote_addr ^123.123.123.2$ allowedip=1
SetEnvIf remote_addr ^123.123.123.3$ allowedip=1
SetEnvIf remote_addr ^123.123.123.4$ allowedip=1

Order deny,allow
deny from all
allow from env=allowedip

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Git resolve conflict using --ours/--theirs for all files

Just grep through the working directory and send the output through the xargs command:

grep -lr '<<<<<<<' . | xargs git checkout --ours

or

grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')

the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.

The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs

More at this link.

Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.

This method should work through at least Git versions 2.4.x

Disable all table constraints in Oracle

It's not a single command, but here's how I do it. The following script has been designed to run in SQL*Plus. Note, I've purposely written this to only work within the current schema.

set heading off

spool drop_constraints.out

select
    'alter table ' || 
    owner || '.' || 
    table_name || 
    ' disable constraint ' || -- or 'drop' if you want to permanently remove
    constraint_name || ';'
from
    user_constraints;

spool off

set heading on

@drop_constraints.out

To restrict what you drop, filter add a where clause to the select statement:-

  • filter on constraint_type to drop only particular types of constraints
  • filter on table_name to do it only for one or a few tables.

To run on more than the current schema, modify the select statement to select from all_constraints rather than user_constraints.

Note - for some reason I can't get the underscore to NOT act like an italicization in the previous paragraph. If someone knows how to fix it, please feel free to edit this answer.

How to remove unused imports in Intellij IDEA on commit?

In mac book

IntelliJ

Control + Option + o (not a zero, letter "o")

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

Using find command in bash script

If you want to loop over what you "find", you should use this:

find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
done

Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

How can I debug my JavaScript code?

Start with Firebug and IE Debugger.

Be careful with debuggers in JavaScript though. Every once in a while they will affect the environment just enough to cause some of the errors you are trying to debug.

Examples:

For Internet Explorer, it's generally a gradual slowdown and is some kind of memory leak type deal. After a half hour or so I need to restart. It seems to be fairly regular.

For Firebug, it's probably been more than a year so it may have been an older version. As a result, I don't remember the specifics, but basically the code was not running correctly and after trying to debug it for a while I disabled Firebug and the code worked fine.

Call a function after previous function is complete

This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.

Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable).then(function() {
            //this function is executed after function1
            function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
    return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
    });
} 

This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:

function1(someVariable).then(function() {
    function2(someOtherVariable);
}).then(function() {
    function3();
});

You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):

Promise.resolve($.ajax(...params...)).then(function(result) {
    //whatever you want to do after the request
});

As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:

$.ajax(...params...).then(function(result) {
    //whatever you want to do after the request
});

How to remove focus from single editText

I know is too late, but for somebody whit the same need editText.setFocusable(false) si what you are looking for.

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

Detect if the device is iPhone X

How to detect iOS device models and screen size?

CheckDevice is detected the current ? device model and screen sizes.

You can also use

CheckDevice.size() returned for iPhone 12 mini's .screen5_4Inch

etc... maybe...

CheckDevice.isPhone()

to check the device type iPhone.

CheckDevice.isWatch()

CheckDevice.isSimulator()

CheckDevice.isPad()

Great repo

CheckDevice https://github.com/ugurethemaydin/CheckDevice

How To: Best way to draw table in console app (C#)

public static void ToPrintConsole(this DataTable dataTable)
    {
        // Print top line
        Console.WriteLine(new string('-', 75));

        // Print col headers
        var colHeaders = dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName);
        foreach (String s in colHeaders)
        {
            Console.Write("| {0,-20}", s);
        }
        Console.WriteLine();

        // Print line below col headers
        Console.WriteLine(new string('-', 75));

        // Print rows
        foreach (DataRow row in dataTable.Rows)
        {
            foreach (Object o in row.ItemArray)
            {
                Console.Write("| {0,-20}", o.ToString());
            }
            Console.WriteLine();
        }

        // Print bottom line
        Console.WriteLine(new string('-', 75));
    }

How to use <DllImport> in VB.NET?

I know this has already been answered, but here is an example for the people who are trying to use SQL Server Types in a vb project:

            Imports System
            Imports System.IO
            Imports System.Runtime.InteropServices

            Namespace SqlServerTypes
                Public Class Utilities



                    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
                    Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr

                    End Function

                    Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
                        Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
                        LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
                        LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
                    End Sub

                    Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
                        Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
                        Dim ptr = LoadLibrary(path)

                        If ptr = IntPtr.Zero Then
                            Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
                        End If
                    End Sub
                End Class
            End Namespace

Pass variables by reference in JavaScript

Putting aside the pass-by-reference discussion, those still looking for a solution to the stated question could use:

const myArray = new Array(var1, var2, var3);
myArray.forEach(var => var = makePretty(var));

CASCADE DELETE just once

I cannot comment Palehorse's answer so I added my own answer. Palehorse's logic is ok but efficiency can be bad with big data sets.

DELETE FROM some_child_table sct 
 WHERE exists (SELECT FROM some_Table st 
                WHERE sct.some_fk_fiel=st.some_id);

DELETE FROM some_table;

It is faster if you have indexes on columns and data set is bigger than few records.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

this worked for me.

    $('#thedate').datepicker({
    dateFormat: 'dd-mm-yy',
    altField: '#thealtdate',
    altFormat: 'yy-mm-dd'
});

Alternate background colors for list items

If you use the jQuery solution it will work on IE8:

jQuery

$(document).ready(function(){
$('#myList li:nth-child(odd)').addClass('alternate');
});

CSS

.alternate {
background: black;
}

If you use the CSS soloution it won't work on IE8:

li:nth-child(odd) {
    background: black;
}

Why doesn't Mockito mock static methods?

I seriously do think that it is code smell if you need to mock static methods, too.

  • Static methods to access common functionality? -> Use a singleton instance and inject that
  • Third party code? -> Wrap it into your own interface/delegate (and if necessary make it a singleton, too)

The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies. I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)

PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

Maximum number of records in a MySQL database table

There is no limit. It only depends on your free memory and system maximum file size. But that doesn't mean you shouldn't take precautionary measure in tackling memory usage in your database. Always create a script that can delete rows that are out of use or that will keep total no of rows within a particular figure, say a thousand.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

Simulate string split function in Excel formula

=IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)

This will firstly check if the cell contains a space, if it does it will return the first value from the space, otherwise it will return the cell value.

Edit

Just to add to the above formula, as it stands if there is no value in the cell it would return 0. If you are looking to display a message or something to tell the user it is empty you could use the following:

=IF(IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)=0, "Empty", IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3))

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

How do I declare an array variable in VBA?

You have to declare the array variable as an array:

Dim test(10) As Variant

Strings in C, how to get subString

char* someString = "abcdedgh";
char* otherString = 0;

otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;

UPDATE:
Tip: A good way to understand definitions is called the right-left rule (some links at the end):

Start reading from identifier and say aloud => "someString is..."
Now go to right of someString (statement has ended with a semicolon, nothing to say).
Now go left of identifier (* is encountered) => so say "...a pointer to...".
Now go to left of "*" (the keyword char is found) => say "..char".
Done!

So char* someString; => "someString is a pointer to char".

Since a pointer simply points to a certain memory address, it can also be used as the "starting point" for an "array" of characters.

That works with anything .. give it a go:

char* s[2]; //=> s is an array of two pointers to char
char** someThing; //=> someThing is a pointer to a pointer to char.
//Note: We look in the brackets first, and then move outward
char (* s)[2]; //=> s is a pointer to an array of two char

Some links: How to interpret complex C/C++ declarations and How To Read C Declarations

How to create a Custom Dialog box in android?

Create custom alert layout custom_aler_update.xml

Then Copy this code to Activity :

AlertDialog basic_reg;
AlertDialog.Builder builder ;
builder = new AlertDialog.Builder(ct, R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = ((Activity) ct).getLayoutInflater();
View v = inflater.inflate(R.layout.custom_aler_update, null);
builder.setView(v);
builder.setCancelable(false);
builder.create();
basic_reg = builder.show();

Copy this code to style :

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorPrimary">@color/primaryTextColor</item>
    <item name="android:background">@color/white</item>
</style>

Converting Select results into Insert script - SQL Server

You can use this Q2C.SSMSPlugin, which is free and open source. You can right click and select "Execute Query To Command... -> Query To Insert...". Enjoy)

How to throw std::exceptions with variable messages?

Ran into a similar issue, in that creating custom error messages for my custom exceptions make ugly code. This was my solution:

class MyRunTimeException: public std::runtime_error
{
public:
      MyRunTimeException(const std::string &filename):std::runtime_error(GetMessage(filename)) {}
private:
      static std::string GetMessage(const std::string &filename)
     {
           // Do your message formatting here. 
           // The benefit of returning std::string, is that the compiler will make sure the buffer is good for the length of the constructor call
           // You can use a local std::ostringstream here, and return os.str()
           // Without worrying that the memory is out of scope. It'll get copied
           // You also can create multiple GetMessage functions that take all sorts of objects and add multiple constructors for your exception
     }
}

This separates the logic for creating the messages. I had originally thought about overriding what(), but then you have to capture your message somewhere. std::runtime_error already has an internal buffer.

How to match all occurrences of a regex

You can use string.scan(your_regex).flatten. If your regex contains groups, it will return in a single plain array.

string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]

Regex can be a named group as well.

string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten

You can also use gsub, it's just one more way if you want MatchData.

str.gsub(/\d/).map{ Regexp.last_match }

How to find good looking font color if background color is known?

In a recent application that I made, I used the inverted colors. With the r,g and b values in hand, just calculate (in this example, the color range varies from 0 to 255) :

r = 127-(r-127) and so on.

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

What should be the sizeof(int) on a 64-bit machine?

Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.

Integration Testing POSTing an entire object to Spring MVC controller

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

Implementing a Custom Error page on an ASP.Net website

Is it a spelling error in your closing tag ie:

</CustomErrors> instead of </CustomError>?

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

Remove Datepicker Function dynamically

This is the solution I use. It has more lines but it will only create the datepicker once.

$('#txtSearch').datepicker({
    constrainInput:false,
    beforeShow: function(){
        var t = $('#ddlSearchType').val();
        if( ['Required Date', 'Submitted Date'].indexOf(t) ) {
            $('#txtSearch').prop('readonly', false);
            return false;
        }
        else $('#txtSearch').prop('readonly', true);
    }
});

The datepicker will not show unless the value of ddlSearchType is either "Required Date" or "Submitted Date"

Unicode character for "X" cancel / close?

? works really well. The HTML code is &#10006;.

An alternative is &#x2715: ?

What are the lesser known but useful data structures?

Bootstrapped skew-binomial heaps by Gerth Stølting Brodal and Chris Okasaki:

Despite their long name, they provide asymptotically optimal heap operations, even in a function setting.

  • O(1) size, union, insert, minimum
  • O(log n) deleteMin

Note that union takes O(1) rather than O(log n) time unlike the more well-known heaps that are commonly covered in data structure textbooks, such as leftist heaps. And unlike Fibonacci heaps, those asymptotics are worst-case, rather than amortized, even if used persistently!

There are multiple implementations in Haskell.

They were jointly derived by Brodal and Okasaki, after Brodal came up with an imperative heap with the same asymptotics.

Get only the date in timestamp in mysql

$date= new DateTime($row['your_date']) ;  
echo $date->format('Y-m-d');

wget ssl alert handshake failure

Below command for download files from TLSv1.2 website.

curl -v --tlsv1.2 https://example.com/filename.zip

It`s worked!

how to convert object to string in java

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

Check if list contains element that contains a string and get that element

To keep it simple use this;

foreach(string item in myList)//Iterate through each item.
{
 if(item.Contains("Search Term")//True if the item contains search pattern.
 {
   return item;//Return the matched item.
 }
}

Alternatively,to do this with for loop,use this;

    for (int iterator = 0; iterator < myList.Count; iterator++)
    {
        if (myList[iterator].Contains("String Pattern"))
        {
            return myList[iterator];
        }
    }

Extract MSI from EXE

Starting with parameter:

setup.exe /A

asks for saving included files (including MSI).

This may depend on the software which created the setup.exe.

Custom Adapter for List View

check this link, in very simple via the convertView, we can get the layout of a row which will be displayed in listview (which is the parentView).

View v = convertView;

if (v == null) {

    LayoutInflater vi;
    vi = LayoutInflater.from(getContext());
    v = vi.inflate(R.layout.itemlistrow, null);

}

using the position, you can get the objects of the List<Item>.

Item p = items.get(position);

after that we'll have to set the desired details of the object to the identified form widgets.

if (p != null) {

    TextView tt = (TextView) v.findViewById(R.id.id);
    TextView tt1 = (TextView) v.findViewById(R.id.categoryId);
    TextView tt3 = (TextView) v.findViewById(R.id.description);

    if (tt != null) {
        tt.setText(p.getId());
    }
    if (tt1 != null) {

        tt1.setText(p.getCategory().getId());
    }
    if (tt3 != null) {

        tt3.setText(p.getDescription());
    }
}

then it will return the constructed view which will be attached to the parentView (which is a ListView/GridView).

'typeid' versus 'typeof' in C++

C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.

typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.

Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.

Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

HTML table headers always visible at top of window when viewing a large table

It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:

<table width="80%">

 <thead>

 <tr>
  <th>Column 1</th>
  <th>Column 2</th>
  <th>Column 3</th>
 </tr>

 </thead>

 <tbody style="height:50px; overflow:auto">

  <tr>
    <td>Cell A1</td>
    <td>Cell B1</td>
    <td>Cell C1</td>
  </tr>

  <tr>
    <td>Cell A2</td>
    <td>Cell B2</td>
    <td>Cell C2</td>
  </tr>

  <tr>
    <td>Cell A3</td>
    <td>Cell B3</td>
    <td>Cell C3</td>
  </tr>

 </tbody>

</table>

asp.net: How can I remove an item from a dropdownlist?

You can use the

myDropDown.Items.Remove(ListItem li);

or

myDropDown.Items.RemoveAt(int index);

to remove it using C#.

git rebase fatal: Needed a single revision

I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream

How to format string to money

Parse to your string to a decimal first.

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

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

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had this same problem when trying to upgrade pm2 to the latest version.

Thanks to sdm's answer I did npm update npm -g and it did the trick for me.

Python, how to check if a result set is empty?

You can do like this :

count = 0
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=serverName;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute(SQL query)
for row in cursor:
    count = 1
    if true condition:
        print("True")
    else:
        print("False")
if count == 0:
    print("No Result")

Thanks :)

How to use wget in php?

To run wget command in PHP you have to do following steps :

1) Allow apache server to use wget command by adding it in sudoers list.

2) Check "exec" function enabled or exist in your PHP config.

3) Run "exec" command as root user i.e. sudo user

Below code sample as per ubuntu machine

#Add apache in sudoers list to use wget command
~$ sudo nano /etc/sudoers
#add below line in the sudoers file
www-data ALL=(ALL) NOPASSWD: /usr/bin/wget


##Now in PHP file run wget command as 
exec("/usr/bin/sudo wget -P PATH_WHERE_WANT_TO_PLACE_FILE URL_OF_FILE");

How to access JSON decoded array in PHP

$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];

Just like this :)

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

Android Studio how to run gradle sync manually?

Shortcut (Ubuntu, Windows):

Ctrl + F5

Will sync the project with Gradle files.

How to name and retrieve a stash by name in git?

I don't think there is a way to git pop a stash by its name.

I have created a bash function that does it.

#!/bin/bash

function gstashpop {
  IFS="
"
  [ -z "$1" ] && { echo "provide a stash name"; return; }
  index=$(git stash list | grep -e ': '"$1"'$' | cut -f1 -d:)
  [ "" == "$index" ] && { echo "stash name $1 not found"; return; }
  git stash apply "$index"
}

Example of usage:

[~/code/site] on master*
$ git stash push -m"here the stash name"
Saved working directory and index state On master: here the stash name

[~/code/site] on master
$ git stash list
stash@{0}: On master: here the stash name

[~/code/site] on master
$ gstashpop "here the stash name"

I hope it helps!

Android on-screen keyboard auto popping up

You can add the single line of code in Android Mainfest.xml under activity tag

 <activity
        android:name="com.sams.MainActivity"
        android:windowSoftInputMode="stateVisible" >
 </activity>

this may helps you.

How to extract one column of a csv file

I needed proper CSV parsing, not cut / awk and prayer. I'm trying this on a mac without csvtool, but macs do come with ruby, so you can do:

echo "require 'csv'; CSV.read('new.csv').each {|data| puts data[34]}" | ruby

How to capitalize the first letter in a String in Ruby

Below is another way to capitalize each word in a string. \w doesn't match Cyrillic characters or Latin characters with diacritics but [[:word:]] does. upcase, downcase, capitalize, and swapcase didn't apply to non-ASCII characters until Ruby 2.4.0 which was released in 2016.

"aAa-BBB ä ????? _a a_a".gsub(/\w+/,&:capitalize)
=> "Aaa-Bbb ä ????? _a A_a"
"aAa-BBB ä ????? _a a_a".gsub(/[[:word:]]+/,&:capitalize)
=> "Aaa-Bbb Ä ????? _a A_a"

[[:word:]] matches characters in these categories:

Ll (Letter, Lowercase)
Lu (Letter, Uppercase)
Lt (Letter, Titlecase)
Lo (Letter, Other)
Lm (Letter, Modifier)
Nd (Number, Decimal Digit)
Pc (Punctuation, Connector)

[[:word:]] matches all 10 of the characters in the "Punctuation, Connector" (Pc) category:

005F _ LOW LINE
203F ? UNDERTIE
2040 ? CHARACTER TIE
2054 ? INVERTED UNDERTIE
FE33 ? PRESENTATION FORM FOR VERTICAL LOW LINE
FE34 ? PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
FE4D ? DASHED LOW LINE
FE4E ? CENTRELINE LOW LINE
FE4F ? WAVY LOW LINE
FF3F _ FULLWIDTH LOW LINE

This is another way to only convert the first character of a string to uppercase:

"striNG".sub(/./,&:upcase)
=> "StriNG"

Persistent invalid graphics state error when using ggplot2

I solved this by clearing all the plots in the console and then making sure the plot area was large enough to accommodate what I was creating.

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

"CSV file does not exist" for a filename with embedded quotes

Just referring to the filename like

df = pd.read_csv("FBI-CRIME11.csv")

generally only works if the file is in the same directory as the script.

If you are using windows, make sure you specify the path to the file as follows:

PATH = "C:\\Users\\path\\to\\file.csv"

Extract directory path and filename

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How to get only time from date-time C#

if you are using gridview then you can show only the time with DataFormatString="{0:t}" example:

    By bind the value:-
<asp:Label ID="lblreg" runat="server" Text='<%#Eval("Registration_Time ", "{0:t}") %>'></asp:Label>

By bound filed:-
<asp:BoundField DataField=" Registration_Time" HeaderText="Brithday" SortExpression=" Registration Time " DataFormatString="{0:t}"/>

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

Javascript: console.log to html

A little late to the party, but I took @Hristiyan Dodov's answer a bit further still.

All console methods are now rewired and in case of overflowing text, an optional autoscroll to bottom is included. Colors are now based on the logging method rather than the arguments.

_x000D_
_x000D_
rewireLoggingToElement(_x000D_
    () => document.getElementById("log"),_x000D_
    () => document.getElementById("log-container"), true);_x000D_
_x000D_
function rewireLoggingToElement(eleLocator, eleOverflowLocator, autoScroll) {_x000D_
    fixLoggingFunc('log');_x000D_
    fixLoggingFunc('debug');_x000D_
    fixLoggingFunc('warn');_x000D_
    fixLoggingFunc('error');_x000D_
    fixLoggingFunc('info');_x000D_
_x000D_
    function fixLoggingFunc(name) {_x000D_
        console['old' + name] = console[name];_x000D_
        console[name] = function(...arguments) {_x000D_
            const output = produceOutput(name, arguments);_x000D_
            const eleLog = eleLocator();_x000D_
_x000D_
            if (autoScroll) {_x000D_
                const eleContainerLog = eleOverflowLocator();_x000D_
                const isScrolledToBottom = eleContainerLog.scrollHeight - eleContainerLog.clientHeight <= eleContainerLog.scrollTop + 1;_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
                if (isScrolledToBottom) {_x000D_
                    eleContainerLog.scrollTop = eleContainerLog.scrollHeight - eleContainerLog.clientHeight;_x000D_
                }_x000D_
            } else {_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
            }_x000D_
_x000D_
            console['old' + name].apply(undefined, arguments);_x000D_
        };_x000D_
    }_x000D_
_x000D_
    function produceOutput(name, args) {_x000D_
        return args.reduce((output, arg) => {_x000D_
            return output +_x000D_
                "<span class=\"log-" + (typeof arg) + " log-" + name + "\">" +_x000D_
                    (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) +_x000D_
                "</span>&nbsp;";_x000D_
        }, '');_x000D_
    }_x000D_
}_x000D_
_x000D_
_x000D_
setInterval(() => {_x000D_
  const method = (['log', 'debug', 'warn', 'error', 'info'][Math.floor(Math.random() * 5)]);_x000D_
  console[method](method, 'logging something...');_x000D_
}, 200);
_x000D_
#log-container { overflow: auto; height: 150px; }_x000D_
_x000D_
.log-warn { color: orange }_x000D_
.log-error { color: red }_x000D_
.log-info { color: skyblue }_x000D_
.log-log { color: silver }_x000D_
_x000D_
.log-warn, .log-error { font-weight: bold; }
_x000D_
<div id="log-container">_x000D_
  <pre id="log"></pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android camera intent

Try the following I found Here's a link

If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.

EasyImage.openCamera(Activity activity, int type);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
        @Override
        public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
            //Some error handling
        }

        @Override
        public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
            //Handle the images
            onPhotosReturned(imagesFiles);
        }
    });
}

Get the full URL in PHP

Try this:

print_r($_SERVER);

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

Is it necessary to write HEAD, BODY and HTML tags?

The Google Style Guide for HTML recommends omitting all optional tags.
That includes <html>, <head>, <body>, <p> and <li>.

https://google.github.io/styleguide/htmlcssguide.html#Optional_Tags

For file size optimization and scannability purposes, consider omitting optional tags. The HTML5 specification defines what tags can be omitted.

(This approach may require a grace period to be established as a wider guideline as it’s significantly different from what web developers are typically taught. For consistency and simplicity reasons it’s best served omitting all optional tags, not just a selection.)

<!-- Not recommended -->
<!DOCTYPE html>
<html>
  <head>
    <title>Spending money, spending bytes</title>
  </head>
  <body>
    <p>Sic.</p>
  </body>
</html>

<!-- Recommended -->
<!DOCTYPE html>
<title>Saving money, saving bytes</title>
<p>Qed.

(HTML) Download a PDF file instead of opening them in browser when clicked

The solution that worked best for me was the one written up by Nick on his blog

The basic idea of his solution is to use the Apache servers header mod and edit the .htaccess to include a FileMatch directive that the forces all *.pdf files to act as a stream instead of an attachment. While this doesn't actually involve editing HTML (as per the original question) it doesn't require any programming per se.

The first reason I preferred Nick's approach is because it allowed me to set it on a per folder basis so PDF's in one folder could still be opened in the browser while allowing others (the ones we would like users to edit and then re-upload) to be forced as downloads.

I would also like to add that there is an option with PDF's to post/submit fillable forms via an API to your servers, but that takes awhile to implement.

The second reason was because time is a consideration. Writing a PHP file handler to force the content disposition in the header() will also take less time than an API, but still longer than Nick's approach.

If you know how to turn on an Apache mod and edit the .htaccss you can get this in about 10 minutes. It requires Linux hosting (not Windows). This may not be appropriate approach for all uses as it requires high level server access to configure. As such, if you have said access it's probably because you already know how to do those two things. If not, check Nick's blog for more instructions.

Find an element in a list of tuples

[tup for tup in a if tup[0] == 1]

Option to ignore case with .contains method?

Kotlin Devs, go with any / none

private fun compareCategory(
        categories: List<String>?,
        category: String
    ) = categories?.any { it.equals(category, true) } ?: false

What is the behavior difference between return-path, reply-to and from?

Another way to think about Return-Path vs Reply-To is to compare it to snail mail.

When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path.

Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To.

In essence, a Postage Return Address is comparable to SMTP's Return-Path header and SMTP's Reply-To header is similar to the replying instructions contained in a letter.

How to sort the letters in a string alphabetically in Python

>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']

sorted returns a list, so you can make it a string again using join:

>>> c = ''.join(b)

which joins the items of b together with an empty string '' in between each item.

>>> print c
'ENOVWZ'

How to Exit a Method without Exiting the Program?

There are two ways to exit a method early (without quitting the program):

  • Use the return keyword.
  • Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

Specifically about your code:

  • There is no need to write the same test three times. All those conditions are equivalent.
  • You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:

    if (textBox1.Text == String.Empty)
    {
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    }
    return; // Are you sure you want the return to be here??
    
  • If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.

  • You might want to use Environment.Newline instead of "\r\n".
  • You might want to consider another way to display invalid input other than writing messages to a text box.

PHP pass variable to include

You can use the extract() function
Drupal use it, in its theme() function.

Here it is a render function with a $variables argument.

function includeWithVariables($filePath, $variables = array(), $print = true)
{
    $output = NULL;
    if(file_exists($filePath)){
        // Extract the variables to a local namespace
        extract($variables);

        // Start output buffering
        ob_start();

        // Include the template file
        include $filePath;

        // End buffering and return its contents
        $output = ob_get_clean();
    }
    if ($print) {
        print $output;
    }
    return $output;

}


./index.php :

includeWithVariables('header.php', array('title' => 'Header Title'));

./header.php :

<h1><?php echo $title; ?></h1>

Bloomberg BDH function with ISIN

To download ISIN code data the only place I see this is on the ISIN organizations website, www.isin.org. try http://isin.org, they should have a function where you can easily download.

Replacing blank values (white space) with NaN in pandas

I think df.replace() does the job, since pandas 0.13:

df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))

Produces:

                   A    B   C
2000-01-01 -0.532681  foo   0
2000-01-02  1.490752  bar   1
2000-01-03 -1.387326  foo   2
2000-01-04  0.814772  baz NaN
2000-01-05 -0.222552  NaN   4
2000-01-06 -1.176781  qux NaN

As Temak pointed it out, use df.replace(r'^\s+$', np.nan, regex=True) in case your valid data contains white spaces.

Checking for empty or null JToken in a JObject

Try something like this to convert JToken to JArray:

static public JArray convertToJArray(JToken obj)
{
    // if ((obj).Type == JTokenType.Null) --> You can check if it's null here

    if ((obj).Type == JTokenType.Array)
        return (JArray)(obj);
    else
        return new JArray(); // this will return an empty JArray
}

How do I get console input in javascript?

Good old readline();.

See MDN (archive).

Deleting folders in python recursively

For Linux users, you can simply run the shell command in a pythonic way

import os
os.system("rm -r /home/user/folder1  /home/user/folder2  ...")

If facing any issue then instead of rm -r use rm -rf but remember f will delete the directory forcefully.

Where rm stands for remove, -r for recursively and -rf for recursively + forcefully.

Note: It doesn't matter either the directories are empty or not, they'll get deleted.

Sanitizing user input before adding it to the DOM in Javascript

Since the text that you are escaping will appear in an HTML attribute, you must be sure to escape not only HTML entities but also HTML attributes:

var ESC_MAP = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
};

function escapeHTML(s, forAttribute) {
    return s.replace(forAttribute ? /[&<>'"]/g : /[&<>]/g, function(c) {
        return ESC_MAP[c];
    });
}

Then, your escaping code becomes var user_id = escapeHTML(id, true).

For more information, see Foolproof HTML escaping in Javascript.

How to save a dictionary to a file?

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

or use context manager, which is better:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

Node.js Port 3000 already in use but it actually isn't?

check for any process running on the same port by entering the command:

sudo ps -ef

You can find the process running on the respective node port, then kill the node by

kill -9 <node id>

If the problem still remains then just kill all the node

killall node

Convert DateTime to String PHP

There are some predefined formats in date_d.php to use with format like:

define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");

Use like this:

$date = new \DateTime();
$string = $date->format(DATE_RFC2822);

Regular expression to match a word or its prefix

[ ] defines a character class. So every character you set there, will match. [012] will match 0 or 1 or 2 and [0-2] behaves the same.

What you want is groupings to define a or-statement. Use (s|season) for your issue.

Btw. you have to watch out. Metacharacters in normal regex (or inside a grouping) are different from character class. A character class is like a sub-language. [$A] will only match $ or A, nothing else. No escaping here for the dollar.

Rounding to 2 decimal places in SQL

Try using the COLUMN command with the FORMAT option for that:

COLUMN COLUMN_NAME FORMAT 99.99
SELECT COLUMN_NAME FROM ....

How to close an iframe within iframe itself

None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.

I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.

Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage

All these steps are on the GitHub link:

1- You have to inject a JS file on the parent page.

2- In this file injected on the parent, add a window event listner

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

This listener will handle the close and any other event you wish

3- Inside the Iframe page you send the close command via postMessage:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!

Hope it helps,

Index inside map() function

  • suppose you have an array like

_x000D_
_x000D_
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })
_x000D_
_x000D_
_x000D_

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

Easy way to build Android UI?

The Android Development Tools (ADT) plugin for Eclipse includes a visual editor for android application layout files:

http://developer.android.com/tools/help/adt.html

How to declare strings in C

char *p = "String";   means pointer to a string type variable.

char p3[5] = "String"; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:

char p3[7]= "String";

Where's my JSON data in my incoming Django request?

Using Angular you should add header to request or add it to module config headers: {'Content-Type': 'application/x-www-form-urlencoded'}

$http({
    url: url,
    method: method,
    timeout: timeout,
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Convert a string into an int

NSString *string = /* Assume this exists. */;
int value = [string intValue];

How to redirect a url in NGINX

Best way to do what you want is to add another server block:

server {
        #implemented by default, change if you need different ip or port
        #listen *:80 | *:8000;
        server_name test.com;
        return 301 $scheme://www.test.com$request_uri;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

Important: New server block is the right way to do this, if is evil. You must use locations and servers instead of if if it's possible. Rewrite is sometimes evil too, so replaced it with return.

How do HashTables deal with collisions?

I've heard in my degree classes that a HashTable will place a new entry into the 'next available' bucket if the new Key entry collides with another.

This is actually not true, at least for the Oracle JDK (it is an implementation detail that could vary between different implementations of the API). Instead, each bucket contains a linked list of entries prior to Java 8, and a balanced tree in Java 8 or above.

then how would the HashTable still return the correct Value if this collision occurs when calling for one back with the collision key?

It uses the equals() to find the actually matching entry.

If I implement my own hashing function and use it as part of a look-up table (i.e. a HashMap or Dictionary), what strategies exist for dealing with collisions?

There are various collision handling strategies with different advantages and disadvantages. Wikipedia's entry on hash tables gives a good overview.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

You need to add the attribute "formnovalidate" to the control that is triggering the browser validation, e.g.:

<input type="image" id="fblogin" formnovalidate src="/images/facebook_connect.png">

getElementById in React

import React, { useState } from 'react';

function App() {
  const [apes , setap] = useState('yo');
  const handleClick = () =>{
    setap(document.getElementById('name').value)
  };
  return (
    <div>
      <input id='name' />
      <h2> {apes} </h2>
      <button onClick={handleClick} />
  </div>
  );
}

export default App;

Git: How to rebase to a specific commit?

Topic Solution

The correct command to answer the posted question could be any of the following (assuming branch topic is already checked out):

git rebase --onto B master
git rebase --onto master~1 master
git rebase --onto B A
git rebase --onto B C
git rebase --onto B

If topic is not checked out, you simply append topic to the command (except the last one) like so:

git rebase --onto B master topic

Alternatively, check out the branch first with:

git checkout topic

Rebase Any String of Commits to a Target Commit

The basic form of the command we need, cribbed from the documentation, is:

git rebase --onto <Target> [<Upstream> [<Branch>]]

<Branch> is optional and all it does is checks out the branch specified before executing the rest of the command. If you've already checked out the branch you want to rebase, then you don't need this. Note that you must have specified <Upstream> in order to specify <Branch> or git will think you are specifying <Upstream>.

<Target> is the commit we will attach our string of commits to. When providing a branch name, you are simply specifying the head commit of that branch. <Target> can be any commit that won't be contained in the string of commits being moved. For example:

A --- B --- C --- D         master
      \
       \-- X --- Y --- Z    feature

To move the entire feature branch, you can not select X, Y, Z, or feature as the <Target> since those all are commits inside the group being moved.

<Upstream> is special because it can mean two different things. If it is a commit that is an ancestor of the checked out branch, then it serves as the cut point. In the example I provided, this would be anything that isn't C, D, or master. All commits after <Upstream> until the head of the checked out branch are the ones that will be moved.

However, if <Upstream> is not an ancestor, then git backs up the chain from the specified commit until if finds a common ancestor with the checked out branch (and aborts if it can't find one). In our case, an <Upstream> of B, C, D, or master will all result in commit B serving as the cut point. <Upstream> is itself an optional command and if it is not specified, then git looks at the parent of the checked out branch which is the equivalent of entering master.

Now that git has selected the commits it will cut and move, it applies them in order to <Target>, skipping any that are already applied to target.

Interesting Examples and Results

Using this starting point:

A --- B --- C --- D --- E         master
            \
             \-- X --- Y --- Z    feature
  • git rebase --onto D A feature
    Will apply commits B, C, X, Y, Z to commit D and end up skipping B and C because they already have been applied.

  • git rebase --onto C X feature
    Will apply commits Y and Z to commit C, effectively deleting commit X

What does the DOCKER_HOST variable do?

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

$ boot2docker start

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

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

$ export DOCKER_HOST=tcp://192.168.59.103:2375

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

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

Validate phone number using angular js

You can also use ng-pattern and I feel that will be a best practice. Similarly try to use ng-message. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.

angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
  $scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
  <div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
    <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
    <div class="col-sm-9">
      <input type="number" class="form-control" ng-pattern="ph_numbr"  id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
      <div class="help-block" ng-messages="registration.phone.$error">
        <p ng-message="required">Phone number is required.</p>
        <p ng-message="pattern">Phone number is invalid.</p>
      </div>
    </div>
  </div>
</form>

How to loop through array in jQuery?

Option 1 : The traditional for-loop

The basics

A traditional for-loop has three components :

  1. the initialization : executed before the look block is executed the first time
  2. the condition : checks a condition every time before the loop block is executed, and quits the loop if false
  3. the afterthought : performed every time after the loop block is executed

These three components are seperated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for-loop possible :

for (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

Using a tradtional for-loop to loop through an array

The traditional way to loop through an array, is this :

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this :

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like eg. this one :

for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one :

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

Note :

Each of these variations is supported by all browsers, including véry old ones!


Option 2 : The while-loop

One alternative to a for-loop is a while-loop. To loop through an array, you could do this :

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
Note :

Like traditional for-loops, while-loops are supported by even the oldest of browsers.

Also, every while loop can be rewritten as a for-loop. For example, the while-loop hereabove behaves the exact same way as this for-loop :

for(var key = 0;value = myArray[key++];){
    console.log(value);
}

Option 3 : for...in and for...of

In JavaScript, you can also do this :

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditonal for-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.

As an alternative to for...in, there's now also for for...of. The following example shows the difference between a for...of loop and a for...in loop :

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}
Note :

You also need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least IE10.


Option 4 : Array.prototype.forEach()

An alternative to For-loops is Array.prototype.forEach(), which uses the following syntax :

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
Note :

Array.prototype.forEach() is supported by all modern browsers, as well as IE9+.


Option 5 : jQuery.each()

Additionally to the four other options mentioned, jQuery also had its own foreach variation.

It uses the following syntax :

$.each(myArray, function(key, value) {
    console.log(value);
});

The executable was signed with invalid entitlements

Code signing entitlements are no longer necessary for Ad Hoc builds in Xcode 4 - see details notes in Apple Technical Note TN2250

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:

ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)

If you are doing CE development, i would recomend this FAQ:

EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.

How can I find the number of elements in an array?

I personally think that sizeof(a) / sizeof(*a) looks cleaner.

I also prefer to define it as a macro:

#define NUM(a) (sizeof(a) / sizeof(*a))

Then you can use it in for-loops, thusly:

for (i = 0; i < NUM(a); i++)

How to add two strings as if they were numbers?

You can use this to add numbers:

var x = +num1 + +num2;

Android: How do I get string from resources using its name?

If you wannt get it inside an activity or fragmnet, then:

getContext().getResources().getString(R.string.string_name);

If you want to get it from a class outside of activity or fragment where you don't have the activity context then use application context:

getApplicationContext().getResources().getString(R.string.string_name);

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

Like others have said, I had this exact same problem and it turned out to be related to the password / access secret. I generated a password for my s3 user that was not valid, and it didn't inform me. When trying to connect with the user, it gave this error. It doesn't seem to like certain or all symbols in passwords (at least for Minio)

Can an int be null in Java?

An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.

Data Type / Default Value (for fields)

int ------------------ 0

long ---------------- 0L

float ---------------- 0.0f

double ------------- 0.0d

char --------------- '\u0000'

String --------------- null

boolean ------------ false

SQL Server : Transpose rows to columns

One way to do it if tagID values are known upfront is to use conditional aggregation

SELECT TimeSeconds,
       COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
       COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
       COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
       COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
  FROM table1
 GROUP BY TimeSeconds

or if you're OK with NULL values instead of 'n/a'

SELECT TimeSeconds,
       MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
       MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
       MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
       MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
  FROM table1
 GROUP BY TimeSeconds

or with PIVOT

SELECT TimeSeconds, A1, A2, A3, A4
  FROM
(
  SELECT TimeSeconds, TagID, Value
    FROM table1
) s
PIVOT
(
  MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p

Output (with NULLs):

TimeSeconds A1      A2     A3    A4
----------- ------- ------ ----- -----
1378700244  3.75    NULL   NULL  NULL
1378700245  30.00   NULL   NULL  NULL
1378700304  1.20    NULL   NULL  NULL
1378700305  NULL    56.00  NULL  NULL
1378700344  NULL    11.00  NULL  NULL
1378700345  NULL    NULL   0.53  NULL
1378700364  4.00    NULL   NULL  NULL
1378700365  14.50   NULL   NULL  NULL
1378700384  144.00  NULL   NULL  10.00

If you have to figure TagID values out dynamically then use dynamic SQL

DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID)
            FROM Table1
            ORDER BY 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @sql = 'SELECT TimeSeconds, ' + @cols + '
              FROM
            (
              SELECT TimeSeconds, TagID, Value
                FROM table1
            ) s
            PIVOT
            (
              MAX(Value) FOR TagID IN (' + @cols + ')
            ) p'

EXECUTE(@sql)

How to initialize struct?

  1. Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.

  2. To get the syntax you asked for, you can implement an "implicit" operator like so:

    static implicit operator MyStruct(string s) {
        return new MyStruct(...);
    }
    
  3. The implicit operator will work, regardless of whether you make your struct mutable or not.

How can I give eclipse more memory than 512M?

While working on an enterprise project in STS (heavily Eclipse based) I was crashing constantly and STS plateaued at around 1GB of RAM usage. I couldn't add new .war files to my local tomcat server and after deleting the tomcat folder to re-add it, found I couldn't re-add it either. Essentially almost anything that required a new popup besides the main menus was causing STS to freeze up.

I edited the STS.ini (your Eclipse.ini can be configured similarly) to:

--launcher.XXMaxPermSize 1024M -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m

Rebooted STS immediately and saw it plateau at about 1.5 gigs before finally not crashing

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

JavaScript: Is there a way to get Chrome to break on all errors?

This is now supported in Chrome by the "Pause on all exceptions" button.

To enable it:

  • Go to the "Sources" tab in Chrome Developer Tools
  • Click the "Pause" button at the bottom of the window to switch to "Pause on all exceptions mode".

Note that this button has multiple states. Keep clicking the button to switch between

  • "Pause on all exceptions" - the button is colored light blue
  • "Pause on uncaught exceptions", the button is colored purple.
  • "Dont pause on exceptions" - the button is colored gray

Make absolute positioned div expand parent div height

Also consider next approach:

CSS:

.parent {
  height: 100%;
}
.parent:after {
  content: '';
  display: block;
}

Also since you are trying to reposition divs consider css grid

Multiline string literal in C#

Why do people keep confusing strings with string literals? The accepted answer is a great answer to a different question; not to this one.

I know this is an old topic, but I came here with possibly the same question as the OP, and it is frustrating to see how people keep misreading it. Or maybe I am misreading it, I don't know.

Roughly speaking, a string is a region of computer memory that, during the execution of a program, contains a sequence of bytes that can be mapped to text characters. A string literal, on the other hand, is a piece of source code, not yet compiled, that represents the value used to initialize a string later on, during the execution of the program in which it appears.

In C#, the statement...

 string query = "SELECT foo, bar"
 + " FROM table"
 + " WHERE id = 42";

... does not produce a three-line string but a one liner; the concatenation of three strings (each initialized from a different literal) none of which contains a new-line modifier.

What the OP seems to be asking -at least what I would be asking with those words- is not how to introduce, in the compiled string, line breaks that mimick those found in the source code, but how to break up for clarity a long, single line of text in the source code without introducing breaks in the compiled string. And without requiring an extended execution time, spent joining the multiple substrings coming from the source code. Like the trailing backslashes within a multiline string literal in javascript or C++.

Suggesting the use of verbatim strings, nevermind StringBuilders, String.Joins or even nested functions with string reversals and what not, makes me think that people are not really understanding the question. Or maybe I do not understand it.

As far as I know, C# does not (at least in the paleolithic version I am still using, from the previous decade) have a feature to cleanly produce multiline string literals that can be resolved during compilation rather than execution.

Maybe current versions do support it, but I thought I'd share the difference I perceive between strings and string literals.

UPDATE:

(From MeowCat2012's comment) You can. The "+" approach by OP is the best. According to spec the optimization is guaranteed: http://stackoverflow.com/a/288802/9399618

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JAVA_HOME is a environment variable (in Unix terminologies), or a PATH variable (in Windows terminology). A lot of well behaving Java applications (which need the JDK/JRE) to run, looks up the JAVA_HOME variable for the location where the Java compiler/interpreter may be found.

Cannot invoke an expression whose type lacks a call signature

I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:

npm install --save @types/numeral

How do you select a particular option in a SELECT element in jQuery?

You could name the select and use this:

$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);

It should select the option you want.

Override standard close (X) button in a Windows Form

One situation where it is quite useful to be able to handle the x-button click event is when you are using a Form that is an MDI container. The reason is that the closeing and closed events are raised first with children and lastly with the parent. So in one scenario a user clicks the x-button to close the application and the MDI parent asks for a confirmation to proceed. In case he decides to not close the application but carry on whatever he is doing the children will already have processed the closing event potentially lost information/work whatever. One solution is to intercept the WM_CLOSE message from the Windows message loop in your main application form (i.e. which closed, terminates the application) like so:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0010) // WM_CLOSE
        {
            // If we don't want to close this window 
            if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
        }

        base.WndProc(ref m);
    }

What does the "static" modifier after "import" mean?

The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.

I will elaborate my point with example.

import java.lang.Math;

class WithoutStaticImports {

 public static void main(String [] args) {
  System.out.println("round " + Math.round(1032.897));
  System.out.println("min " + Math.min(60,102));
 }
}

Same code, with static imports:

import static java.lang.System.out;
import static java.lang.Math.*;

class WithStaticImports {
  public static void main(String [] args) {
    out.println("round " + round(1032.897));
    out.println("min " + min(60,102));
  }
}

Note: static import can make your code confusing to read.

Python: Converting string into decimal number

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

What is the difference between pip and conda?

To answer the original question,
For installing packages, PIP and Conda are different ways to accomplish the same thing. Both are standard applications to install packages. The main difference is the source of the package files.

  • PIP/PyPI will have more "experimental" packages, or newer, less common, versions of packages
  • Conda will typically have more well established packages or versions

An important cautionary side note: If you use both sources (pip and conda) to install packages in the same environment, this may cause issues later.

  • Recreate the environment will be more difficult
  • Fix package incompatibilities becomes more complicated

Best practice is to select one application, PIP or Conda, to install packages, and use that application to install any packages you need. However, there are many exceptions or reasons to still use pip from within a conda environment, and vice versa. For example:

  • When there are packages you need that only exist on one, and the other doesn't have them.
  • You need a certain version that is only available in one environment

window.onload vs $(document).ready()

_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
    // Executes when the HTML document is loaded and the DOM is ready_x000D_
    alert("Document is ready");_x000D_
});_x000D_
_x000D_
// .load() method deprecated from jQuery 1.8 onward_x000D_
$(window).on("load", function() {_x000D_
_x000D_
     // Executes when complete page is fully loaded, including_x000D_
     // all frames, objects and images_x000D_
     alert("Window is loaded");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Implementation difference between Aggregation and Composition in Java

The difference is that any composition is an aggregation and not vice versa.

Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".

Further from UML standard:

composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).

So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)

Precise semantics of shared aggregation varies by application area and modeler.

I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.

A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).

The manual explains it as follows:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.

The manual explains how indexes are used in general: here.

In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.

Untested, but I believe the MSSQL equivalent is:

CREATE TABLE tmp (
  id int NOT NULL PRIMARY KEY IDENTITY,
  uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
  name varchar(255) NOT NULL,
  tag int NOT NULL DEFAULT 0,
  description varchar(255),
);

CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);

Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).

What is this Javascript "require"?

Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).

Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).

Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.

Now require() is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules in the same directory (or the directory of the invoked javascript file) or the system-wide search path.

To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.

Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.

As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.

/* your connection code */

var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
    var name = req.params.name || '';
    name = name.replace(/[^a-zA_Z]/, '');
    if (!name.length) {
        res.send({});
    } else {
        var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
        var data = {};
        query.on('row', function(row) {
            data = row;
            res.send(data);
        });
    };
});
app.listen(80, '127.0.0.1');

Is it possible to use Visual Studio on macOS?

There is no native version of Visual Studio for Mac OS X.

Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Assign variable value inside if-statement

Yes, it is possible to assign inside if conditional check. But, your variable should have already been declared to assign something.

How to select rows in a DataFrame between two values, in Python Pandas?

you can also use .between() method

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")

emp[emp["Salary"].between(60000, 61000)]

Output

enter image description here

Pip error: Microsoft Visual C++ 14.0 is required

You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

Invoke(Delegate)

Invoke((MethodInvoker)delegate{ textBox1.Text = "Test"; });

android: data binding error: cannot find symbol class

You need to add the tags into your Activity's Xml Layout.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
             name=""
             type="" />
    </data
    <android.support.design.widget.CoordinatorLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
  tools:context="com.letsnurture.ln_202.databindingdemo.ContactListActivity">

    </android.support.design.widget.CoordinatorLayout>
</layout>

and then, add an android:id into your tag

After that, you'll have a ActivityContactListBinding object and you can access and bind variables on your included layouts.

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

What is the difference between declarations, providers, and import in NgModule?

Adding a quick cheat sheet that may help after the long break with Angular:


DECLARATIONS

Example:

declarations: [AppComponent]

What can we inject here? Components, pipes, directives


IMPORTS

Example:

imports: [BrowserModule, AppRoutingModule]

What can we inject here? other modules


PROVIDERS

Example:

providers: [UserService]

What can we inject here? services


BOOTSTRAP

Example:

bootstrap: [AppComponent]

What can we inject here? the main component that will be generated by this module (top parent node for a component tree)


ENTRY COMPONENTS

Example:

entryComponents: [PopupComponent]

What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())


EXPORT

Example:

export: [TextDirective, PopupComponent, BrowserModule]

What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)

Is there any good dynamic SQL builder library in Java?

Hibernate Criteria API (not plain SQL though, but very powerful and in active development):

List sales = session.createCriteria(Sale.class)
         .add(Expression.ge("date",startDate);
         .add(Expression.le("date",endDate);
         .addOrder( Order.asc("date") )
         .setFirstResult(0)
         .setMaxResults(10)
         .list();

How to initialize a JavaScript Date to a particular time zone

I found the most supported way to do this, without worrying about a third party library, was by using getTimezoneOffset to calculate the appropriate timestamp, or update the time then use the normal methods to get the necessary date and time.

var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);

// ET timezone offset in hours.
var timezone = -5;
// Timezone offset in minutes + the desired offset in minutes, converted to ms.
// This offset should be the same for ALL date calculations, so you should only need to calculate it once.
var offset = (mydate.getTimezoneOffset() + (timezone * 60)) * 60 * 1000;

// Use the timestamp and offset as necessary to calculate min/sec etc, i.e. for countdowns.
var timestamp = mydate.getTime() + offset,
    seconds = Math.floor(timestamp / 1000) % 60,
    minutes = Math.floor(timestamp / 1000 / 60) % 60,
    hours   = Math.floor(timestamp / 1000 / 60 / 60);

// Or update the timestamp to reflect the timezone offset.
mydate.setTime(mydate.getTime() + offset);
// Then Output dates and times using the normal methods.
var date = mydate.getDate(),
    hour = mydate.getHours();

EDIT

I was previously using UTC methods when performing the date transformations, which was incorrect. With adding the offset to the time, using the local get functions will return the desired results.

NOT IN vs NOT EXISTS

If the optimizer says they are the same then consider the human factor. I prefer to see NOT EXISTS :)

What is the difference between Swing and AWT?

The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.

How do you format code in Visual Studio Code (VSCode)

Formatting code in Visual Studio.

I have tried to format in Windows 8.

Just follow the screenshots below.

  1. Click on View on the top menu bar, and then click on Command Palette.

    Enter image description here

  2. Then a textbox would appear where we need type Format

    Shift + Alt + F

    Enter image description here

How can I set / change DNS using the command-prompt at windows 8

First, the network name is likely "Ethernet", not "Local Area Connection". To find out the name you can do this:

netsh interface show interface

Which will show the name under the "Interface Name" column (shown here in bold):

Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Ethernet

Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp):

netsh interface ipv4 add dnsserver "Ethernet" address=192.168.x.x index=1

2018 Update - The command will work with either dnsserver (singular) or dnsservers (plural). The following example uses the latter and is valid as well:

netsh interface ipv4 add dnsservers "Ethernet" address=192.168.x.x index=1

Multiline text in JLabel

In my case it was enough to split the text at every \n and then create a JLabel for every line:

JPanel panel = new JPanel(new GridLayout(0,1));
String[] lines = message.split("\n");
for (String line : lines) {
    JLabel label = new JLabel(line);
    panel.add(label);
}

I used above in a JOptionPane.showMessageDialog

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

How to sort a list of strings numerically?

In case you want to use sorted() function: sorted(list1, key=int)

It returns a new sorted list.

How can I escape white space in a bash loop list?

find Downloads -type f | while read file; do printf "%q\n" "$file"; done

how can I enable scrollbars on the WPF Datagrid?

Add grid with defined height and width for columns and rows. Then add ScrollViewer and inside it add the dataGrid.

How to find Max Date in List<Object>?

Comparator<User> cmp = new Comparator<User>() {
    @Override
    public int compare(User user1, User user2) {
        return user1.date.compareTo(user2.date);
    }
};

Collections.max(list, cmp);

no debugging symbols found when using gdb

Hope the sytem you compiled on and the system you are debugging on have the same architecture. I ran into an issue where debugging symbols of 32 bit binary refused to load up on my 64 bit machine. Switching to a 32 bit system worked for me.

Embed YouTube Video with No Ads

If you play the video as a playlist and then single out that video you can get it without ads. Here is what I have done: https://www.youtube.com/v/VIDEO_ID?playlist=VIDEO_ID&autoplay=1&rel=0

how to deal with google map inside of a hidden div (Updated picture)

My solution was:

CSS:

.map {
   height: 400px;
   border: #ccc solid 1px;
}

jQuery:

$('.map').width(555); // width of map canvas

CSS/Javascript to force html table row on a single line

Try:

td, th {
  white-space: nowrap;
  overflow: hidden;
}

How to get current moment in ISO 8601 format with date, hour, and minute?

I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.

private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";

public static Calendar isoToCalendar(final String inputDate) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
        Date date = dateFormat.parse(inputDate);
        calendar.setTime(date);
    } catch (ParseException e) {
        Log.e("TAG",e.getMessage());
    }
    return calendar;
}

REMEMBER: The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.

LINQ select one field from list of DTO objects to array

I think you're looking for;

  string[] skus = myLines.Select(x => x.Sku).ToArray();

However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray() bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;

  var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>

  foreach (string sku in skus) // forces execution of the query

In Java, how do I get the difference in seconds between 2 dates?

I should like to provide the modern answer. The other answers were fine when this question was asked, but time moves on. Today I recommend you use java.time, the modern Java date and time API.

    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");

This prints:

Difference: 2689 seconds

ChronoUnit.SECONDS.between() works with two ZonedDateTime objects or two OffsetDateTimes, two LocalDateTimes, etc.

If you need anything else than just the seconds, you should consider using the Duration class:

    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");

This prints:

Duration: PT44M49.247S
Difference: 2689 seconds

The former of the two lines prints the duration in ISO 8601 format, the output means a duration of 44 minutes and 49.247 seconds.

Why java.time?

The Date class used in several of the other answers is now long outdated. Joda-Time also used in a couple (and possibly in the question) is now in maintenance mode, no major enhancements are planned, and the developers officially recommend migrating to java.time, also known as JSR-310.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

How to determine if binary tree is balanced?

#include <iostream>
#include <deque>
#include <queue>

struct node
{
    int data;
    node *left;
    node *right;
};

bool isBalanced(node *root)
{
    if ( !root)
    {
        return true;
    }

    std::queue<node *> q1;
    std::queue<int>  q2;
    int level = 0, last_level = -1, node_count = 0;

    q1.push(root);
    q2.push(level);

    while ( !q1.empty() )
    {
        node *current = q1.front();
        level = q2.front();

        q1.pop();
        q2.pop();

        if ( level )
        {
            ++node_count;
        }

                if ( current->left )
                {
                        q1.push(current->left);
                        q2.push(level + 1);
                }

                if ( current->right )
                {
                        q1.push(current->right);
                        q2.push(level + 1);
                }

        if ( level != last_level )
        {
            std::cout << "Check: " << (node_count ? node_count - 1 : 1) << ", Level: " << level << ", Old level: " << last_level << std::endl;
            if ( level && (node_count - 1) != (1 << (level-1)) )
            {
                return false;
            }

            last_level = q2.front();
            if ( level ) node_count = 1;
        }
    }

    return true;
}

int main()
{
    node tree[15];

    tree[0].left  = &tree[1];
    tree[0].right = &tree[2];
    tree[1].left  = &tree[3];
    tree[1].right = &tree[4];
    tree[2].left  = &tree[5];
    tree[2].right = &tree[6];
    tree[3].left  = &tree[7];
    tree[3].right = &tree[8];
    tree[4].left  = &tree[9];   // NULL;
    tree[4].right = &tree[10];  // NULL;
    tree[5].left  = &tree[11];  // NULL;
    tree[5].right = &tree[12];  // NULL;
    tree[6].left  = &tree[13];
    tree[6].right = &tree[14];
    tree[7].left  = &tree[11];
    tree[7].right = &tree[12];
    tree[8].left  = NULL;
    tree[8].right = &tree[10];
    tree[9].left  = NULL;
    tree[9].right = &tree[10];
    tree[10].left = NULL;
    tree[10].right= NULL;
    tree[11].left = NULL;
    tree[11].right= NULL;
    tree[12].left = NULL;
    tree[12].right= NULL;
    tree[13].left = NULL;
    tree[13].right= NULL;
    tree[14].left = NULL;
    tree[14].right= NULL;

    std::cout << "Result: " << isBalanced(tree) << std::endl;

    return 0;
}

Scala vs. Groovy vs. Clojure

They can be differentiated with where they are coming from or which developers they're targeting mainly.

Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.

Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.

Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Write HTML file using Java

You can use jsoup or wffweb (HTML5) based.

Sample code for jsoup:-

Document doc = Jsoup.parse("<html></html>");
doc.body().addClass("body-styles-cls");
doc.body().appendElement("div");
System.out.println(doc.toString());

prints

<html>
 <head></head>
 <body class=" body-styles-cls">
  <div></div>
 </body>
</html>

Sample code for wffweb:-

Html html = new Html(null) {{
    new Head(this);
    new Body(this,
        new ClassAttribute("body-styles-cls"));
}};

Body body = TagRepository.findOneTagAssignableToTag(Body.class, html);
body.appendChild(new Div(null));

System.out.println(html.toHtmlString());
//directly writes to file
html.toOutputStream(new FileOutputStream("/home/user/filepath/filename.html"), "UTF-8");

prints (in minified format):-

<html>
<head></head>
<body class="body-styles-cls">
    <div></div>
</body>
</html>

Shrink a YouTube video to responsive width

You can make YouTube videos responsive with CSS. Wrap the iframe in a div with the class of "videowrapper" and apply the following styles:

.videowrapper {
    float: none;
    clear: both;
    width: 100%;
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 25px;
    height: 0;
}
.videowrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

The .videowrapper div should be inside a responsive element. The padding on the .videowrapper is necessary to keep the video from collapsing. You may have to tweak the numbers depending upon your layout.

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

Regarding C++ Include another class

C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.

Example

ClassOne.hpp:

class ClassOne
{
public:
  ClassOne(); // note, no function body        
  int method(); // no body here either
private:
  int member;
};

ClassOne.cpp:

#include "ClassOne.hpp"

// implementation of constructor
ClassOne::ClassOne()
 :member(0)
{}

// implementation of "method"
int ClassOne::method()
{
  return member++;
}

main.cpp:

#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler

int main(int argc, char* argv[])
{
  ClassOne c1;
  c1.method();

  return 0;
}

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How to concatenate strings in django templates?

extends has no facility for this. Either put the entire template path in a context variable and use that, or copy the exist template tag and modify it appropriately.

Making a triangle shape using xml definitions?

You can use vector to make triangle like this

ic_triangle_right.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:pathData="M0,12l0,12 11.5,-5.7c6.3,-3.2 11.5,-6 11.5,-6.3 0,-0.3 -5.2,-3.1 -11.5,-6.3l-11.5,-5.7 0,12z"
        android:strokeColor="#00000000"
        android:fillColor="#000000"/>
</vector>

Then use it like

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_triangle_right"
    />

For change the color and direction, use android:tint and android:rotation

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_triangle_right"
    android:rotation="180" // change direction
    android:tint="#00f" // change color
    />

Result

enter image description here

For change the shape of vector, you can change the width/height of vector. Example change width to 10dp

<vector 
        android:width="10dp"
        android:height="24dp"
        >
       ...
</vector>

enter image description here

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.