Programs & Examples On #Doctrine 1.2

Doctrine 1.2 is a PHP (5.2.3+) ORM. While Doctrine 2.0 uses the Data Mapper pattern, Doctrine 1.2 uses the Active Record pattern.

tar: Error is not recoverable: exiting now

The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu

sudo apt-get install bzip2

The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.

Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).

batch/bat to copy folder and content at once

For Folder Copy You can Use

robocopy C:\Source D:\Destination /E

For File Copy

copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y 

Delete file in some folder last modify date more than some day

forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"

And you can Shedule task in windows perform this task automatically in specific time.

How to take a screenshot programmatically on iOS

For iOS 7.0 or above..

If you want to take screenshots of view say(myView), you can do this with single line:

[myView snapshotViewAfterScreenUpdates:NO];

How to express a NOT IN query with ActiveRecord/Rails?

If someone want to use two or more conditions, you can do that:

your_array = [1,2,3,4]
your_string = "SOMETHING"

YourModel.where('variable1 NOT IN (?) AND variable2=(?)',Array.wrap(your_array),your_string)

How do I remove the top margin in a web page?

Try margin -10px:

body { margin-top:-10px; }

How to lock orientation of one view controller to portrait mode only in Swift

Create new extension with

import UIKit

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

extension UITabBarController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

Finding sum of elements in Swift array

Swift 3.0

i had the same problem, i found on the documentation Apple this solution.

let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10

But, in my case i had a list of object, then i needed transform my value of my list:

let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })

this work for me.

Anaconda version with Python 3.5

According to the official docu it's recommended to downgrade the whole Python environment:

conda install python=3.5

How to get N rows starting from row M from sorted table in T-SQL

And this is how you can achieve same goal on tables without primary key:

select * from
(
    select row_number() over(order by (select 0)) rowNum,*
    from your_table
) tmp
where tmp.rowNum between 20 and 30 -- any numbers you need

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

How to get element by classname or id

If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');
});

Hope this helps. :)

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Jquery - How to get the style display attribute "none / block"

this is the correct answer

$('#theid').css('display') == 'none'

You can also use following line to find if it is display block or none

$('.deal_details').is(':visible')

Set value for particular cell in pandas DataFrame using index

In my example i just change it in selected cell

    for index, row in result.iterrows():
        if np.isnan(row['weight']):
            result.at[index, 'weight'] = 0.0

'result' is a dataField with column 'weight'

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

How to call python script on excel vba?

This code will works:

 your_path= ActiveWorkbook.Path & "\your_python_file.py" 
 Shell "RunDll32.Exe Url.Dll,FileProtocolHandler " & your_path, vbNormalFocus 

ActiveWorkbook.Path return the current directory of the workbook. The shell command open the file through the shell of Windows.

Convert List<String> to List<Integer> directly

Using lambda:

strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl.

In my case, I was doing (in Serverless Framework YML):

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName"

Instead of:

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName/*"

Which adds a /* to the end of the bucket ARN.

Hope this helps.

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

How to Apply Gradient to background view of iOS Swift App

Cleaner code that lets you pass any UIColor to an instance of the GradientLayer class:

class GradientLayer {

    let gradientLayer: CAGradientLayer
    let colorTop: CGColor
    let colorBottom: CGColor

    init(colorTop: UIColor, colorBottom: UIColor) {
        self.colorTop = colorTop.CGColor
        self.colorBottom = colorBottom.CGColor
        gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
    }
}

How can I get the root domain URI in ASP.NET?

C# Example Below:

string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
  scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();

jQuery: more than one handler for same event

jquery will execute both handler since it allows multiple event handlers. I have created sample code. You can try it

demo

Constraint Layout Vertical Align Center

 <TextView
        android:id="@+id/tvName"
        style="@style/textViewBoldLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Welcome"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

Total number of items defined in an enum

From the previous answers just adding code sample.

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }

Saving and loading objects and using pickle

You're forgetting to read it as binary too.

In your write part you have:

open(b"Fruits.obj","wb") # Note the wb part (Write Binary)

In the read part you have:

file = open("Fruits.obj",'r') # Note the r part, there should be a b too

So replace it with:

file = open("Fruits.obj",'rb')

And it will work :)


As for your second error, it is most likely cause by not closing/syncing the file properly.

Try this bit of code to write:

>>> import pickle
>>> filehandler = open(b"Fruits.obj","wb")
>>> pickle.dump(banana,filehandler)
>>> filehandler.close()

And this (unchanged) to read:

>>> import pickle
>>> file = open("Fruits.obj",'rb')
>>> object_file = pickle.load(file)

A neater version would be using the with statement.

For writing:

>>> import pickle
>>> with open('Fruits.obj', 'wb') as fp:
>>>     pickle.dump(banana, fp)

For reading:

>>> import pickle
>>> with open('Fruits.obj', 'rb') as fp:
>>>     banana = pickle.load(fp)

"webxml attribute is required" error in Maven

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

This solution works for me (I was using 2.2 before). Also, I am using Java Based Configuration for Servlet 3.0 and no need to have web.xml file.

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

This answer is based on the following answer by @YuSolution https://stackoverflow.com/a/44622211/4567504.

In my case Installing MySQL changed my path variable and even after reinstalling @angular/cli globally many times I was not able to fix the issue.

Solution:

In command prompt, run the following command

npm config get prefix

A path will be returned like

C:\Users{{Your_Username}}\AppData\Roaming\npm

Copy this path and go to ControlPanel > System and Security > System, Click on Advanced System settings, go to advanced tab and select environment variable button like

enter image description here

Now in User Variables box click on Path row and edit and in variable value box paste your copied path.

Restart the command prompt and it will work

Remove all unused resources from an android project

Beware if you are using multiple flavours when running lint. Lint may give false unused resources depending on the flavour you have selected.

How to ping a server only once from within a batch file?

if you want to use the name "ping.bat", a small trick is to use this code:

@echo off
cd\ 
ping google.com -t

Just add that "cd\" and you are fine... ;)

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Spring RestTemplate GET with parameters

To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner than manually concatenating strings and it takes care of the URL encoding for you:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", msisdn)
        .queryParam("email", email)
        .queryParam("clientVersion", clientVersion)
        .queryParam("clientType", clientType)
        .queryParam("issuerName", issuerName)
        .queryParam("applicationName", applicationName);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.toUriString(), 
        HttpMethod.GET, 
        entity, 
        String.class);

How to automatically select all text on focus in WPF TextBox?

Here are the Blend behaviors implementing the answer solution for your convenience:

One for attaching to a single TextBox:

public class SelectAllTextOnFocusBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotKeyboardFocus += AssociatedObjectGotKeyboardFocus;
        AssociatedObject.GotMouseCapture += AssociatedObjectGotMouseCapture;
        AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObjectPreviewMouseLeftButtonDown;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotKeyboardFocus -= AssociatedObjectGotKeyboardFocus;
        AssociatedObject.GotMouseCapture -= AssociatedObjectGotMouseCapture;
        AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObjectPreviewMouseLeftButtonDown;
    }

    private void AssociatedObjectGotKeyboardFocus(object sender,
        System.Windows.Input.KeyboardFocusChangedEventArgs e)
    {
        AssociatedObject.SelectAll();
    }

    private void AssociatedObjectGotMouseCapture(object sender,
        System.Windows.Input.MouseEventArgs e)
    {
        AssociatedObject.SelectAll();   
    }

    private void AssociatedObjectPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if(!AssociatedObject.IsKeyboardFocusWithin)
        {
            AssociatedObject.Focus();
            e.Handled = true;
        }
    }
}

And one for attaching to the root of a container containing multiple TextBox'es:

public class SelectAllTextOnFocusMultiBehavior : Behavior<UIElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotKeyboardFocus += HandleKeyboardFocus;
        AssociatedObject.GotMouseCapture += HandleMouseCapture;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotKeyboardFocus -= HandleKeyboardFocus;
        AssociatedObject.GotMouseCapture -= HandleMouseCapture;
    }

    private static void HandleKeyboardFocus(object sender,
        System.Windows.Input.KeyboardFocusChangedEventArgs e)
    {
        var txt = e.NewFocus as TextBox;
        if (txt != null)
            txt.SelectAll();
    }

    private static void HandleMouseCapture(object sender,
        System.Windows.Input.MouseEventArgs e)
    {
        var txt = e.OriginalSource as TextBox;
        if (txt != null)
            txt.SelectAll();
    }
}

How to add icons to React Native app

Coming in a bit late here but Android Studio has a very handy icon asset wizard. Its very self explanatory but has a few handy effects and its built right in:

enter image description here

My Routes are Returning a 404, How can I Fix Them?

Just Run in your terminal.

 composer dump-autoload

SonarQube Exclude a directory

what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".

This will skip the whole module. So be aware of it.

Java: Clear the console

Since there are several answers here showing non-working code for Windows, here is a clarification:

Runtime.getRuntime().exec("cls");

This command does not work, for two reasons:

  1. There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.

  2. When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.

To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.

Use virtualenv with Python with Visual Studio Code in Ubuntu

With the latest Python extension for Visual Studio Code, there is a venvPath Setting:

// Path to folder with a list of Virtual Environments (e.g. ~/.pyenv, ~/Envs, ~/.virtualenvs).
  "python.venvPath": "",

On Mac OS X, go to Code ? Preferences ? Settings and scroll down to Python Configuration.

Look for "python.venvPath: "", and click the pencil on the left-hand side to open up your user settings. Finally, add the path to where you store your virtual environments.

If you are using virtuanenvwrapper, or you have put all your virtual environment setting in one folder, this will be the one for you.

After you have configured "python.venvPath", restart Visual Studio Code. Then open the command palette and look for "Python: Select Interpreter". At this point, you should see the interpreter associated with the virtual environment you just added.

Can CSS force a line break after each word in an element?

If you want to be able to choose from different solutions, in addition to the given answers...

An alternative method is to give the container a width of 0 and to make sure overflow is visible. Then each word will overflow out of it and will be on its own line.

_x000D_
_x000D_
div {_x000D_
  width: 0;_x000D_
  overflow: visible;_x000D_
}
_x000D_
<div>Short Word</div>_x000D_
<hr>_x000D_
<div>Gargantuan Word</div>
_x000D_
_x000D_
_x000D_

Or you can use one of those newly proposed width values, provided those still exist by the time you read this.

_x000D_
_x000D_
div {_x000D_
  width: min-intrinsic;       /* old Chrome, Safari */_x000D_
  width: -webkit-min-content; /* less old Chrome, Safari */_x000D_
  width: -moz-min-content;    /* current Firefox */_x000D_
  width: min-content;         /* current Chrome, Safari; not IE or Edge */_x000D_
}
_x000D_
<div>Short Word</div>_x000D_
<hr>_x000D_
<div>Gargantuan Word</div>
_x000D_
_x000D_
_x000D_

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

You could use method

javax.crypto.Cipher.getMaxAllowedKeyLength(String transformation)

to test the available key length, use that and inform the user about what is going on. Something stating that your application is falling back to 128 bit keys due to the policy files not being installed, for example. Security conscious users will install the policy files, others will continue using weaker keys.

Reloading module giving NameError: name 'reload' is not defined

If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).

import sys
if(sys.version_info.major>=3):
    def reload(MODULE):        
        import importlib
        importlib.reload(MODULE)

BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

How to get only filenames within a directory using c#?

You can use Path.GetFileName to get the filename from the full path

private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
                                     .Select(Path.GetFileName)
                                     .ToArray();

EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:

private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");

private static string[] GetFileNames(string path, string filter)
{
    string[] files = Directory.GetFiles(path, filter);
    for(int i = 0; i < files.Length; i++)
        files[i] = Path.GetFileName(files[i]);
    return files;
}

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

Java: how do I get a class literal from a generic type?

You can't due to type erasure.

Java generics are little more than syntactic sugar for Object casts. To demonstrate:

List<Integer> list1 = new ArrayList<Integer>();
List<String> list2 = (List<String>)list1;
list2.add("foo"); // perfectly legal

The only instance where generic type information is retained at runtime is with Field.getGenericType() if interrogating a class's members via reflection.

All of this is why Object.getClass() has this signature:

public final native Class<?> getClass();

The important part being Class<?>.

To put it another way, from the Java Generics FAQ:

Why is there no class literal for concrete parameterized types?

Because parameterized type has no exact runtime type representation.

A class literal denotes a Class object that represents a given type. For instance, the class literal String.class denotes the Class object that represents the type String and is identical to the Class object that is returned when method getClass is invoked on a String object. A class literal can be used for runtime type checks and for reflection.

Parameterized types lose their type arguments when they are translated to byte code during compilation in a process called type erasure . As a side effect of type erasure, all instantiations of a generic type share the same runtime representation, namely that of the corresponding raw type . In other words, parameterized types do not have type representation of their own. Consequently, there is no point in forming class literals such as List<String>.class , List<Long>.class and List<?>.class , since no such Class objects exist. Only the raw type List has a Class object that represents its runtime type. It is referred to as List.class.

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

Java 8 Distinct by property

Extending Stuart Marks's answer, this can be done in a shorter way and without a concurrent map (if you don't need parallel streams):

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    final Set<Object> seen = new HashSet<>();
    return t -> seen.add(keyExtractor.apply(t));
}

Then call:

persons.stream().filter(distinctByKey(p -> p.getName());

"Repository does not have a release file" error

I opened up my Software & Updates program and switched from my country to the main servers like so:
Software & Updates screen

After I done this and run the sudo apt update commando again, my problems where gone.

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

Why does using an Underscore character in a LIKE filter give me all the results?

The underscore is the wildcard in a LIKE query for one arbitrary character.

Hence LIKE %_% means "give me all records with at least one arbitrary character in this column".

You have to escape the wildcard character, in sql-server with [] around:

SELECT m.* 
FROM Manager m 
WHERE m.managerid    LIKE  '[_]%'
AND   m.managername  LIKE '%[_]%'

See: LIKE (Transact-SQL)

Demo

How to write new line character to a file in Java

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();

Convert Pandas column containing NaNs to dtype `int`

If you absolutely want to combine integers and NaNs in a column, you can use the 'object' data type:

df['col'] = (
    df['col'].fillna(0)
    .astype(int)
    .astype(object)
    .where(df['col'].notnull())
)

This will replace NaNs with an integer (doesn't matter which), convert to int, convert to object and finally reinsert NaNs.

What does Html.HiddenFor do?

The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code

 <input type="hidden"/>

And also refer the following link

https://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hiddenfor(v=vs.118).aspx

Mvn install or Mvn package

The proper way is mvn package if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.

In addition if you use Travis you can "cache" your dependencies because it will not touch your $HOME.m2/repository if you use package for your own project.

In practicality if you even attempt to do a mvn site you usually need to do a mvn install before. There's just too many bugs with either site or it's numerous poorly maintained plugins.

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

How to darken an image on mouseover?

Put a black, semitransparent, div on top of it.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

I know this question is old, but the solution to my application, was different to the already suggested answers. If anyone else like me still have this issue, and none of the above answers works, this might be the problem:

I used a Network Credentials object to parse a windows username+password to a third party SOAP webservice. I had set the username="domainname\username", password="password" and domain="domainname". Now this game me that strange Ntlm and not NTLM error. To solve the problems, make sure not to use the domain parameter on the NetworkCredentials object if the domain name is included in the username with the backslash. So either remove domain name from the username and parse in domain parameter, or leave out the domain parameter. This solved my issue.

List columns with indexes in PostgreSQL

@cope360 's excellent answer, converted to use join syntax.

select t.relname as table_name
     , i.relname as index_name
     , array_to_string(array_agg(a.attname), ', ') as column_names
from pg_class t
join pg_index ix
on t.oid = ix.indrelid
join pg_class i
on i.oid = ix.indexrelid
join pg_attribute a
on a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
where t.relkind = 'r'
and t.relname like 'test%'
group by t.relname
       , i.relname
order by t.relname
       , i.relname
;

Is it valid to define functions in JSON results?

Leave the quotes off...

var a = {"b":function(){alert('hello world');} };

a.b();

Java: Calling a super method which calls an overridden method

If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.

Here's a suggestion:

public class SuperClass {

  public void method1() {
    System.out.println("superclass method1");
    this.internalMethod2();
  }

  public void method2()  {
    // this method can be overridden.  
    // It can still be invoked by a childclass using super
    internalMethod2();
  }

  private void internalMethod2()  {
    // this one cannot.  Call this one if you want to be sure to use
    // this implementation.
    System.out.println("superclass method2");
  }

}

public class SubClass extends SuperClass {

  @Override
  public void method1() {
    System.out.println("subclass method1");
    super.method1();
  }

  @Override
  public void method2() {
    System.out.println("subclass method2");
  }
}

If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

How can I add an item to a SelectList in ASP.net MVC

Okay I like clean code so I made this an extension method

static public class SelectListHelper
{
    static public SelectList Add(this SelectList list, string text, string value = "", ListPosition listPosition = ListPosition.First)
    {
        if (string.IsNullOrEmpty(value))
        {
            value = text;
        }
        var listItems = list.ToList();
        var lp = (int)listPosition;
        switch (lp)
        {
            case -1:
                lp = list.Count();
                break;
            case -2:
                lp = list.Count() / 2;
                break;
            case -3:
                var random = new Random();
                lp = random.Next(0, list.Count());
                break;
        }
        listItems.Insert(lp, new SelectListItem { Value = value, Text = text });
        list = new SelectList(listItems, "Value", "Text");
        return list;
    }

    public enum ListPosition
    {
        First = 0,
        Last = -1,
        Middle = -2,
        Random = -3
    }
}

Usage (by example):

var model = new VmRoutePicker
    {
     Routes =
     new SelectList(_dataSource.Routes.Select(r => r.RouteID).Distinct())
     };                                     
  model.Routes = model.Routes.Add("All", "All", SelectListHelper.ListPosition.Random);
//or
  model.Routes = model.Routes.Add("All");

How do I use spaces in the Command Prompt?

If double quotes do not solve the issue then try e.g.

dir /X ~1 c:\

to get a list of alternative file or directory names. Example output:

11/09/2014 12:54 AM             8,065  DEFAUL~1.XML Default Desktop Policy.xml
06/12/2014  03:49 PM    <DIR>          PROGRA~1     Program Files 
10/12/2014  12:46 AM    <DIR>          PROGRA~2     Program Files (x86)

Now use the short 8 character file or folder name in the 5th column, e.g. PROGRA~1 or DEFAUL~1.XML, in your commands. For instance:

set JAVA_HOME=c:\PROGRA~1\Java\jdk1.6.0_45 

Android EditText view Floating Hint in Material Design

Import the Support Libraries, In your project's build.gradle file, add the following lines in the project's dependencies:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Use following TextInputLayout in your UI Layout:

<android.support.design.widget.TextInputLayout
    android:id="@+id/usernameWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="Username"/>

</android.support.design.widget.TextInputLayout>

Than, call setHint on TextInputLayout just after setContentView call because, to animate the floating label, you just need to set a hint, using the setHint method.

final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
usernameWrapper.setHint("Username");

How to convert a string to lower case in Bash?

Bash 5.1 provides a straight forward way to do this with the L parameter transformation:

${var@L}

So for example you can say:

$ v="heLLo"
$ echo "${v@L}"
hello

You can also do uppercase with U:

$ v="hello"
$ echo "${v@U}"
HELLO

And uppercase the first letter with u:

$ v="hello"
$ echo "${v@u}"
Hello

Best practice to look up Java Enum

Looks like you have a bad practice here but not where you think.

Catching an IllegalArgumentException to rethrow another RuntimeException with a clearer message might look like a good idea but it is not. Because it means you care about messages in your exceptions.

If you care about messages in your exceptions, then it means that your user is somehow seeing your exceptions. This is bad.

If you want to provide an explicit error message to your user, you should check the validity of the enum value when parsing user input and send the appropriate error message in the response if user input is incorrect.

Something like:

// This code uses pure fantasy, you are warned!
class MyApi
{
    // Return the 24-hour from a 12-hour and AM/PM

    void getHour24(Request request, Response response)
    {
        // validate user input
        int nTime12 = 1;
        try
        {
            nTime12 = Integer.parseInt(request.getParam("hour12"));
            if( nTime12 <= 0 || nTime12 > 12 )
            {
                throw new NumberFormatException();
            }
        }
        catch( NumberFormatException e )
        {
            response.setCode(400); // Bad request
            response.setContent("time12 must be an integer between 1 and 12");
            return;
        }

        AMPM pm = null;
        try
        {
            pm = AMPM.lookup(request.getParam("pm"));
        }
        catch( IllegalArgumentException e )
        {
            response.setCode(400); // Bad request
            response.setContent("pm must be one of " + AMPM.values());
            return;
        }

        response.setCode(200);
        switch( pm )
        {
            case AM:
                response.setContent(nTime12);
                break;
            case PM:
                response.setContent(nTime12 + 12);
                break;
        }
        return;
    }
}

'heroku' does not appear to be a git repository

Following official Heroku article:

Initialize GIT

$ cd myapp
$ git init

$ git add .
$ git commit -m "my first commit"

Then create (initialize) heroku app with:

$ heroku create YourAppName

Lastly add git remote:

$ heroku git:remote -a YourAppName

Now you can safely deploy your app with:

$ git push heroku master

You should wait for some time and see if you don't get any error/interrupt on console while deploying. For details look at heroku article.

How to check empty DataTable

This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:

if ((dataTableName?.Rows?.Count ?? 0) > 0)

How best to read a File into List<string>

A little update to Evan Mulawski answer to make it shorter

List<string> allLinesText = File.ReadAllLines(fileName).ToList()

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

A Generic error occurred in GDI+ in Bitmap.Save method

This error message is displayed if the path you pass to Bitmap.Save() is invalid (folder doesn't exist etc).

How to Import 1GB .sql file to WAMP/phpmyadmin

I've tried with the SQLyog and It has done the work.

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

ngFor with index as value in attribute

with laravel pagination

file.component.ts file

    datasource: any = {
        data: []
    }

    loadData() {
        this.service.find(this.params).subscribe((res: any) => {
            this.datasource = res;
        });
    }

html file

   <tr *ngFor="let item of datasource.data; let i = index">
       <th>{{ datasource.from + i }}</th>
   </tr>

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Is there a better way to do optional function parameters in JavaScript?

In all cases where optionalArg is falsy you will end up with defaultValue.

function myFunc(requiredArg, optionalArg) {
    optionalArg = optionalArg || 'defaultValue';
    console.log(optionalArg);
    // Do stuff
}
myFunc(requiredArg);
myFunc(requiredArg, null);
myFunc(requiredArg, undefined);
myFunc(requiredArg, "");
myFunc(requiredArg, 0);
myFunc(requiredArg, false);

All of the above log defaultValue, because all of 6 are falsy. In case 4, 5, 6 you might not be interested to set optionalArg as defaultValue, but it sets since they are falsy.

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

Split array into chunks

Using generators

_x000D_
_x000D_
function* chunks(arr, n) {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

let someArray = [0,1,2,3,4,5,6,7,8,9]
console.log([...chunks(someArray, 2)]) // [[0,1],[2,3],[4,5],[6,7],[8,9]]
_x000D_
_x000D_
_x000D_

Laravel Request getting current path with query string

Similar to Yada's answer: $request->url() will also work if you are injecting Illuminate\Http\Request

Edit: The difference between fullUrl and url is the fullUrl includes your query parameters

Disable validation of HTML5 form elements

Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.

window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
    if(!window.submittingForm){
        window.submittingForm = true;
        $(e.target.form).submit();
        setTimeout(function(){window.submittingForm = false;}, 100);
    }
    e.preventDefault();
    return false;
});

How to set image in imageview in android?

if u want to set a bitmap object to image view here is simple two line`

Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sample_drawable_image);
image.setImageBitmap(bitmap);

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

Connecting to SQL Server with Visual Studio Express Editions

If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.

How do I ignore files in a directory in Git?

Paths which contain slashes are taken to be relative to the directory containing the .gitignore file - usually the top level of your repository, though you can also place them in subdirectories.

So, since in all of the examples you give, the paths contain slashes, the two versions are identical. The only time you need to put a leading slash is when there isn't one in the path already. For example, to ignore foo only at the top level of the repository, use /foo. Simply writing foo would ignore anything called foo anywhere in the repository.

Your wildcards are also redundant. If you want to ignore an entire directory, simply name it:

lib/model/om

The only reason to use wildcards the way you have is if you intend to subsequently un-ignore something in the directory:

lib/model/om/*      # ignore everything in the directory
!lib/model/om/foo   # except foo

How do I check if a column is empty or null in MySQL?

Either

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename

or

SELECT case when field1 IS NULL or field1 = ''
        then 'empty'
        else field1
   end as field1 from tablename

How to serve up a JSON response using Go?

In gobuffalo.io framework I got it to work like this:

// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.

How to cd into a directory with space in the name?

Instead of:

DOCS="/cygdrive/c/Users/my\ dir/Documents"

Try:

DOCS="/cygdrive/c/Users/my dir/Documents" 

This should work on any POSIX system.

What JSON library to use in Scala?

Number 7 on the list is Jackson, not using Jerkson. It has support for Scala objects, (case classes etc).

Below is an example of how I use it.

object MyJacksonMapper extends JacksonMapper
val jsonString = MyJacksonMapper.serializeJson(myObject)
val myNewObject = MyJacksonMapper.deserializeJson[MyCaseClass](jsonString)

This makes it very simple. In addition is the XmlSerializer and support for JAXB Annotations is very handy.

This blog post describes it's use with JAXB Annotations and the Play Framework.

http://krasserm.blogspot.co.uk/2012/02/using-jaxb-for-xml-and-json-apis-in.html

Here is my current JacksonMapper.

trait JacksonMapper {

  def jsonSerializer = {
    val m = new ObjectMapper()
    m.registerModule(DefaultScalaModule)
    m
  }

  def xmlSerializer = {
    val m = new XmlMapper()
    m.registerModule(DefaultScalaModule)
    m
  }

  def deserializeJson[T: Manifest](value: String): T = jsonSerializer.readValue(value, typeReference[T])
  def serializeJson(value: Any) = jsonSerializer.writerWithDefaultPrettyPrinter().writeValueAsString(value)
  def deserializeXml[T: Manifest](value: String): T = xmlSerializer.readValue(value, typeReference[T])
  def serializeXml(value: Any) = xmlSerializer.writeValueAsString(value)

  private[this] def typeReference[T: Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  private[this] def typeFromManifest(m: Manifest[_]): Type = {
     if (m.typeArguments.isEmpty) { m.erasure }
     else new ParameterizedType {
       def getRawType = m.erasure

       def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray

       def getOwnerType = null
     }
  }
}   

Get class list for element with jQuery

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);

Make body have 100% of the browser height

You can also use JS if needed

var winHeight = window.innerHeight    || 
document.documentElement.clientHeight || 
document.body.clientHeight;

var pageHeight = $('body').height();
if (pageHeight < winHeight) {
    $('.main-content,').css('min-height',winHeight)
}

MySQL "between" clause not inclusive?

You can run the query as:

select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'

like others pointed out, if your dates are hardcoded.

On the other hand, if the date is in another table, you can add a day and subtract a second (if the dates are saved without the second/time), like:

select * from person JOIN some_table ... where dob between some_table.initial_date and (some_table.final_date + INTERVAL 1 DAY - INTERVAL 1 SECOND)

Avoid doing casts on the dob fiels (like in the accepted answer), because that can cause huge performance problems (like not being able to use an index in the dob field, assuming there is one). The execution plan may change from using index condition to using where if you make something like DATE(dob) or CAST(dob AS DATE), so be careful!

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

After installing run below command

sudo chmod 755 -R laravel
chmod -R o+w laravel/storage

here "laravel" is the name of directory where laravel installed

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to remove newlines from beginning and end of a string?

Another elegant solution.

String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");

set date in input type date

document.getElementById("datePicker").valueAsDate = new Date()

should work.

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

If your git was already set to something and you only copied that folder to some other location, simply run:

git config --global http.proxy ""

And git will set itself straight, after what, you can pull again :)

In PANDAS, how to get the index of a known value?

The other way around using numpy.where() :

import numpy as np
import pandas as pd

In [800]: df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])

In [801]: df
Out[801]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [802]: np.where(df["c1"]==6)
Out[802]: (array([3]),)

In [803]: indices = list(np.where(df["c1"]==6)[0])

In [804]: df.iloc[indices]
Out[804]: 
   c1  c2
3   6   7

In [805]: df.iloc[indices].index
Out[805]: Int64Index([3], dtype='int64')

In [806]: df.iloc[indices].index.tolist()
Out[806]: [3]

Read text from response

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();

How to add/update child entities when updating a parent entity in EF

Refer below code snippet from one of my projects where I implemented the same thing. It will make save data if new entry, updates if existing and delete if record is not available in the posting json. Json Data to help you understand the schema:

{
    "groupId": 1,
    "groupName": "Group 1",
    "sortOrder": 1,
    "filterNames": [
        {
            "filterId": 1,
            "filterName1": "Name11111",
            "sortOrder": 10,
            "groupId": 1           
        }  ,
        {
            "filterId": 1006,
            "filterName1": "Name Changed 1",
            "sortOrder": 10,
            "groupId": 1           
        }  ,
        {
            "filterId": 1007,
            "filterName1": "New Filter 1",
            "sortOrder": 10,
            "groupId": 1           
        } ,
        {
            "filterId": 2,
            "filterName1": "Name 2 Changed",
            "sortOrder": 10,
            "groupId": 1           
        }                 
    ]
}


public async Task<int> UpdateFilter(FilterGroup filterGroup)
        {                        
            var Ids = from f in filterGroup.FilterNames select f.FilterId;
            var toBeDeleted = dbContext.FilterNames.Where(x => x.GroupId == filterGroup.GroupId
            && !Ids.Contains(x.FilterId)).ToList();
            foreach(var item in toBeDeleted)
            {
                dbContext.FilterNames.Remove(item);
            }
            await dbContext.SaveChangesAsync();

            dbContext.FilterGroups.Attach(filterGroup);
            dbContext.Entry(filterGroup).State = EntityState.Modified;
            for(int i=0;i<filterGroup.FilterNames.Count();i++)            
            {
                if (filterGroup.FilterNames.ElementAt(i).FilterId != 0)
                {
                    dbContext.Entry(filterGroup.FilterNames.ElementAt(i)).State = EntityState.Modified;
                }
            }            
            return await dbContext.SaveChangesAsync();
        }

Fastest way to check if a string is JSON in PHP?

Another simple way

function is_json($str)
{
    return is_array(json_decode($str,true));
}

Spark DataFrame groupBy and sort in the descending order (pyspark)

Use orderBy:

df.orderBy('column_name', ascending=False)

Complete answer:

group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Android WSDL/SOAP service client

i founded this tool to auto generate wsdl to android code,

http://www.wsdl2code.com/Example.aspx

public void callWebService(){
    SampleService srv1 = new SampleService();
    Request req = new Request();
    req.companyId = "1";
    req.userName = "userName";
    req.password = "pas";
    Response response =  srv1.ServiceSample(req);
}

How do I delete all messages from a single queue using the CLI?

To purge queue you can use following command (more information in API doc):

curl -i -u guest:guest -XDELETE http://localhost:15672/api/queues/vhost_name/queue_name/contents

Getting mouse position in c#

To answer your specific example:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

Don't forget to add using System.Windows.Forms;, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)

Gunicorn worker timeout error

WORKER TIMEOUT means your application cannot response to the request in a defined amount of time. You can set this using gunicorn timeout settings. Some application need more time to response than another.

Another thing that may affect this is choosing the worker type

The default synchronous workers assume that your application is resource-bound in terms of CPU and network bandwidth. Generally this means that your application shouldn’t do anything that takes an undefined amount of time. An example of something that takes an undefined amount of time is a request to the internet. At some point the external network will fail in such a way that clients will pile up on your servers. So, in this sense, any web application which makes outgoing requests to APIs will benefit from an asynchronous worker.

When I got the same problem as yours (I was trying to deploy my application using Docker Swarm), I've tried to increase the timeout and using another type of worker class. But all failed.

And then I suddenly realised I was limitting my resource too low for the service inside my compose file. This is the thing slowed down the application in my case

deploy:
  replicas: 5
  resources:
    limits:
      cpus: "0.1"
      memory: 50M
  restart_policy:
    condition: on-failure

So I suggest you to check what thing slowing down your application in the first place

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

how to implement login auth in node.js

Actually this is not really the answer of the question, but this is a better way to do it.

I suggest you to use connect/express as http server, since they save you a lot of time. You obviously don't want to reinvent the wheel. In your case session management is much easier with connect/express.

Beside that for authentication I suggest you to use everyauth. Which supports a lot of authentication strategies. Awesome for rapid development.

All this can be easily down with some copy pasting from their documentation!

Set session variable in laravel

For example, To store data in the session, you will typically use the putmethod or the session helper:

// Via a request instance...
$request->session()->put('key', 'value');

or

// Via the global helper...
session(['key' => 'value']);

for retrieving an item from the session, you can use get :

$value = $request->session()->get('key', 'default value');

or global session helper :

$value = session('key', 'default value');

To determine if an item is present in the session, you may use the has method:

if ($request->session()->has('users')) {
//
}

Creating object with dynamic keys

You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).

How to pass parameters in GET requests with jQuery

You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL

Source: http://api.jquery.com/jQuery.ajax/

CSS - display: none; not working

Check following html I removed display:block from style

<div id="tfl" style="width: 187px; height: 260px; font-family: Verdana, Arial, Helvetica, sans-serif !important; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/widget-panel.gif) #fff no-repeat; font-size: 11px; border: 1px solid #103994; border-radius: 4px; box-shadow: 2px 2px 3px 1px #ccc;">
        <div style="display: block; padding: 30px 0 15px 0;">
            <h2 style="color: rgb(36, 66, 102); text-align: center; display: block; font-size: 15px; font-family: arial; border: 0; margin-bottom: 1em; margin-top: 0; font-weight: bold !important; background: 0; padding: 0">Journey Planner</h2>
            <form action="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2" id="jpForm" method="post" target="tfl" style="margin: 5px 0 0 0 !important; padding: 0 !important;">
                <input type="hidden" name="language" value="en" />
                <!-- in language = english -->
                <input type="hidden" name="execInst" value="" /><input type="hidden" name="sessionID" value="0" />
                <!-- to start a new session on JP the sessionID has to be 0 -->
                <input type="hidden" name="ptOptionsActive" value="-1" />
                <!-- all pt options are active -->
                <input type="hidden" name="place_origin" value="London" />
                <!-- London is a hidden parameter for the origin location -->
                <input type="hidden" name="place_destination" value="London" /><div style="padding-right: 15px; padding-left: 15px">
                    <input type="text" name="name_origin" style="width: 155px !important; padding: 1px" value="From" /><select style="width: 155px !important; margin: 0 !important;" name="type_origin"><option value="stop">Station or stop</option>
                        <option value="locator">Postcode</option>
                        <option value="address">Address</option>
                        <option value="poi">Place of interest</option>
                    </select>
                </div>
                <div style="margin-top: 10px; margin-bottom: 4px; padding-right: 15px; padding-left: 15px; padding-bottom: 15px; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom;">
                    <input type="text" name="name_destination" style="width: 100% !important; padding: 1px" value="232 Kingsbury Road (NW9)" /><select style="width: 155px !important; margin-top: 0 !important;" name="type_destination"><option value="stop">Station or stop</option>
                        <option value="locator">Postcode</option>
                        <option value="address" selected="selected">Address</option>
                        <option value="poi">Place of interest</option>
                    </select>
                </div>
                <div style="background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom; padding-bottom: 2px; padding-top: 2px; overflow: hidden; margin-bottom: 8px">
                    <div style="clear: both; background: url(http://www.tfl.gov.uk/tfl-global/images/options-icons.gif) no-repeat 9.5em 0; height: 30px; padding-right: 15px; padding-left: 15px"><a style="text-decoration: none; color: #113B92; font-size: 11px; white-space: nowrap; display: inline-block; padding: 4px 0 5px 0; width: 155px" target="tfl" href="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2?language=en&amp;ptOptionsActive=1" onclick="javascript:document.getElementById('jpForm').ptOptionsActive.value='1';document.getElementById('jpForm').execInst.value='readOnly';document.getElementById('jpForm').submit(); return false">More options</a></div>
                </div>
                <div style="text-align: center;">
                    <input type="submit" title="Leave now" value="Leave now" style="border-style: none; background-color: #157DB9; display: inline-block; padding: 4px 11px; color: #fff; text-decoration: none; border-radius: 3px; border-radius: 3px; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border-bottom: 1px solid rgba(0,0,0,0.25); position: relative; cursor: pointer; font: bold  13px/1 Arial,Helvetica,sans-serif; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.4); line-height: 1;" />
                </div>
            </form>
        </div>
    </div

Why are iframes considered dangerous and a security risk?

"Dangerous" and "Security risk" are not the first things that spring to mind when people mention iframes … but they can be used in clickjacking attacks.

What do two question marks together mean in C#?

It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

expands to:

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

which further expands to:

if(formsAuth != null)
    FormsAuth = formsAuth;
else
    FormsAuth = new FormsAuthenticationWrapper();

In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."

Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer# to Answer (if all Answers are null then the Answer is null):

string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;

Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)

Java SSLException: hostname in certificate didn't match

You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.

// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";  
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

Android Preventing Double Click On A Button

final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    private final AtomicBoolean onClickEnabled = new AtomicBoolean(true);

    @Override
    public void onClick(View v) {
        Log.i("TAG", "onClick begin");
        if (!onClickEnabled.compareAndSet(true, false)) {
            Log.i("TAG", "onClick not enabled");
            return;
        }

        button.setEnabled(false);

        // your action here

        button.setEnabled(true);
        onClickEnabled.set(true);
        Log.i("TAG", "onClick end");
    }
});

xlsxwriter: is there a way to open an existing worksheet in my workbook?

After searching a bit about the method to open the existing sheet in xlxs, i discovered

existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')

You can now append/write any data to the open worksheet. I hope it helps. Thanks

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Datatables Select All Checkbox

The solution given by @annoyingmouse works for me.

But to use the checkbox in the header cell, I also had to fix select.dataTables.css.
It seems that they used :

table.dataTable tbody th.select-checkbox

instead of :

table.dataTable thead th.select-checkbox

So I had to add this to my css :

table.dataTable thead th.select-checkbox {
  position: relative;
}
table.dataTable thead th.select-checkbox:before,
table.dataTable thead th.select-checkbox:after {
  display: block;
  position: absolute;
  top: 1.2em;
  left: 50%;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
}
table.dataTable tbody td.select-checkbox:before,
table.dataTable thead th.select-checkbox:before {
  content: ' ';
  margin-top: -6px;
  margin-left: -6px;
  border: 1px solid black;
  border-radius: 3px;
}

Take the content of a list and append it to another list

You can simply concatnate two lists, e.g:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

Is there a better jQuery solution to this.form.submit();?

Your question in somewhat confusing in that that you don't explain what you mean by "current element".

If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.

But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.

Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:

<form action="...">
    <input type="hidden" name="rowId" value="...">
    <button type="submit" name="myaction" value="edit">Edit</button>
    <button type="submit" name="myaction" value="delete">Delete</button>
</form>

When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).

Then on the server you just read the value of the variable "myaction" and decide what to do.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

The AngularJS Bootstrap website hasn't been updated with the latest documentation. About 3 months ago pkozlowski-opensource authored a change to separate out $modal from $dialog commit is below:

https://github.com/angular-ui/bootstrap/commit/d7a48523e437b0a94615350a59be1588dbdd86bd

In that commit he added new documentation for $modal, which can be found below:

https://github.com/angular-ui/bootstrap/blob/d7a48523e437b0a94615350a59be1588dbdd86bd/src/modal/docs/readme.md.

Hope this helps!

include external .js file in node.js app

The correct answer is usually to use require, but in a few cases it's not possible.

The following code will do the trick, but use it with care:

var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

How do you determine the size of a file in C?

Don't use int. Files over 2 gigabytes in size are common as dirt these days

Don't use unsigned int. Files over 4 gigabytes in size are common as some slightly-less-common dirt

IIRC the standard library defines off_t as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.

If you're on windows, you should use GetFileSizeEx - it actually uses a signed 64 bit integer, so they'll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)

Reading a binary input stream into a single byte array in Java

You can read it by chunks (byte buffer[] = new byte[2048]) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.

Get array of object's keys

Of course, Object.keys() is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()'s behaviour).

However, your example code...

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
    keys.push(key);
}

jsFiddle.

...could be modified. You can do the assignment right in the variable part.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}

jsFiddle.

Of course, this behaviour is different to what Object.keys() actually does (jsFiddle). You could simply use the shim on the MDN documentation.

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

Ajax call Into MVC Controller- Url Issue

you have an type error in example of code. You forget curlybracket after success

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

Android replace the current fragment with another fragment

Use android.support.v4.app for FragmentManager & FragmentTransaction in your code, it has worked for me.

DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Shouldn't you have:

DELETE FROM tableA WHERE entitynum IN (...your select...)

Now you just have a WHERE with no comparison:

DELETE FROM tableA WHERE (...your select...)

So your final query would look like this;

DELETE FROM tableA WHERE entitynum IN (
    SELECT tableA.entitynum FROM tableA q
      INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
    WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
      AND (u.FldFormat = 'Date')
)

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to write a std::string to a UTF-8 text file

std::wstring text = L"??????";
QString qstr = QString::fromStdWString(text);
QByteArray byteArray(qstr.toUtf8());    
std::string str_std( byteArray.constData(), byteArray.length());

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

Select tableview row programmatically

Like Jaanus told:

Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.

So you just have to call the delegate method yourself.

For example:

Swift 3 version:

let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

ObjectiveC version:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath 
                            animated:YES 
                      scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

Swift 2.3 version:

 let indexPath = NSIndexPath(forRow: 0, inSection: 0);
 self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
 self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

What's the best way to check if a String represents an integer in Java?

Another option:

private boolean isNumber(String s) {
    boolean isNumber = true;
    for (char c : s.toCharArray()) {
        isNumber = isNumber && Character.isDigit(c);
    }
    return isNumber;
}

npm can't find package.json

Generate package.json without having it ask any questions. I ran the below comment in Mac and Windows under the directory that I would like to create package.json and it works

$ npm init -y

Wrote to C:\workspace\package.json:

{
  "name": "workspace",
  "version": "1.0.0",
  "description": "",
  "main": "builder.js",
  "dependencies": {
    "jasmine-spec-reporter": "^4.2.1",
    "selenium-webdriver": "^4.0.0-alpha.5"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

Create view with primary key?

You cannot create a primary key on a view. In SQL Server you can create an index on a view but that is different to creating a primary key.

If you give us more information as to why you want a key on your view, perhaps we can help with that.

Difference in make_shared and normal shared_ptr in C++

I see one problem with std::make_shared, it doesn't support private/protected constructors

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

Function vs. Stored Procedure in SQL Server

Stored procedure:

  • Is like a miniature program in SQL Server.
  • Can be as simple as a select statement, or as complex as a long script that adds, deletes, updates, and/or reads data from multiple tables in a database.
  • (Can implement loops and cursors, which both allow you to work with smaller results or row by row operations on data.)
  • Should be called using EXEC or EXECUTE statement.
  • Returns table variables, but we can't use OUT parameter.
  • Supports transactions.

Function:

  • Can not be used to update, delete, or add records to the database.
  • Simply returns a single value or a table value.
  • Can only be used to select records. However, it can be called very easily from within standard SQL, such as:

    SELECT dbo.functionname('Parameter1')
    

    or

    SELECT Name, dbo.Functionname('Parameter1') FROM sysObjects
    
  • For simple reusable select operations, functions can simplify code. Just be wary of using JOIN clauses in your functions. If your function has a JOIN clause and you call it from another select statement that returns multiple results, that function call will JOIN those tables together for each line returned in the result set. So though they can be helpful in simplifying some logic, they can also be a performance bottleneck if they're not used properly.

  • Returns the values using OUT parameter.
  • Does not support transactions.

Are nested try/except blocks in Python a good programming practice?

In my opinion, this would be the most Pythonic way to handle it, although and because it makes your question moot. Note that this defines __getattr__() instead of __getattribute__() , because doing so means it only has to deal with the "special" attributes being kept in the internal dictionary.

def __getattr__(self, name):
    """Only called when an attribute lookup in the usual places has failed"""
    try:
        return self.my_dict[name]
    except KeyError:
        raise AttributeError("some customized error message")

Checking during array iteration, if the current element is the last element

This always does the trick for me

foreach($array as $key => $value) {
   if (end(array_keys($array)) == $key)
       // Last key reached
}

Edit 30/04/15

$last_key = end(array_keys($array));
reset($array);

foreach($array as $key => $value) {
  if ( $key == $last_key)
      // Last key reached
}

To avoid the E_STRICT warning mentioned by @Warren Sergent

$array_keys = array_keys($array);
$last_key = end($array_keys);

sqlplus how to find details of the currently connected database session

Try:

select * from v$session where sid = SYS_CONTEXT('USERENV','SID');

You might also be interested in this AskTom post

After seing your comment, you can do:

SELECT * FROM global_name;

Capture Video of Android's Screen

Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:

adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4

Screen recording is limited to a maximum of 3 minutes.

Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord

How to add a "open git-bash here..." context menu to the windows explorer?

As, @Shaswat Rungta said: "I think the question is more about how to add it after the installation is over."

On my PC(Windows 7) I think that the command "Git Bash here" disappeard after I installed Visual Studio 2017.

I fixt this by downloading and installing Git again.


NOTE: "When installing Git for Windows the context menu options are not 'on' by default. You will have to select them during the install." – @nbushnell (I did this)

Transpose/Unzip Function (inverse of zip)?

While numpy arrays and pandas may be preferrable, this function imitates the behavior of zip(*args) when called as unzip(args).

Allows for generators, like the result from zip in Python 3, to be passed as args as it iterates through values.

def unzip(items, cls=list, ocls=tuple):
    """Zip function in reverse.

    :param items: Zipped-like iterable.
    :type  items: iterable

    :param cls: Container factory. Callable that returns iterable containers,
        with a callable append attribute, to store the unzipped items. Defaults
        to ``list``.
    :type  cls: callable, optional

    :param ocls: Outer container factory. Callable that returns iterable
        containers. with a callable append attribute, to store the inner
        containers (see ``cls``). Defaults to ``tuple``.
    :type  ocls: callable, optional

    :returns: Unzipped items in instances returned from ``cls``, in an instance
        returned from ``ocls``.
    """
    # iter() will return the same iterator passed to it whenever possible.
    items = iter(items)

    try:
        i = next(items)
    except StopIteration:
        return ocls()

    unzipped = ocls(cls([v]) for v in i)

    for i in items:
        for c, v in zip(unzipped, i):
            c.append(v)

    return unzipped

To use list cointainers, simply run unzip(zipped), as

unzip(zip(["a","b","c"],[1,2,3])) == (["a","b","c"],[1,2,3])

To use deques, or other any container sporting append, pass a factory function.

from collections import deque

unzip([("a",1),("b",2)], deque, list) == [deque(["a","b"]),deque([1,2])]

(Decorate cls and/or main_cls to micro manage container initialization, as briefly shown in the final assert statement above.)

Is there shorthand for returning a default value if None in Python?

You can use a conditional expression:

x if x is not None else some_value

Example:

In [22]: x = None

In [23]: print x if x is not None else "foo"
foo

In [24]: x = "bar"

In [25]: print x if x is not None else "foo"
bar

Appending to list in Python dictionary

list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date)

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

This will create a new list object, if the key is not found in the dictionary.

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

Best way to encode text data for XML in Java?

This has worked well for me to provide an escaped version of a text string:

public class XMLHelper {

/**
 * Returns the string where all non-ascii and <, &, > are encoded as numeric entities. I.e. "&lt;A &amp; B &gt;"
 * .... (insert result here). The result is safe to include anywhere in a text field in an XML-string. If there was
 * no characters to protect, the original string is returned.
 * 
 * @param originalUnprotectedString
 *            original string which may contain characters either reserved in XML or with different representation
 *            in different encodings (like 8859-1 and UFT-8)
 * @return
 */
public static String protectSpecialCharacters(String originalUnprotectedString) {
    if (originalUnprotectedString == null) {
        return null;
    }
    boolean anyCharactersProtected = false;

    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < originalUnprotectedString.length(); i++) {
        char ch = originalUnprotectedString.charAt(i);

        boolean controlCharacter = ch < 32;
        boolean unicodeButNotAscii = ch > 126;
        boolean characterWithSpecialMeaningInXML = ch == '<' || ch == '&' || ch == '>';

        if (characterWithSpecialMeaningInXML || unicodeButNotAscii || controlCharacter) {
            stringBuffer.append("&#" + (int) ch + ";");
            anyCharactersProtected = true;
        } else {
            stringBuffer.append(ch);
        }
    }
    if (anyCharactersProtected == false) {
        return originalUnprotectedString;
    }

    return stringBuffer.toString();
}

}

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

Responsive iframe using Bootstrap

Option 3

To update current iframe

$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');

How to reset form body in bootstrap modal box?

Just find your form and clear before it opens!

    $modal = $('#modal');
    $modal.find('form')[0].reset();

How do I disable the security certificate check in Python requests

Also can be done from the environment variable:

export CURL_CA_BUNDLE=""

Pandas percentage of total with groupby

I think this needs benchmarking. Using OP's original DataFrame,

df = pd.DataFrame({
    'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
    'office_id': range(1, 7) * 2,
    'sales': [np.random.randint(100000, 999999) for _ in range(12)]
})

1st Andy Hayden

As commented on his answer, Andy takes full advantage of vectorisation and pandas indexing.

c = df.groupby(['state', 'office_id'])['sales'].sum().rename("count")
c / c.groupby(level=0).sum()

3.42 ms ± 16.7 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)


2nd Paul H

state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100

4.66 ms ± 24.4 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)


3rd exp1orer

This is the slowest answer as it calculates x.sum() for each x in level 0.

For me, this is still a useful answer, though not in its current form. For quick EDA on smaller datasets, apply allows you use method chaining to write this in a single line. We therefore remove the need decide on a variable's name, which is actually very computationally expensive for your most valuable resource (your brain!!).

Here is the modification,

(
    df.groupby(['state', 'office_id'])
    .agg({'sales': 'sum'})
    .groupby(level=0)
    .apply(lambda x: 100 * x / float(x.sum()))
)

10.6 ms ± 81.5 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)


So no one is going care about 6ms on a small dataset. However, this is 3x speed up and, on a larger dataset with high cardinality groupbys this is going to make a massive difference.

Adding to the above code, we make a DataFrame with shape (12,000,000, 3) with 14412 state categories and 600 office_ids,

import string

import numpy as np
import pandas as pd
np.random.seed(0)

groups = [
    ''.join(i) for i in zip(
    np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
    np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
    np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
                       )
]

df = pd.DataFrame({'state': groups * 400,
               'office_id': list(range(1, 601)) * 20000,
               'sales': [np.random.randint(100000, 999999)
                         for _ in range(12)] * 1000000
})

Using Andy's,

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

and exp1orer

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

So now we see x10 speed up on large, high cardinality datasets.


Be sure to UV these three answers if you UV this one!!

SQL - How do I get only the numbers after the decimal?

The usual hack (which varies a bit in syntax) is

x - floor(x)

That's the fractional part. To make into an integer, scale it.

(x - floor(x)) * 1000

Java String new line

To make the code portable to any system, I would use:

public static String newline = System.getProperty("line.separator");

This is important because different OSs use different notations for newline: Windows uses "\r\n", Classic Mac uses "\r", and Mac and Linux both use "\n".

Commentors - please correct me if I'm wrong on this...

How to determine CPU and memory consumption from inside a process?

I used this following code in my C++ project and it worked fine:

static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;

double percent;

numProcessors = sysInfo.dwNumberOfProcessors;

//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime; 
FILETIME SysuserTime; 
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  

//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)

percent = 100*(numerator/denomenator);

Default string initialization: NULL or Empty?

For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:

if (s == "value")

I get a bad feeling. Why is there a string literal in this method? What's setting s? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare? Should I be creating an Enum and parsing into it?

From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.

Knowing this, I don't blink when I see something like this in our code base:

string msg = Validate(item);
if (msg != null)
{
   DisplayErrorMessage(msg);
   return;
}

I know that Validate would never return String.Empty, because we write better code than that.

Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty and when it should mean null.

(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)

Remove non-utf8 characters from string

If you apply utf8_encode() to an already UTF8 string it will return a garbled UTF8 output.

I made a function that addresses all this issues. It´s called Encoding::toUTF8().

You dont need to know what the encoding of your strings is. It can be Latin1 (ISO8859-1), Windows-1252 or UTF8, or the string can have a mix of them. Encoding::toUTF8() will convert everything to UTF8.

I did it because a service was giving me a feed of data all messed up, mixing those encodings in the same string.

Usage:

require_once('Encoding.php'); 
use \ForceUTF8\Encoding;  // It's namespaced now.

$utf8_string = Encoding::toUTF8($mixed_string);

$latin1_string = Encoding::toLatin1($mixed_string);

I've included another function, Encoding::fixUTF8(), which will fix every UTF8 string that looks garbled product of having been encoded into UTF8 multiple times.

Usage:

require_once('Encoding.php'); 
use \ForceUTF8\Encoding;  // It's namespaced now.

$utf8_string = Encoding::fixUTF8($garbled_utf8_string);

Examples:

echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");

will output:

Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football

Download:

https://github.com/neitanod/forceutf8

How to split data into 3 sets (train, validation and test)?

Numpy solution. We will shuffle the whole dataset first (df.sample(frac=1, random_state=42)) and then split our data set into the following parts:

  • 60% - train set,
  • 20% - validation set,
  • 20% - test set

In [305]: train, validate, test = \
              np.split(df.sample(frac=1, random_state=42), 
                       [int(.6*len(df)), int(.8*len(df))])

In [306]: train
Out[306]:
          A         B         C         D         E
0  0.046919  0.792216  0.206294  0.440346  0.038960
2  0.301010  0.625697  0.604724  0.936968  0.870064
1  0.642237  0.690403  0.813658  0.525379  0.396053
9  0.488484  0.389640  0.599637  0.122919  0.106505
8  0.842717  0.793315  0.554084  0.100361  0.367465
7  0.185214  0.603661  0.217677  0.281780  0.938540

In [307]: validate
Out[307]:
          A         B         C         D         E
5  0.806176  0.008896  0.362878  0.058903  0.026328
6  0.145777  0.485765  0.589272  0.806329  0.703479

In [308]: test
Out[308]:
          A         B         C         D         E
4  0.521640  0.332210  0.370177  0.859169  0.401087
3  0.333348  0.964011  0.083498  0.670386  0.169619

[int(.6*len(df)), int(.8*len(df))] - is an indices_or_sections array for numpy.split().

Here is a small demo for np.split() usage - let's split 20-elements array into the following parts: 80%, 10%, 10%:

In [45]: a = np.arange(1, 21)

In [46]: a
Out[46]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])

In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))])
Out[47]:
[array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]),
 array([17, 18]),
 array([19, 20])]

How to undo a git pull?

Or to make it more explicit than the other answer:

git pull 

whoops?

git reset --keep HEAD@{1}

Versions of git older than 1.7.1 do not have --keep. If you use such version, you could use --hard - but that is a dangerous operation because it loses any local changes.


To the commenter

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation)

How to initialize an array in Kotlin with values?

Kotlin language has specialised classes for representing arrays of primitive types without boxing overhead: for instance – IntArray, ShortArray, ByteArray, etc. I need to say that these classes have no inheritance relation to the parent Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function. So, to initialise an array with values in Kotlin you just need to type this:

val myArr: IntArray = intArrayOf(10, 20, 30, 40, 50)

...or this way:

val myArr = Array<Int>(5, { i -> ((i+1) * 10) })

myArr.forEach { println(it) }                                // 10, 20, 30, 40, 50

Now you can use it:

myArr[0] = (myArr[1] + myArr[2]) - myArr[3]

How can I mix LaTeX in with Markdown?

kramdown does exactly what you describe:

https://kramdown.gettalong.org/syntax.html#math-blocks

And it's way more reliable and well-defined than Markdown.

horizontal line and right way to code it in html, css

I'd go for semantic markup, use an <hr/>.

Unless it's just a border what you want, then you can use a combination of padding, border and margin, to get the desired bound.

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

How do I check if a file exists in Java?

first hit for "java file exists" on google:

import java.io.*;

public class FileTest {
    public static void main(String args[]) {
        File f = new File(args[0]);
        System.out.println(f + (f.exists()? " is found " : " is missing "));
    }
}

How do I read a date in Excel format in Python?

For quick and dirty:

year, month, day, hour, minute, second = xlrd.xldate_as_tuple(excelDate, wb.datemode)
whatYouWant = str(month)+'/'+str(day)+'/'+str(year)

Peak memory usage of a linux/unix process

(This is an already answered, old question.. but just for the record :)

I was inspired by Yang's script, and came up with this small tool, named memusg. I simply increased the sampling rate to 0.1 to handle much short living processes. Instead of monitoring a single process, I made it measure rss sum of the process group. (Yeah, I write lots of separate programs that work together) It currently works on Mac OS X and Linux. The usage had to be similar to that of time:

memusg ls -alR / >/dev/null

It only shows the peak for the moment, but I'm interested in slight extensions for recording other (rough) statistics.

It's good to have such simple tool for just taking a look before we start any serious profiling.

Creating a very simple 1 username/password login in php

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in

How do you display code snippets in MS Word preserving format and syntax highlighting?

You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).

SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.

Accessing an array out of bounds gives no error, why?

As I understand, local variables are allocated on stack, so going out of bounds on your own stack can only overwrite some other local variable, unless you go oob too much and exceed your stack size. Since you have no other variables declared in your function - it does not cause any side effects. Try declaring another variable/array right after your first one and see what will happen with it.

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

@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.

It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:

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

If you're using perl, then you can get the values out with something like this:

$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$minute = $5;
$second = $6;

Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

DISABLE the Horizontal Scroll

.name 
  { 
      max-width: 100%; 
       overflow-x: hidden; 
   }

You apply the above style or you can create function in javaScript to solve that problem

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Whenever you start Visual Studio run it as administrator. It works for me.

Focus Input Box On Load

Try:

Javascript Pure:

[elem][n].style.visibility='visible';
[elem][n].focus();

Jquery:

[elem].filter(':visible').focus();

explode string in jquery

if your input's id is following

<input type='text'  id='kg_row1' >

then you can get explode/split the above with the following function of split in jquery

  var kg_id = $(this).attr("id");
  var getvalues =kg_id.split("_");
  var id = getvalues[1];

Check if option is selected with jQuery, if not select a default

Here is my function changing the selected option. It works for jQuery 1.3.2

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}

How to Implement Custom Table View Section Headers and Footers with Storyboard

If you use storyboards you can use a prototype cell in the tableview to layout your header view. Set an unique id and viewForHeaderInSection you can dequeue the cell with that ID and cast it to a UIView.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

urlencoded Forward slash is breaking URL

Apache denies all URLs with %2F in the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between %2F and / due to the PATH_INFO environment variable being automatically URL-decoded (which is stupid, but a long-standing part of the CGI specification so there's nothing can be done about it).

You can turn this feature off using the AllowEncodedSlashes directive, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg. %5C), and that %00 in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have %2F or other characters in a path part you'd be limiting your compatibility/deployment options.

I am using urlencode() while preparing the search URL

You should use rawurlencode(), not urlencode() for escaping path parts. urlencode() is misnamed, it is actually for application/x-www-form-urlencoded data such as in the query string or the body of a POST request, and not for other parts of the URL.

The difference is that + doesn't mean space in path parts. rawurlencode() will correctly produce %20 instead, which will work both in form-encoded data and other parts of the URL.

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

Iterate Multi-Dimensional Array with Nested Foreach Statement

If you want to iterate over every item in the array as if it were a flattened array, you can just do:

foreach (int i in array) {
    Console.Write(i);
}

which would print

123456

If you want to be able to know the x and y indexes as well, you'll need to do:

for (int x = 0; x < array.GetLength(0); x += 1) {
    for (int y = 0; y < array.GetLength(1); y += 1) {
        Console.Write(array[x, y]);
    }
}

Alternatively you could use a jagged array instead (an array of arrays):

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}

or

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
    for (int k = 0; k < array[j].Length; k += 1) {
        Console.Write(array[j][k]);
    }
}

App not setup: This app is still in development mode

Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission

  1. The app are not in Live Mode
  2. You are not listed as admin or a tester in
    https://developers.facebook.com/app/yourapp
  3. Your App Hashkey are not set. if Facebook app cant be on Live Mode you need a hashkey to test it. because the app are not yet Live. Facebook wont allow an access.

HOW TO CHANGE TO LIVE MODE
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. toggle the switch from OFF to ON

enter image description hereenter image description here

HOW TO ADD AS TEST OR ADMIN
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. go to : Roles > Roles > Press Add for example administratorenter image description here 4. Search your new admin/tester Facebook account.
enter image description here 5. admin must enter facebook password to confirm.then submit enter image description here
the new admin must go to developer.facebook page and accept the request
6. go to : https://developers.facebook.com

7. Profile > Requests > Confirm
enter image description here List item 8. Congratulation you have been assign as new Admin

HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
as Refer to Facebook Login Documentation
https://developers.facebook.com/docs/android/getting-started/#create_hash
The most preferable solution by me is by code ( Troubleshooting Sample Apps )
it will print out the hash key. you can update it on
https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
on Android > Key Hashes section

a step by step process on how to get the hashKey.

  1. Firstly Add the code to any oncreate method enter image description here

  2. Run The app and Search the KeyHash at Logcat enter image description here

step by step process on how Update on Facebook Developer.

  1. Open Facebook Developer Page. You need access as to update the Facebook Developer page.
    https://developers.facebook.com

  2. Follow the step as follow.enter image description here

How can I create a self-signed cert for localhost?

After spending a good amount of time on this issue I found whenever I followed suggestions of using IIS to make a self signed certificate, I found that the Issued To and Issued by was not correct. SelfSSL.exe was the key to solving this problem. The following website not only provided a step by step approach to making self signed certificates, but also solved the Issued To and Issued by problem. Here is the best solution I found for making self signed certificates. If you'd prefer to see the same tutorial in video form click here.

A sample use of SelfSSL would look something like the following:

SelfSSL /N:CN=YourWebsite.com /V:1000 /S:2

SelfSSL /? will provide a list of parameters with explanation.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Element-wise addition of 2 lists?

Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).

How do I remove the title bar from my app?

For Beginner Like Me. Just Do it what I say.From your Android Project.

app -> res -> values -> style.xml

replace this code

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

</resources>

Enjoy.