Programs & Examples On #Autofixture

AutoFixture is an open source library for .NET designed to minimize the 'Arrange' phase of your unit tests. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.

How do I list / export private keys from a keystore?

A portion of code originally from Example Depot for listing all of the aliases in a key store:

    // Load input stream into keystore
    keystore.load(is, password.toCharArray());

    // List the aliases
    Enumeration aliases = keystore.aliases();
    for (; aliases.hasMoreElements(); ) {
        String alias = (String)aliases.nextElement();

        // Does alias refer to a private key?
        boolean b = keystore.isKeyEntry(alias);

        // Does alias refer to a trusted certificate?
        b = keystore.isCertificateEntry(alias);
    }

The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app.

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        String b64 = new BASE64Encoder().encode(key.getEncoded());
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

Note: this use Sun package, which is a "bad thing".
If you can download apache commons code, here is a version which will compile without warning:

javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java

and will give the same result:

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        //String b64 = new BASE64Encoder().encode(key.getEncoded());
        String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

You can use it like so:

java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat

ReactJS: "Uncaught SyntaxError: Unexpected token <"

Add type="text/babel" to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>

What is the difference between public, protected, package-private and private in Java?

It's actually a bit more complicated than a simple grid shows. The grid tells you whether an access is allowed, but what exactly constitutes an access? Also, access levels interact with nested classes and inheritance in complex ways.

The "default" access (specified by the absence of a keyword) is also called package-private. Exception: in an interface, no modifier means public access; modifiers other than public are forbidden. Enum constants are always public.

Summary

Is an access to a member with this access specifier allowed?

  • Member is private: Only if member is defined within the same class as calling code.
  • Member is package private: Only if the calling code is within the member's immediately enclosing package.
  • Member is protected: Same package, or if member is defined in a superclass of the class containing the calling code.
  • Member is public: Yes.

What access specifiers apply to

Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.

For classes in the top scope, only public and package-private are permitted. This design choice is presumably because protected and private would be redundant at the package level (there is no inheritance of packages).

All the access specifiers are possible on class members (constructors, methods and static member functions, nested classes).

Related: Java Class Accessibility

Order

The access specifiers can be strictly ordered

public > protected > package-private > private

meaning that public provides the most access, private the least. Any reference possible on a private member is also valid for a package-private member; any reference to a package-private member is valid on a protected member, and so on. (Giving access to protected members to other classes in the same package was considered a mistake.)

Notes

  • A class's methods are allowed to access private members of other objects of the same class. More precisely, a method of class C can access private members of C on objects of any subclass of C. Java doesn't support restricting access by instance, only by class. (Compare with Scala, which does support it using private[this].)
  • You need access to a constructor to construct an object. Thus if all constructors are private, the class can only be constructed by code living within the class (typically static factory methods or static variable initializers). Similarly for package-private or protected constructors.
    • Only having private constructors also means that the class cannot be subclassed externally, since Java requires a subclass's constructors to implicitly or explicitly call a superclass constructor. (It can, however, contain a nested class that subclasses it.)

Inner classes

You also have to consider nested scopes, such as inner classes. An example of the complexity is that inner classes have members, which themselves can take access modifiers. So you can have a private inner class with a public member; can the member be accessed? (See below.) The general rule is to look at scope and think recursively to see whether you can access each level.

However, this is quite complicated, and for full details, consult the Java Language Specification. (Yes, there have been compiler bugs in the past.)

For a taste of how these interact, consider this example. It is possible to "leak" private inner classes; this is usually a warning:

class Test {
    public static void main(final String ... args) {
        System.out.println(Example.leakPrivateClass()); // OK
        Example.leakPrivateClass().secretMethod(); // error
    }
}

class Example {
    private static class NestedClass {
        public void secretMethod() {
            System.out.println("Hello");
        }
    }
    public static NestedClass leakPrivateClass() {
        return new NestedClass();
    }
}

Compiler output:

Test.java:4: secretMethod() in Example.NestedClass is defined in an inaccessible class or interface
        Example.leakPrivateClass().secretMethod(); // error
                                  ^
1 error

Some related questions:

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

Create patch or diff file from git repository and apply it to another different git repository

As a complementary, to produce patch for only one specific commit, use:

git format-patch -1 <sha>

When the patch file is generated, make sure your other repo knows where it is when you use git am ${patch-name}

Before adding the patch, use git apply --check ${patch-name} to make sure that there is no confict.

How to find the nearest parent of a Git branch?

I'm not saying this is a good way to solve this problem, however this does seem to work-for-me.

git branch --contains $(cat .git/ORIG_HEAD) The issue being that cat'ing a file is peeking into the inner working of git so this is not necessarily forwards-compatible (or backwards-compatible).

UIImage resize (Scale proportion)

This change worked for me:

// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width; 
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);

'MOD' is not a recognized built-in function name

In TSQL, the modulo is done with a percent sign.

SELECT 38 % 5 would give you the modulo 3

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

UnicodeDecodeError, invalid continuation byte

I had the same error when I tried to open a CSV file by pandas.read_csv method.

The solution was change the encoding to latin-1:

pd.read_csv('ml-100k/u.item', sep='|', names=m_cols , encoding='latin-1')

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

Open Command prompt type this..

"c:\Program Files(x86)\Java\jdk1.7.0\bin\keytool.exe" -list -v -alias androiddebugkey -keystore "C:\Users\EIS.android\debug.keystore" -storepass android -keypass android

Then Hit Enter MD5 and SHA1 key will get

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffcc5d00" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image1"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image2"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image3"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image4"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to detect scroll position of page using jQuery

GET Scroll Position:

var scrolled_val = window.scrollY;

DETECT Scroll Position:

$(window).scroll
(
     function (event) 
     {
          var scrolled_val = window.scrollY;
          alert(scrolled_val);
     }
 );

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

How to make scipy.interpolate give an extrapolated result beyond the input range?

As of SciPy version 0.17.0, there is a new option for scipy.interpolate.interp1d that allows extrapolation. Simply set fill_value='extrapolate' in the call. Modifying your code in this way gives:

import numpy as np
from scipy import interpolate

x = np.arange(0,10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, fill_value='extrapolate')

print f(9)
print f(11)

and the output is:

0.0497870683679
0.010394302658

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

Which TensorFlow and CUDA version combinations are compatible?

The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.

For tensorflow-gpu==1.12.0 and cuda==9.0, the compatible cuDNN version is 7.1.4, which can be downloaded from here after registration.

You can check your cuda version using
nvcc --version

cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2

tensorflow-gpu version using
pip freeze | grep tensorflow-gpu

UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).

  • tensorflow-gpu = 2.0.0
  • cuda = 10.0
  • cuDNN = 7.6.0

Splitting words into letters in Java

You can use

String [] strArr = Str.split("");

Default port for SQL Server

SQL Server default port is 1434.

To allow remote access I had to release those ports on my firewall:

Protocol  |   Port
---------------------
UDP       |   1050
TCP       |   1050
TCP       |   1433
UDP       |   1434

How can I get CMake to find my alternative Boost installation?

I had a similar issue, CMake finding a vendor-installed Boost only, but my cluster had a locally installed version which is what I wanted it to use. Red Hat Linux 6.

Anyway, it looks like all the BOOSTROOT, BOOST_ROOT, and Boost_DIR stuff would get annoyed unless one also sets Boost_NO_BOOST_CMAKE (e.g add to cmd line -DBoost_NO_BOOST_CMAKE=TRUE).

(I will concede the usefulness of CMake for multiplatform, but I can still hate it.)

How can I get the line number which threw exception?

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

Note that this will only work if there is a pdb file available for the assembly.

How do I retrieve my MySQL username and password?

An improvement to the most useful answer here:

1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network

There is no need to restart the MySQL server.

use FLUSH PRIVILEGES; after the update mysql.user statement for password change.

The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

The --skip-grant-options enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to

use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.

from: reference: resetting-permissions-generic

IIS - can't access page by ip address instead of localhost

Follow the below steps -

  1. In IIS Right click the "Default Web Site"
  2. Click Edit Buildings in the context menu
  3. Select and edit
  4. Give your machine IP instead of "*" in IP Address

How to find specific lines in a table using Selenium?

you can try following

int index = 0;
WebElement baseTable = driver.findElement(By.className("table gradient myPage"));
List<WebElement> tableRows = baseTable.findElements(By.tagName("tr"));
tableRows.get(index).getText();

You can also iterate over tablerows to perform any function you want.

How to call a method in another class in Java?

Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");

You have to add the class' and at a point like

yourClassNameWhereTheMethodIs.theMethodsName();

I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

Serialize and Deserialize Json and Json Array in Unity

To Read JSON File, refer this simple example

Your JSON File (StreamingAssets/Player.json)

{
    "Name": "MyName",
    "Level": 4
}

C# Script

public class Demo
{
    public void ReadJSON()
    {
        string path = Application.streamingAssetsPath + "/Player.json";
        string JSONString = File.ReadAllText(path);
        Player player = JsonUtility.FromJson<Player>(JSONString);
        Debug.Log(player.Name);
    }
}

[System.Serializable]
public class Player
{
    public string Name;
    public int Level;
}

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

Query to get the names of all tables in SQL Server 2008 Database

In a single database - yes:

USE your_database
SELECT name FROM sys.tables

Getting all tables across all databases - only with a hack.... see this SO question for several approaches how to do that: How do I list all tables in all databases in SQL Server in a single result set?

How to print the current Stack Trace in .NET without any exception?

You can also do this in the Visual Studio debugger without modifying the code.

  1. Create a breakpoint where you want to see the stack trace.
  2. Right-click the breakpoint and select "Actions..." in VS2015. In VS2010, select "When Hit...", then enable "Print a message".
  3. Make sure "Continue execution" is selected.
  4. Type in some text you would like to print out.
  5. Add $CALLSTACK wherever you want to see the stack trace.
  6. Run the program in the debugger.

Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.

How to Use Order By for Multiple Columns in Laravel 4?

Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:

public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
    $result = $this->model->with($with);
    $dataSet = $result->where($where)
        // Conditionally use $orderBy if not empty
        ->when(!empty($orderBy), function ($query) use ($orderBy) {
            // Break $orderBy into pairs
            $pairs = array_chunk($orderBy, 2);
            // Iterate over the pairs
            foreach ($pairs as $pair) {
                // Use the 'splat' to turn the pair into two arguments
                $query->orderBy(...$pair);
            }
        })
        ->paginate($limit)
        ->appends(Input::except('page'));

    return $dataSet;
}

Now, you can make your call like this:

$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);

Error: Cannot invoke an expression whose type lacks a call signature

This error can be caused when you are requesting a value from something and you put parenthesis at the end, as if it is a function call, yet the value is correctly retrieved without ending parenthesis. For example, if what you are accessing is a Property 'get' in Typescript.

private IMadeAMistakeHere(): void {
    let mynumber = this.SuperCoolNumber();
}

private IDidItCorrectly(): void {
    let mynumber = this.SuperCoolNumber;
}

private get SuperCoolNumber(): number {
    let response = 42;
    return response;
};

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How do MySQL indexes work?

In MySQL InnoDB, there are two types of index.

  1. Primary key which is called clustered index. Index key words are stored with real record data in the B+Tree leaf node.

  2. Secondary key which is non clustered index. These index only store primary key's key words along with their own index key words in the B+Tree leaf node. So when searching from secondary index, it will first find its primary key index key words and scan the primary key B+Tree to find the real data records. This will make secondary index slower compared to primary index search. However, if the select columns are all in the secondary index, then no need to look up primary index B+Tree again. This is called covering index.

How to enable curl in xampp?

You can add any extension (in Wamp and Xampp servers) by removing the semi-colon (;)

How do I convert a file path to a URL in ASP.NET

The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

facebook: permanent Page Access Token?

Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:

  1. From (Graph Explorer tool)0, select the relevant permissions and get the short lived page access token.
  2. (Go to debugger tool)1 and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
  3. Copy the the extended token and use it in this API:
  4. https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
  5. This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

javascript windows alert with redirect function

Use this if you also want to consider non-javascript users:

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://someplace.com';
       </SCRIPT>
       <NOSCRIPT>
           <a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
       </NOSCRIPT>");

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

angular.module('app')
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){
          element.html(html);
          $compile(element.contents())(scope);
        });
      }
    };
  });

How to import classes defined in __init__.py

Yes, it is possible. You might also want to define __all__ in __init__.py files. It's a list of modules that will be imported when you do

from lib import *

Finding square root without using sqrt function?

Here is a very awesome code to find sqrt and even faster than original sqrt function.

float InvSqrt (float x) 
{
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f375a86 - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x=1/x;
    return x;
}

Faking an RS232 Serial Port

I know this is an old post, but in case someone else happens upon this question, one good option is Virtual Serial Port Emulator (VSPE) from Eterlogic It provides an API for creating kernel mode virtual comport devices, i.e. connectors, mappers, splitters etc.
However, some of the advertised capabilities were really not capabilities at all.

EDIT
A much better choice, Eltima. This product is fully baked. Good developer tech support. The product did all it claimed to do. Product options include both desktop applications, as well as software development kits with APIs.

Neither of these products are open source, or free. However, as other posts here have pointed out, there are other options. Here is a list of various serial utilities:

com0com (current)
com0com - With Signed Driver (old version)
Yet another place for com0com with Signed Driver (Pete's Blog)
Tactical Software
Termite
COM Port Serial Emulator
Kermit (obsolete, but still downloadable)
HWVSP3
HHD Software (free edition)

How to change my Git username in terminal?

There is a easy solution for that problem, the solution is removed the certificate the yours Keychain, the previous thing will cause that it asks again to the user and password.

Steps:

  1. Open keychain access

enter image description here

  1. Search the certificate gitHub.com.

  2. Remove gitHub.com certificate.

  3. Execute any operation with git in your terminal. this again ask your username and password.

For Windows Users find the key chain by following:

Control Panel >> User Account >> Credential Manager >> Windows Credential >> Generic Credential

How do I make an html link look like a button?

If you need some cool effect, hover and shadow; you can use this:

    .button {
        text-decoration: none;
        padding: 15px 25px;
        font-size: 24px;
        cursor: pointer;
        text-align: center;
        text-decoration: none;
        outline: none;
        color: #fff;
        background-color: #450775;
        border: none;
        border-radius: 15px;
        box-shadow: 0 9px #e1d5ed;

    }

    .button:hover {background-color: #220440}

    .button:active {
        background-color: #230545;
        box-shadow: 0 5px #e1d5ed;
        transform: translateY(4px);
    }

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports a "fallback" field to use in case the primary field happens to be null or undefined:

yourApp.filter('orderObjectBy', function() {
  return function(items, field, fallback, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      var af = a[field];
      if(af === undefined || af === null) { af = a[fallback]; }

      var bf = b[field];
      if(bf === undefined || bf === null) { bf = b[fallback]; }

      return (af > bf ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

How do I install Python packages on Windows?

Starting with Python 2.7, pip is included by default. Simply download your desired package via

python -m pip install [package-name]

Padding characters in printf

Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.

function create-console-spanner() {
    # 1: left-side-text, 2: right-side-text
    local spanner="";
    eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
    printf "%s %s %s" "$1" "$spanner" "$2";
}

Example: create-console-spanner "loading graphics module" "[success]"

Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.

# Author: Triston J. Taylor <[email protected]>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite

declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);

declare -i PAINT_ACTIVE=1;

function paint-replace() {
    local contents=$(cat)
    echo "${contents//$1/$2}"
}

source <(cat <<EOF
function paint-activate() {
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)

source <(cat <<EOF
function paint-deactivate(){
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;    
}
EOF
)

function paint-get-spanner() {
    (( $# == 0 )) && set -- - 0;
    declare -i l=$(( `tput cols` - ${2}))
    eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}

function paint-span() {
    local left_format=$1 right_format=$3
    local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
    paint-format "$left_format";
    paint-get-spanner "$2" $(( left_length + right_length));
    paint-format "$right_format";
}

function paint-format() {
    local VAR="" OPTIONS='';
    local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
    while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
        if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
        if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
    done;
    OPTIONS+=" --"
    local format="$1"; shift;
    if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
        format=$(paint-activate "$format&none;")
    else
        format=$(paint-deactivate "$format")
    fi
    printf $OPTIONS "${format}" "$@";
    (( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}

function paint-show-pallette() {
    local -i PAINT_ACTIVE=1
    paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
    paint-format "  Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}

To print a color, that's simple enough: paint-format "&red;This is %s\n" red And you might want to get bold later on: paint-format "&bold;%s!\n" WOW

The -l option to the paint-format function measures the text so you can do console font metrics operations.

The -v option to the paint-format function works the same as printf but cannot be supplied with -l

Now for the spanning!

paint-span "hello " . " &blue;world" [note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]

and the output of that is:

hello ............................. world

Vertical Tabs with JQuery?

I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

Spring Boot default H2 jdbc connection (and H2 console)

Use jdbc:h2:mem:testdb as your path when logging into the H2 console.

Obviously if you have altered Spring Boot properties your datasource may be different, but it seems like you're struggling with how to find the default. That's all there is to it! You'll see your schema after logging in to H2.

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

Proper use of const for defining functions in JavaScript

Although using const to define functions seems like a hack, but it comes with some great advantages that make it superior (in my opinion)

  1. It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.

  2. You can use fat arrow syntax, which is shorter & cleaner.

  3. Using arrow functions takes care of this binding for you.

example with function

_x000D_
_x000D_
// define a function_x000D_
function add(x, y) { return x + y; }_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// oops, someone mutated your function_x000D_
add = function (x, y) { return x - y; };_x000D_
_x000D_
// now this is not what you expected_x000D_
console.log(add(1, 2)); // -1
_x000D_
_x000D_
_x000D_

same example with const

_x000D_
_x000D_
// define a function (wow! that is 8 chars shorter)_x000D_
const add = (x, y) => x + y;_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// someone tries to mutate the function_x000D_
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable._x000D_
// the intruder fails and your function remains unchanged
_x000D_
_x000D_
_x000D_

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

How to check if $? is not equal to zero in unix shell scripting?

if [ $var1 != $var2 ] 
then 
echo "$var1"
else 
echo "$var2"
fi

Explanation of BASE terminology

  • Basic Availability: The database appears to work most of the time.

  • Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.

  • Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.

Set Icon Image in Java

I use this:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class IconImageUtilities
{
    public static void setIconImage(Window window)
    {
        try
        {
            InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
            BufferedImage bufferedImage = ImageIO.read(imageInputStream);
            window.setIconImage(bufferedImage);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }
    }
}

Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:

IconImageUtilities.setIconImage(this);

ASP.NET GridView RowIndex As CommandArgument

<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

inside your event handler :

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

How to use Typescript with native ES6 Promises

If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:

tsc a.ts --target es6 --module commonjs

More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

If you use tsconfig.json, then like this:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
    }
}

More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

Disable scrolling in all mobile devices

After having no success trying all the answers I managed to turn my mobile scroll off by simply adding:

html,
body {
  overflow-x: hidden;
  height: 100%;
}

body {
  position: relative;
}

Its important to use % not vh for this. The height: 100% was something I had been missing all along, crazy.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

The significant differences between the two methods are the class of the objects they return when used for extraction and whether they may accept a range of values, or just a single value during assignment.

Consider the case of data extraction on the following list:

foo <- list( str='R', vec=c(1,2,3), bool=TRUE )

Say we would like to extract the value stored by bool from foo and use it inside an if() statement. This will illustrate the differences between the return values of [] and [[]] when they are used for data extraction. The [] method returns objects of class list (or data.frame if foo was a data.frame) while the [[]] method returns objects whose class is determined by the type of their values.

So, using the [] method results in the following:

if( foo[ 'bool' ] ){ print("Hi!") }
Error in if (foo["bool"]) { : argument is not interpretable as logical

class( foo[ 'bool' ] )
[1] "list"

This is because the [] method returned a list and a list is not valid object to pass directly into an if() statement. In this case we need to use [[]] because it will return the "bare" object stored in 'bool' which will have the appropriate class:

if( foo[[ 'bool' ]] ){ print("Hi!") }
[1] "Hi!"

class( foo[[ 'bool' ]] )
[1] "logical"

The second difference is that the [] operator may be used to access a range of slots in a list or columns in a data frame while the [[]] operator is limited to accessing a single slot or column. Consider the case of value assignment using a second list, bar():

bar <- list( mat=matrix(0,nrow=2,ncol=2), rand=rnorm(1) )

Say we want to overwrite the last two slots of foo with the data contained in bar. If we try to use the [[]] operator, this is what happens:

foo[[ 2:3 ]] <- bar
Error in foo[[2:3]] <- bar : 
more elements supplied than there are to replace

This is because [[]] is limited to accessing a single element. We need to use []:

foo[ 2:3 ] <- bar
print( foo )

$str
[1] "R"

$vec
     [,1] [,2]
[1,]    0    0
[2,]    0    0

$bool
[1] -0.6291121

Note that while the assignment was successful, the slots in foo kept their original names.

How to resolve git's "not something we can merge" error

I had a work tree with master and an another branch checked out in two different work folders.

PS C:\rhipheusADO\Build> git worktree list
C:/rhipheusADO/Build         7d32e6e [vyas-cr-core]
C:/rhipheusADO/Build-master  91d418c [master]

PS C:\rhipheusADO\Build> cd ..\Build-master\

PS C:\rhipheusADO\Build-master> git merge 7d32e6e #Or any other intermediary commits
Updating 91d418c..7d32e6e
Fast-forward
 Pipeline/CR-MultiPool/azure-pipelines-auc.yml | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

PS C:\rhipheusADO\Build-master> git ls-remote
From https://myorg.visualstudio.com/HelloWorldApp/_git/Build
53060bac18f9d4e7c619e5170c436e6049b63f25        HEAD
7d32e6ec76d5a5271caebc2555d5a3a84b703954        refs/heads/vyas-cr-core 

PS C:\rhipheusADO\Build-master> git merge 7d32e6ec76d5a5271caebc2555d5a3a84b703954
Already up-to-date

PS C:\rhipheusADO\Build>  git push
Total 0 (delta 0), reused 0 (delta 0)
To https://myorg.visualstudio.com/HelloWorldApp/_git/Build
   91d418c..7d32e6e  master -> master

If you need to just merge the latest commit:

git merge origin/vyas-cr-core 
git push

And is same as what I've always done:

git checkout master # This is needed if you're not using worktrees
git pull origin vyas-cr-core
git push

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

You can first use String.trim(), and then apply the regex replace command on the result.

Linq style "For Each"

There isn't anything built-in, but you can easily create your own extension method to do it:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}

MySQL: View with Subquery in the FROM Clause Limitation

You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/

This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.

What's the best way to dedupe a table?

Here's the method I use if you can get your dupe criteria into a group by statement and your table has an id identity column for uniqueness:

delete t
from tablename t
inner join  
(
    select date_time, min(id) as min_id
    from tablename
    group by date_time
    having count(*) > 1
) t2 on t.date_time = t2.date_time
where t.id > t2.min_id

In this example the date_time is the grouping criteria, if you have more than one column make sure to join on all of them.

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

Sort an array of objects in React and render them

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more : lodash.sortBy

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

JavaScript

$scope.get_pre = function(x) {
    return $sce.trustAsHtml(x);
};

HTML

<pre ng-bind-html="get_pre(html)"></pre>

Check If only numeric values were entered in input. (jQuery)

 if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
            alert('Please enter only numbers into amount textbox.')
            }
            else
            {
            alert('Right Number');
            }

I hope this code may help you.

in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".

Thanks... :)

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Counting lines, words, and characters within a text file using Python

Try this:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

Back to your code:

fname = "feed.txt"
fname = open('feed.txt', 'r')

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

for line in feed:
    lines = line.split('\n')

line is one line from the file. It does not make sense to split('\n') it.

How to have multiple conditions for one if statement in python

Assuming you're passing in strings rather than integers, try casting the arguments to integers:

def example(arg1, arg2, arg3):
     if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
          print("Example Text")

(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )

"PKIX path building failed" and "unable to find valid certification path to requested target"

This is a solution but in form of my story with this problem:

I was almost dead trying all the solution given above(for 3 days ) and nothing worked for me.

I lost all hope.

I contacted my security team regarding this because i was behind a proxy and they told that they had recently updated their security policy.

I scolded them badly for not informing the Developers.

Later they issued a new "cacerts" file which contains all the certificates.

I removed the cacerts file which is present inside %JAVA_HOME%/jre/lib/security and it solved my problem.

So if you are facing this issue it might be from your network team also like this.

How can I convert a date to GMT?

Although it looks logical, the accepted answer is incorrect because JavaScript dates don't work like that.

It's super important to note here that the numerical value of a date (i.e., new Date()-0 or Date.now()) in JavaScript is always measured as millseconds since the epoch which is a timezone-free quantity based on a precise exact instant in the history of the universe. You do not need to add or subtract anything to the numerical value returned from Date() to convert the numerical value into a timezone, because the numerical value has no timezone. If it did have a timezone, everything else in JavaScript dates wouldn't work.

Timezones, leap years, leap seconds, and all of the other endlessly complicated adjustments to our local times and dates, are based on this consistent and unambiguous numerical value, not the other way around.

Here are examples of how the numerical value of a date (provided to the date constructor) is independent of timezone:

In Central Standard Time:

new Date(0);
// Wed Dec 31 1969 18:00:00 GMT-0600 (CST)

In Anchorage, Alaska:

new Date(0);
// Wed Dec 31 1969 15:00:00 GMT-0900 (AHST)

In Paris, France:

new Date(0);
// Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

It is critical to observe that in ALL cases, based on the timezone-free epoch offset of zero milliseconds, the resulting time is identical. 1 am in Paris, France is the exact same moment as 3 pm the day before in Anchorage, Alaska, which is the exact same moment as 6 pm in Chicago, Illinois.

For this reason, the accepted answer on this page is incorrect. Observe:

// Create a date.
   date = new Date();
// Fri Jan 27 2017 18:16:35 GMT-0600 (CST)


// Observe the numerical value of the date.
   date.valueOf();
// 1485562595732
// n.b. this value has no timezone and does not need one!!


// Observe the incorrectly "corrected" numerical date value.
   date.valueOf() + date.getTimezoneOffset() * 60000;
// 1485584195732


// Try out the incorrectly "converted" date string.
   new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
// Sat Jan 28 2017 00:16:35 GMT-0600 (CST)

/* Not the correct result even within the same script!!!! */

If you have a date string in another timezone, no conversion to the resulting object created by new Date("date string") is needed. Why? JavaScript's numerical value of that date will be the same regardless of its timezone. JavaScript automatically goes through amazingly complicated procedures to extract the original number of milliseconds since the epoch, no matter what the original timezone was.

The bottom line is that plugging a textual date string x into the new Date(x) constructor will automatically convert from the original timezone, whatever that might be, into the timezone-free epoch milliseconds representation of time which is the same regardless of any timezone. In your actual application, you can choose to display the date in any timezone that you want, but do NOT add/subtract to the numerical value of the date in order to do so. All the conversion already happened at the instant the date object was created. The timezone isn't even there anymore, because the date object is instantiated using a precisely-defined and timezone-free sense of time.

The timezone only begins to exist again when the user of your application is considered. The user does have a timezone, so you simply display that timezone to the user. But this also happens automatically.

Let's consider a couple of the dates in your original question:

   date1 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300");
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)


   date2 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300")
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)

The console already knows my timezone, and so it has automatically shown me what those times mean to me.

And if you want to know the time in GMT/UTC representation, also no conversion is needed! You don't change the time at all. You simply display the UTC string of the time:

    date1.toUTCString();
// "Fri, 20 Jan 2012 14:51:36 GMT"

Code that is written to convert timezones numerically using the numerical value of a JavaScript date is almost guaranteed to fail. Timezones are way too complicated, and that's why JavaScript was designed so that you didn't need to.

Add placeholder text inside UITextView in Swift?

Swift Answer

Here is the custom class, that animates placeholder.

class CustomTextView: UITextView {
    
    //   MARK: - public
    
    public var placeHolderText: String? = "Enter Reason.."
    
    public lazy var placeHolderLabel: UILabel! = {
        let placeHolderLabel = UILabel(frame: .zero)
        placeHolderLabel.numberOfLines = 0
        placeHolderLabel.backgroundColor = .clear
        placeHolderLabel.alpha = 0.5
        return placeHolderLabel
    }()
    
    //   MARK: - Init
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        enableNotifications()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        enableNotifications()
    }
    
    func setup() {
        placeHolderLabel.frame = CGRect(x: 8, y: 8, width: self.bounds.size.width - 16, height: 15)
        placeHolderLabel.sizeToFit()
    }
    
    //   MARK: - Cycle
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        textContainerInset = UIEdgeInsets(top: 8, left: 5, bottom: 8, right: 8)
        returnKeyType = .done
        addSubview(placeHolderLabel)
        placeHolderLabel.frame = CGRect(x: 8, y: 8, width: self.bounds.size.width - 16, height: 15)
        placeHolderLabel.textColor = textColor
        placeHolderLabel.font = font
        placeHolderLabel.text = placeHolderText
        bringSubviewToFront(placeHolderLabel)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    
    //   MARK: - Notifications
    
    private func enableNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChangeNotification(_:)), name: UITextView.textDidChangeNotification , object: nil)
    }
    
    @objc func textDidChangeNotification(_ notify: Notification) {
        guard self == notify.object as? UITextView else { return }
        guard placeHolderText != nil else { return }
        
        UIView.animate(withDuration: 0.25, animations: {
            self.placeHolderLabel.alpha = (self.text.count == 0) ? 0.5 : 0
        }, completion: nil)
    }
    
}

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

Changing ViewPager to enable infinite page scrolling

Actually, I've been looking at the various ways to do this "infinite" pagination, and even though the human notion of time is that it is infinite (even though we have a notion of the beginning and end of time), computers deal in the discrete. There is a minimum and maximum time (that can be adjusted as time goes on, remember the basis of the Y2K scare?).

Anyways, the point of this discussion is that it is/should be sufficient to support a relatively infinite date range through an actually finite date range. A great example of this is the Android framework's CalendarView implementation, and the WeeksAdapter within it. The default minimum date is in 1900 and the default maximum date is in 2100, this should cover 99% of the calendar use of anyone within a 10 year radius around today easily.

What they do in their implementation (focused on weeks) is compute the number of weeks between the minimum and maximum date. This becomes the number of pages in the pager. Remember that the pager doesn't need to maintain all of these pages simultaneously (setOffscreenPageLimit(int)), it just needs to be able to create the page based on the page number (or index/position). In this case the index is the number of weeks that the week is from the minimum date. With this approach you just have to maintain the minimum date and the number of pages (distance to the maximum date), then for any page you can easily compute the week associated with that page. No dancing around the fact that ViewPager doesn't support looping (a.k.a infinite pagination), and trying to force it to behave like it can scroll infinitely.

new FragmentStatePagerAdapter(getFragmentManager()) {
    @Override
    public Fragment getItem(int index) {
        final Bundle arguments = new Bundle(getArguments());
        final Calendar temp_calendar = Calendar.getInstance();
        temp_calendar.setTimeInMillis(_minimum_date.getTimeInMillis());
        temp_calendar.setFirstDayOfWeek(_calendar.getStartOfWeek());
        temp_calendar.add(Calendar.WEEK_OF_YEAR, index);
        // Moves to the first day of this week
        temp_calendar.add(Calendar.DAY_OF_YEAR,
                -UiUtils.modulus(temp_calendar.get(Calendar.DAY_OF_WEEK) - temp_calendar.getFirstDayOfWeek(),
                7));
        arguments.putLong(KEY_DATE, temp_calendar.getTimeInMillis());
        return Fragment.instantiate(getActivity(), WeekDaysFragment.class.getName(), arguments);
    }

    @Override
    public int getCount() {
        return _total_number_of_weeks;
    }
};

Then WeekDaysFragment can easily display the week starting at the date passed in its arguments.

Alternatively, it seems that some version of the Calendar app on Android uses a ViewSwitcher (which means there's only 2 pages, the one you see and the hidden page). It then changes the transition animation based on which way the user swiped and renders the next/previous page accordingly. In this way you get infinite pagination because it just switching between two pages infinitely. This requires using a View for the page though, which is way I went with the first approach.

In general, if you want "infinite pagination", it's probably because your pages are based off of dates or times somehow. If this is the case consider using a finite subset of time that is relatively infinite instead. This is how CalendarView is implemented for example. Or you can use the ViewSwitcher approach. The advantage of these two approaches is that neither does anything particularly unusual with the ViewSwitcher or ViewPager, and doesn't require any tricks or reimplementation to coerce them to behave infinitely (ViewSwitcher is already designed to switch between views infinitely, but ViewPager is designed to work on a finite, but not necessarily constant, set of pages).

Is there a real solution to debug cordova apps

If you use phonegap build, there is an option to enable debug.


For local builds, you can install weinre with npm : https://npmjs.org/package/weinre

And the link to the weinre docs : http://people.apache.org/~pmuellr/weinre/docs/latest/


And there is something called chrome remote debugging but I don't know much about it, you can have a look at Raymond Camden's article : http://www.raymondcamden.com/index.cfm/2014/1/2/Apache-Cordova-33-and-Remote-Debugging-for-Android

Docs for the chrome remote debugging : https://developers.google.com/chrome-developer-tools/docs/remote-debugging (if I understood correctly you need an android device with chrome as default browser) Maybe the closest to your dream solution?

Rounding a double to turn it into an int (java)

Documentation of Math.round says:

Returns the result of rounding the argument to an integer. The result is equivalent to (int) Math.floor(f+0.5).

No need to cast to int. Maybe it was changed from the past.

C function that counts lines in file

You declare

int countlines(char *filename)

to take a char * argument.

You call it like this

countlines(fp)

passing in a FILE *.

That is why you get that compile error.

You probably should change that second line to

countlines("Test.txt")

since you open the file in countlines

Your current code is attempting to open the file in two different places.

How to read data From *.CSV file using javascript?

No need to write your own...

The jQuery-CSV library has a function called $.csv.toObjects(csv) that does the mapping automatically.

Note: The library is designed to handle any CSV data that is RFC 4180 compliant, including all of the nasty edge cases that most 'simple' solutions overlook.

Like @Blazemonger already stated, first you need to add line breaks to make the data valid CSV.

Using the following dataset:

heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2

Use the code:

var data = $.csv.toObjects(csv):

The output saved in 'data' will be:

[
  { heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" } 
  { heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]

Note: Technically, the way you wrote the key-value mapping is invalid JavaScript. The objects containing the key-value pairs should be wrapped in brackets.

If you want to try it out for yourself, I suggest you take a look at the Basic Usage Demonstration under the 'toObjects()' tab.

Disclaimer: I'm the original author of jQuery-CSV.

Update:

Edited to use the dataset that the op provided and included a link to the demo where the data can be tested for validity.

Update2:

Due to the shuttering of Google Code. jquery-csv has moved to GitHub

How to call stopservice() method of Service class from the calling activity class

In Kotlin you can do this...

Service:

class MyService : Service() {
    init {
        instance = this
    }

    companion object {
        lateinit var instance: MyService

        fun terminateService() {
            instance.stopSelf()
        }
    }
}

In your activity (or anywhere in your app for that matter):

btn_terminate_service.setOnClickListener {
    MyService.terminateService()
}

Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

Google.com and clients1.google.com/generate_204

Like Snukker said, clients1.google.com is where the search suggestions come from. My guess is that they make a request to force clients1.google.com into your DNS cache before you need it, so you will have less latency on the first "real" request.

Google Chrome already does that for any links on a page, and (I think) when you type an address in the location bar. This seems like a way to get all browsers to do the same thing.

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

How do I copy SQL Azure database to my local development server?

There are multiple ways to do this:

  1. Using SSIS (SQL Server Integration Services). It only imports data in your table. Column properties, constraints, keys, indices, stored procedures, triggers, security settings, users, logons, etc. are not transferred. However it is very simple process and can be done simply by going through wizard in SQL Server Management Studio.
  2. Using combination of SSIS and DB creation scripts. This will get you data and all missing metadata that is not transferred by SSIS. This is also very simple. First transfer data using SSIS (see instructions below), then create DB Create script from SQL Azure database, and re-play it on your local database.
  3. Finally, you can use Import/Export service in SQL Azure. This transfers data (with a schema objects) to Azure Blob Storage as a BACPAC. You will need an Azure Storage account and do this in Azure web portal. It is as simple as pressing an "Export" button in the Azure web portal when you select the database you want to export. The downside is that it is only manual procedure, I don't know a way to automate this through tools or scripts -- at least the first part that requires a click on the web page.

Manual procedure for method #1 (using SSIS) is the following:

  • In Sql Server Management Studio (SSMS) create new empty database on your local SQL instance.
  • Choose Import Data from context menu (right click the database -> Tasks -> Import data...)
  • Type in connection parameters for the source (SQL Azure). Select ".Net Framework Data Provider for SqlServer" as a provider.
  • Choose existing empty local database as destination.
  • Follow the wizard -- you will be able to select tables data you want to copy. You can choose to skip any of the tables you don't need. E.g. if you keep application logs in database, you probably don't need it in your backup.

You can automate it by creating SSIS package and re-executing it any time you like to re-import the data. Note that you can only import using SSIS to a clean DB, you cannot do incremental updates to your local database once you already done it once.

Method #2 (SSID data plus schema objects) is very simple. First go though a steps described above, then create DB Creation script (righ click on database in SSMS, choose Generate Scripts -> Database Create). Then re-play this script on your local database.

Method #3 is described in the Blog here: http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/. There is a video clip with the process of transferring DB contents to Azure Blob storage as BACPAC. After that you can copy the file locally and import it to your SQL instance. Process of importing BACPAC to Data-Tier application is described here: http://msdn.microsoft.com/en-us/library/hh710052.aspx.

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

How to view file diff in git before commit

The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d - This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.

VB.Net Properties - Public Get, Private Set

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

Installing J2EE into existing eclipse IDE

You could install Web Tool Platform on top of your current installation to help you learn about Java EE. Download the Web Tools Platform by using Eclipse Software Update (Instruction at http://download.eclipse.org/webtools/updates/). It has features to get you going with learning Java EE. You could learn more about Web Tools Platform at http://www.eclipse.org/webtools/

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

If you want to deploy an MVC application without installing MVC, you can deploy the MVC DLL's with your application. This gets around installing MVC 3. You can use features in some .Net 4.0 namespaces without installing .Net using a similar approach.

How could I use requests in asyncio?

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I wasn't completely happy by the --allow-file-access-from-files solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.

Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !

exclude @Component from @ComponentScan

The configuration seem alright, except that you should use excludeFilters instead of excludes:

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

How to force view controller orientation in iOS 8?

For iOS 7 - 10:

Objective-C:

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
[UINavigationController attemptRotationToDeviceOrientation];

Swift 3:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()

Just call it in - viewDidAppear: of the presented view controller.

Can a background image be larger than the div itself?

Use trasform: scale(1.1) property to make bg image bigger, move it up with position: relative; top: -10px;

<div class="home-hero">
    <div class="home-hero__img"></div>
</div>

.home-hero__img{
 position:relative;
    top:-10px;
    transform: scale(1.1);
    background: {
        size: contain;
        image: url('image.svg');
    }
}

Reading a registry key in C#

If you want it casted to a specific type you can use this method. Most non primitive types won't by default support direct casting so you will have to handle those accordingly.

  public T GetValue<T>(string registryKeyPath, string value, T defaultValue = default(T))
  {
    T retVal = default(T);

      retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue);

      return retVal;
  }

Exception thrown inside catch block - will it be caught again?

If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:

public void doStuff() throws MyException {
    try {
        //Stuff
    } catch(StuffException e) {
        throw new MyException();
    }
}

And now your compiler will not yell at you :)

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Whenever I set debug="off" in my web.config and run my mvc4 application i would end up with ...

<script src="/bundles/jquery?v=<some long string>"></script>

in my html code and a JavaScript error

Expected ';'

There were 2 ways to get rid of the javascript error

  1. set BundleTable.EnableOptimizations = false in BundleConfig.cs

OR

  1. I ended up using NuGet Package Manager to update WebGrease.dll. It works fine irrespective if debug= "true" or debug = "false".

How to select option in drop down protractorjs e2e tests

Helper to set the an option element:

selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }

Disabling vertical scrolling in UIScrollView

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x,0)];

}

you must have confirmed to UIScrollViewDelegate

aScrollView.delegate = self;

Difference between Encapsulation and Abstraction

Yes !!!! If I say Encapsulation is a kind of an advanced specific scope abstraction,

How many of you read/upvote my answer. Let's dig in why I am saying like this.

I need to clear two things before my claiming.

One is data hiding and, another one is the abstraction

Data hiding

Most of the time, we will not give direct access to our internal data. Our internal data should not go out directly that is an outside person can't access our internal data directly. It's all about security since we need to protect the internal states of a particular object.


Abstraction

For simplicity, hide the internal implementations is called abstraction. In abstraction, we only focus on the necessary things. Basically, We talk about "What to do" and not "How to do" in abstraction. Security also can be achieved by abstraction since we are not going to highlight "how we are implementing". Maintainability will be increased since we can alter the implementation but it will not affect our end user.


I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction

encapsulation = data hiding + abstraction

In encapsulation, we need to hide the data so outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.

This is why I said like above encapsulation is a kind of abstraction.

So Where is the difference?

The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,

encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).

Session state can only be used when enableSessionState is set to true either in a configuration

For SharePoint Can find the web config file in C:\inetpub\wwwroot\wss\VirtualDirectories\Sitecollection port number - and Make changes

 <system.web>
  <pages enableSessionState="true" /> 
 </system.web>

and using SharePoint Management Shell Run below Command

   Enable-SPSessionStateService -DefaultProvision

firefox proxy settings via command line

Thank very much, I find the answers in this website.

Here I refer to the production of a cmd file

by minimo

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "192.168.1.235 ");>>"%ffile%\prefs.js"
echo user_pref("network.proxy.http_port", 80);>>"%ffile%\prefs.js"
echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js"
set ffile=
cd %windir%

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

Can I do Android Programming in C++, C?

There is more than one library for working in C++ in Android programming:

  1. C++ - qt (A Nokia product, also available as LGPL)
  2. C++ - Wxwidget (Available as GPL)

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

I used this and it worked out well for me. If your directory is

"repo" and your project is "hello" copy the project there

cd /path/to/my/repo

Initialize your directory

git init

Stage the project

git add hello

commit the project

git commit

Add configurations using the email and username you are using in Bitbucket

git config --global user.email
git config --global user.name

Add comment to the project

git commit -m 'comment'

push the project now

git push origin master

Check out of the master

git checkout master

How to use HTML Agility pack

HtmlAgilityPack uses XPath syntax, and though many argues that it is poorly documented, I had no trouble using it with help from this XPath documentation: https://www.w3schools.com/xml/xpath_syntax.asp

To parse

<h2>
  <a href="">Jack</a>
</h2>
<ul>
  <li class="tel">
    <a href="">81 75 53 60</a>
  </li>
</ul>
<h2>
  <a href="">Roy</a>
</h2>
<ul>
  <li class="tel">
    <a href="">44 52 16 87</a>
  </li>
</ul>

I did this:

string url = "http://website.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//h2//a"))
{
  names.Add(node.ChildNodes[0].InnerHtml);
}
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='tel']//a"))
{
  phones.Add(node.ChildNodes[0].InnerHtml);
}

Notice: Undefined variable: _SESSION in "" on line 9

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");

Checking letter case (Upper/Lower) within a string in Java

package passwordValidator;

import java.util.Scanner;

public class Main {
    /**
     * @author felipe mello.
     */

    private static Scanner scanner = new Scanner(System.in);

     /*
     * Create a password validator(from an input string) via TDD
     * The validator should return true if
     *  The Password is at least 8 characters long
     *  The Password contains uppercase Letters(atLeastOne)
     *  The Password contains digits(at least one)
     *  The Password contains symbols(at least one)
     */


    public static void main(String[] args) {
        System.out.println("Please enter a password");
        String password = scanner.nextLine();   

        checkPassword(password);
    }
    /**
     * 
     * @param checkPassword the method check password is validating the input from the the user and check if it matches the password requirements
     * @return
     */
    public static boolean checkPassword(String password){
        boolean upperCase = !password.equals(password.toLowerCase()); //check if the input has a lower case letter
        boolean lowerCase = !password.equals(password.toUpperCase()); //check if the input has a CAPITAL case letter
        boolean isAtLeast8 = password.length()>=8;                    //check if the input is greater than 8 characters
        boolean hasSpecial = !password.matches("[A-Za-z0-9]*");       // check if the input has a special characters
        boolean hasNumber = !password.matches(".*\\d+.*");            //check if the input contains a digit
        if(!isAtLeast8){
            System.out.println("Your Password is not big enough\n please enter a password with minimun of 8 characters");
            return true;
        }else if(!upperCase){
            System.out.println("Password must contain at least one UPPERCASE letter");
            return true;
        }else if(!lowerCase){
            System.out.println("Password must contain at least one lower case letter");
            return true;
        }else if(!hasSpecial){
            System.out.println("Password must contain a special character");
            return true;
        }else if(hasNumber){
            System.out.println("Password must contain at least one number");
            return true;
        }else{
            System.out.println("Your password: "+password+", sucessfully match the requirements");
            return true;
        }

    }
}

Uncaught SyntaxError: Unexpected token :

Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.

IP to Location using Javascript

A better way is to skip the "middle man" (ip)

jQuery.get("http://ipinfo.io", function(response) {
    console.log(response.city);
}, "jsonp");

This gives you the IP, the city, the country, etc

RESTful URL design for search

For the searching, use querystrings. This is perfectly RESTful:

/cars?color=blue&type=sedan&doors=4

An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

sudo apt-get install putty

This will automatically install the puttygen tool.

Now to convert the PPK file to be used with SSH command execute the following in terminal

puttygen mykey.ppk -O private-openssh -o my-openssh-key

Then, you can connect via SSH with:

ssh -v [email protected] -i my-openssh-key

http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

Google MAP API v3: Center & Zoom on displayed markers

I've also find this fix that zooms to fit all markers

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
                 ],
    latlngbounds = new google.maps.LatLngBounds();

LatLngList.forEach(function(latLng){
   latlngbounds.extend(latLng);
});

// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);

map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

How to convert an NSTimeInterval (seconds) into minutes

How I did this in Swift (including the string formatting to show it as "01:23"):

let totalSeconds: Double = someTimeInterval
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(round(totalSeconds % 60))        
let timeString = String(format: "%02d:%02d", minutes, seconds)
NSLog(timeString)

Adobe Reader Command Line Reference

Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n

string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe"; 
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();

MySQL Removing Some Foreign keys

The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;

How do I use boolean variables in Perl?

Perl doesn't have a native boolean type, but you can use comparison of integers or strings in order to get the same behavior. Alan's example is a nice way of doing that using comparison of integers. Here's an example

my $boolean = 0;
if ( $boolean ) {
    print "$boolean evaluates to true\n";
} else {
    print "$boolean evaluates to false\n";
}

One thing that I've done in some of my programs is added the same behavior using a constant:

#!/usr/bin/perl

use strict;
use warnings;

use constant false => 0;
use constant true  => 1;

my $val1 = true;
my $val2 = false;

print $val1, " && ", $val2;
if ( $val1 && $val2 ) {
    print " evaluates to true.\n";
} else {
    print " evaluates to false.\n";
}

print $val1, " || ", $val2;
if ( $val1 || $val2 ) {
    print " evaluates to true.\n";
} else {
    print " evaluates to false.\n";
}

The lines marked in "use constant" define a constant named true that always evaluates to 1, and a constant named false that always evaluates by 0. Because of the way that constants are defined in Perl, the following lines of code fails as well:

true = 0;
true = false;

The error message should say something like "Can't modify constant in scalar assignment."

I saw that in one of the comments you asked about comparing strings. You should know that because Perl combines strings and numeric types in scalar variables, you have different syntax for comparing strings and numbers:

my $var1 = "5.0";
my $var2 = "5";

print "using operator eq\n";
if ( $var1 eq $var2 ) {
    print "$var1 and $var2 are equal!\n";
} else {
    print "$var1 and $var2 are not equal!\n";
}

print "using operator ==\n";
if ( $var1 == $var2 ) {
    print "$var1 and $var2 are equal!\n";
} else {
    print "$var1 and $var2 are not equal!\n";
}

The difference between these operators is a very common source of confusion in Perl.

Understanding unique keys for array children in React.js

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

This will sove the problem.

Correct way to read a text file into a buffer in C?

See this article from JoelOnSoftware for why you don't want to use strcat.

Look at fread for an alternative. Use it with 1 for the size when you're reading bytes or characters.

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

How to redraw DataTable with new data

You have to first clear the table and then add new data using row.add() function. At last step adjust also column size so that table renders correctly.

$('#upload-new-data').on('click', function () {
   datatable.clear().draw();
   datatable.rows.add(NewlyCreatedData); // Add new data
   datatable.columns.adjust().draw(); // Redraw the DataTable
});

Also if you want to find a mapping between old and new datatable API functions bookmark this

Error Dropping Database (Can't rmdir '.test\', errno: 17)

just go to data directory in my case path is "wamp\bin\mysql\mysql5.6.17\data" here you will see all databases folder just delete this your database folder the db will automatically drooped :)

Install Application programmatically on Android

UpdateNode provides an API for Android to install APK packages from inside another App.

You can just define your Update online and integrate the API into your App - that's it.
Currently the API is in Beta state, but you can already do some tests yourself.

Beside that, UpdateNode offers also displaying messages though the system - pretty useful if you want to tell something important to your users.

I am part of the client dev team and am using at least the message functionality for my own Android App.

See here a description how to integrate the API

Calculating distance between two geographic locations

http://developer.android.com/reference/android/location/Location.html

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);

or

private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
   
    return 6366000 * tt;
}

Incrementing in C++ - When to use x++ or ++x?

Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.

"More Effective C++" item #6 - that's sufficient authority for me.

For those who don't own the book, here are the pertinent quotes. From page 32:

From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...

And on page 34:

If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...

Fast way to discover the row count of a table in PostgreSQL

For SQL Server (2005 or above) a quick and reliable method is:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('MyTableName')   
AND (index_id=0 or index_id=1);

Details about sys.dm_db_partition_stats are explained in MSDN

The query adds rows from all parts of a (possibly) partitioned table.

index_id=0 is an unordered table (Heap) and index_id=1 is an ordered table (clustered index)

Even faster (but unreliable) methods are detailed here.

Should I use string.isEmpty() or "".equals(string)?

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

"webxml attribute is required" error in Maven

failOnMissingWebXml since 2020

All other answers about might be obsolete because the default value used by the maven-war-plugin changed:

Starting with 3.1.0, this property defaults to false if the project depends on the Servlet 3.0 API or newer.

So the ONLY thing you have to do is to add

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

Example:

<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>foo</groupId>
    <artifactId>bar</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <tomcat.ignorePackaging>true</tomcat.ignorePackaging>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

iOS: present view controller programmatically

LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Check the level of collation that is mismatched (server, database,table,column,character).

If it is the server, these steps helped me once:

  1. Stop the server
  2. Find your sqlservr.exe tool
  3. Run this command:

    sqlservr -m -T4022 -T3659 -s"name_of_insance" -q "name_of_collation"

  4. Start your sql server:

    net start name_of_instance

  5. Check the collation of your server again.

Here is more info:

https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

How to set a variable to current date and date-1 in linux?

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

How to program a fractal?

I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.

Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.

fractal(p0, p1){
    Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
    fractal(p0,Pmid);
    fractal(Pmid, p1);
}

An item with the same key has already been added

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..

Get OS-level system information

You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.

public class Main {
  public static void main(String[] args) {
    /* Total number of processors or cores available to the JVM */
    System.out.println("Available processors (cores): " + 
        Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    System.out.println("Free memory (bytes): " + 
        Runtime.getRuntime().freeMemory());

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    System.out.println("Maximum memory (bytes): " + 
        (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));

    /* Total memory currently available to the JVM */
    System.out.println("Total memory available to JVM (bytes): " + 
        Runtime.getRuntime().totalMemory());

    /* Get a list of all filesystem roots on this system */
    File[] roots = File.listRoots();

    /* For each filesystem root, print some info */
    for (File root : roots) {
      System.out.println("File system root: " + root.getAbsolutePath());
      System.out.println("Total space (bytes): " + root.getTotalSpace());
      System.out.println("Free space (bytes): " + root.getFreeSpace());
      System.out.println("Usable space (bytes): " + root.getUsableSpace());
    }
  }
}

Regular expression to match DNS hostname or IP Address?

how about this?

([0-9]{1,3}\.){3}[0-9]{1,3}

HttpWebRequest using Basic authentication

You can also just add the authorization header yourself.

Just make the name "Authorization" and the value "Basic BASE64({USERNAME:PASSWORD})"

String username = "abc";
String password = "123";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);

Edit

Switched the encoding from UTF-8 to ISO 8859-1 per What encoding should I use for HTTP Basic Authentication? and Jeroen's comment.

Android Center text on canvas

Center with Paint.getTextBounds():

enter image description here

private Rect r = new Rect();

private void drawCenter(Canvas canvas, Paint paint, String text) {
    canvas.getClipBounds(r);
    int cHeight = r.height();
    int cWidth = r.width();
    paint.setTextAlign(Paint.Align.LEFT);
    paint.getTextBounds(text, 0, text.length(), r);
    float x = cWidth / 2f - r.width() / 2f - r.left;
    float y = cHeight / 2f + r.height() / 2f - r.bottom;
    canvas.drawText(text, x, y, paint);
}
  • Paint.Align.CENTER doesn't mean that the reference point of the text is vertically centered. The reference point is always on the baseline. So, why not use Paint.Align.LEFT? You have to calculate the reference point anyway.

  • Paint.descent() has the disadvantage, that it doesn't consider the real text. Paint.descent() retrieves the same value, regardless of whether the text contains letters with descents or not. That's why I use r.bottom instead.

  • I have had some problems with Canvas.getHeight() if API < 16. That's why I use Canvas.getClipBounds(Rect) instead. (Do not use Canvas.getClipBounds().getHeight() as it allocates memory for a Rect.)

  • For reasons of performance, you should allocate objects before they are used in onDraw(). As drawCenter() will be called within onDraw() the object Rect r is preallocated as a field here.


I tried to put the code of the two top answers into my own code (August 2015) and made a screenshot to compare the results:

text centered three versions

The text should be centered within the red filled rectangle. My code produces the white text, the other two codes produces altogether the gray text (they are actually the same, overlapping). The gray text is a little bit too low and two much on the right.

This is how I made the test:

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

class MyView extends View {

    private static String LABEL = "long";
    private static float TEXT_HEIGHT_RATIO = 0.82f;

    private FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(0, 0);
    private Rect r = new Rect();
    private Paint paint = new Paint();
    private Paint rectPaint = new Paint();

    public MyView(Context context) {
        super(context);
    }

    private void drawTextBounds(Canvas canvas, Rect rect, int x, int y) {
        rectPaint.setColor(Color.rgb(0, 0, 0));
        rectPaint.setStyle(Paint.Style.STROKE);
        rectPaint.setStrokeWidth(3f);
        rect.offset(x, y);
        canvas.drawRect(rect, rectPaint);
    }

    // andreas1724 (white color):
    private void draw1(Canvas canvas, Paint paint, String text) {
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setColor(Color.rgb(255, 255, 255));
        canvas.getClipBounds(r);
        int cHeight = r.height();
        int cWidth = r.width();
        paint.getTextBounds(text, 0, text.length(), r);
        float x = cWidth / 2f - r.width() / 2f - r.left;
        float y = cHeight / 2f + r.height() / 2f - r.bottom;
        canvas.drawText(text, x, y, paint);
        drawTextBounds(canvas, r, (int) x, (int) y);
    }

    // Arun George (light green color):
    private void draw2(Canvas canvas, Paint textPaint, String text) {
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.argb(100, 0, 255, 0));
        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2));
        canvas.drawText(text, xPos, yPos, textPaint);
    }

    // VinceStyling (light blue color):
    private void draw3(Canvas yourCanvas, Paint mPaint, String pageTitle) {
        mPaint.setTextAlign(Paint.Align.LEFT);
        mPaint.setColor(Color.argb(100, 0, 0, 255));
        r = yourCanvas.getClipBounds();
        RectF bounds = new RectF(r);
        bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
        bounds.bottom = mPaint.descent() - mPaint.ascent();
        bounds.left += (r.width() - bounds.right) / 2.0f;
        bounds.top += (r.height() - bounds.bottom) / 2.0f;
        yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int margin = 10;
        int width = w - 2 * margin;
        int height = h - 2 * margin;
        params.width = width;
        params.height = height;
        params.leftMargin = margin;
        params.topMargin = margin;
        setLayoutParams(params);
        paint.setTextSize(height * TEXT_HEIGHT_RATIO);
        paint.setAntiAlias(true);
        paint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.rgb(255, 0, 0));
        draw1(canvas, paint, LABEL);
        draw2(canvas, paint, LABEL);
        draw3(canvas, paint, LABEL);
    }
}

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        FrameLayout container = new FrameLayout(this);
        container.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        container.addView(new MyView(this));
        setContentView(container);
    }
}

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

Can a foreign key be NULL and/or duplicate?

Short answer: Yes, it can be NULL or duplicate.

I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.

Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.

Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.

Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.

Display TIFF image in all web browser

You can try converting your image from tiff to PNG, here is how to do it:

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;

public class ImgConvTiffToPng {

    public static byte[] convert(byte[] tiff) throws Exception {

        byte[] out = new byte[0];
        InputStream inputStream = new ByteArrayInputStream(tiff);

        TIFFDecodeParam param = null;

        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
        RenderedImage op = dec.decodeAsRenderedImage(0);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PNGEncodeParam jpgparam = null;
        ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
        en.encode(op);
        outputStream = (ByteArrayOutputStream) en.getOutputStream();
        out = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();

        return out;

    }

How to Copy Text to Clip Board in Android?

With Jetpack Compose, it's really easy:

AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

How do malloc() and free() work?

Well it depends on the memory allocator implementation and the OS.

Under windows for example a process can ask for a page or more of RAM. The OS then assigns those pages to the process. This is not, however, memory allocated to your application. The CRT memory allocator will mark the memory as a contiguous "available" block. The CRT memory allocator will then run through the list of free blocks and find the smallest possible block that it can use. It will then take as much of that block as it needs and add it to an "allocated" list. Attached to the head of the actual memory allocation will be a header. This header will contain various bit of information (it could, for example, contain the next and previous allocated blocks to form a linked list. It will most probably contain the size of the allocation).

Free will then remove the header and add it back to the free memory list. If it forms a larger block with the surrounding free blocks these will be added together to give a larger block. If a whole page is now free the allocator will, most likely, return the page to the OS.

It is not a simple problem. The OS allocator portion is completely out of your control. I recommend you read through something like Doug Lea's Malloc (DLMalloc) to get an understanding of how a fairly fast allocator will work.

Edit: Your crash will be caused by the fact that by writing larger than the allocation you have overwritten the next memory header. This way when it frees it gets very confused as to what exactly it is free'ing and how to merge into the following block. This may not always cause a crash straight away on the free. It may cause a crash later on. In general avoid memory overwrites!

Hide all elements with class using plain Javascript

Late answer, but I found out that this is the simplest solution (if you don't use jQuery):

var myClasses = document.querySelectorAll('.my-class'),
    i = 0,
    l = myClasses.length;

for (i; i < l; i++) {
    myClasses[i].style.display = 'none';
}

Demo

Auto code completion on Eclipse

Pressing Ctrl+Space opens up the auto-completion dialog in Eclipse. In the Java Perspective it opens automatically after you typed a . (normally with a short delay).

global variable for all controller and views

I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders. Here is what i did:

  1. Created the Provider SettingsServiceProvider
    php artisan make:provider SettingsServiceProvider
  1. Created the Model i needed (GlobalSettings)
    php artisan make:model GlobalSettings
  1. Edited the generated register method in \App\Providers\SettingsServiceProvider. As you can see, I retrieve my settings using the eloquent model for it with Setting::all().
 

    public function register()
    {
        $this->app->singleton('App\GlobalSettings', function ($app) {
            return new GlobalSettings(Setting::all());
        });
    }

 
  1. Defined some useful parameters and methods (including the constructor with the needed Collection parameter) in GlobalSettings
 

    class GlobalSettings extends Model
    {
        protected $settings;
        protected $keyValuePair;

        public function __construct(Collection $settings)
        {
            $this->settings = $settings;
            foreach ($settings as $setting){
                $this->keyValuePair[$setting->key] = $setting->value;
            }
        }

        public function has(string $key){ /* check key exists */ }
        public function contains(string $key){ /* check value exists */ }
        public function get(string $key){ /* get by key */ }
    }

 
  1. At last I registered the provider in config/app.php
 

    'providers' => [
        // [...]

        App\Providers\SettingsServiceProvider::class
    ]

 
  1. After clearing the config cache with php artisan config:cache you can use your singleton as follows.
 

    $foo = app(App\GlobalSettings::class);
    echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";

 

You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.

This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.


I forgot to include the boot method of SettingsServiceProvider, to make the settings variable global available in views, so here you go:

 

    public function boot(GlobalSettings $settinsInstance)
    {
        View::share('globalsettings', $settinsInstance);
    }

 

Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings instance as parameter, so it can be injected by Laravel.

In blade template:

 

    {{ $globalsettings->get("company") }}

 

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

"inappropriate ioctl for device"

Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.

Package opencv was not found in the pkg-config search path

When you run cmake add the additional parameter -D OPENCV_GENERATE_PKGCONFIG=YES (this will generate opencv.pc file)

Then make and sudo make install as before.

Use the name opencv4 instead of just opencv Eg:-

pkg-config --modversion opencv4

How to access the php.ini from my CPanel?

In cPanel search for php, You will find "Select PHP version" under Software.

Software -> Select PHP Version -> Switch to Php Options -> Change Value -> save.

Check that an email address is valid on iOS

Heres a good one with NSRegularExpression that's working for me.

[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;

You can insert whatever regex you want but I like being able to do it in one line.

SQL statement to get column type

Use this query to get Schema, Table, Column,Type, max_length, is_nullable

SELECT QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema'
    ,QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table'
    ,C.NAME as 'Column'
    ,T.name AS 'Type'
    ,C.max_length
    ,C.is_nullable
FROM SYS.COLUMNS C INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
    INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0
ORDER BY tb.[Name]

What's the difference between StaticResource and DynamicResource in WPF?

Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. You can abstract away entire control using static resources.

Static resources are used under following circumstances:

  1. When reaction resource changes at runtime is not required.
  2. If you need a good performance with lots of resources.
  3. While referencing resources within the same dictionary.

Dynamic resources:

  1. Value of property or style setter theme is not known until runtime
    • This include system, aplication, theme based settings
    • This also includes forward references.
  2. Referencing large resources that may not load when page, windows, usercontrol loads.
  3. Referencing theme styles in a custom control.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

After nearly seven years this keeps getting different answers.† Many are similar--but none identical--to what worked for me. Here's what worked for me (Ubuntu server).

Moving a site to a new server, forgot to install the PHP MySQL module/extension. I ran a quick

apt-get install php-mysql

and then

apachectl restart

Bada bing. No php5, php7; just plain php-mysql.

Get error message if ModelState.IsValid fails?

Ok Check and Add to Watch:

  1. Do a breakpoint at your ModelState line in your Code
  2. Add your model state to your Watch
  3. Expand ModelState "Values"
  4. Expand Values "Results View"

Now you can see a list of all SubKey with its validation state at end of value.

So search for the Invalid value.

IPython/Jupyter Problems saving notebook as PDF

In any system, the basic steps to correctly setup nbconvert to convert ipython notebooks to pdf/latex are

  1. Install nbconvert
  2. Install pandoc
  3. Install Texlive

Installing nbconvert

pip install nbconvert

or conda install nbconvert

Installing pandoc

sudo apt-get install pandoc for Ubuntu

or sudo yum install pandoc for CentOS

for others visit pandoc-installation

Installing texlive

You can install recommended packages or full install. For Ubuntu

sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended

`

For others and to full install texlive follow the instructions given at tug as per your system and choice.

I downloaded tar.gz file from tug-texlive-download and followed instructions given at TeX Live - Quick install. Installation instructions in summary:

  1. Clean up

    rm -rf /usr/local/texlive/2019

    rm -rf ~/.texlive2019

  2. Run installer

    unpack the zip file

    cd /your/unpacked/directory

    perl install-tl

    Enter command: i

  3. Setting path

    sudo vi /etc/bash.bashrc and insert

    PATH=/usr/local/texlive/2019/bin/x86_64-linux:$PATH; export PATH

    MANPATH=/usr/local/texlive/2019/texmf-dist/doc/man:$MANPATH; export MANPATH

    INFOPATH=/usr/local/texlive/2019/texmf-dist/doc/info:$INFOPATH; export INFOPATH

  4. Setting default papersize

    tlmgr paper letter

The commands may differ as per your system but the basic steps remains the same.

How to update a value, given a key in a hashmap?

Use a for loop to increment the index:

for (int i =0; i<5; i++){
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("beer", 100);

    int beer = map.get("beer")+i;
    System.out.println("beer " + beer);
    System.out ....

}

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

How do I find a stored procedure containing <text>?

SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%FieldName%' 
AND ROUTINE_TYPE='PROCEDURE'

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

How should I copy Strings in Java?

String str1="this is a string";
String str2=str1.clone();

How about copy like this? I think to get a new copy is better, so that the data of str1 won't be affected when str2 is reference and modified in futher action.

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

How can I strip all punctuation from a string in JavaScript using regex?

/[^A-Za-z0-9\s]/g should match all punctuation but keep the spaces. So you can use .replace(/\s{2,}/g, " ") to replace extra spaces if you need to do so. You can test the regex in http://rubular.com/

.replace(/[^A-Za-z0-9\s]/g,"").replace(/\s{2,}/g, " ")

Update: Will only work if the input is ANSI English.

gem install: Failed to build gem native extension (can't find header files)

Red Hat, Fedora:

sudo dnf -y install gcc-c++ redhat-rpm-config ruby-devel gcc mysql-devel rubygems

Getting query parameters from react-router hash fragment

Simple js solution:

queryStringParse = function(string) {
    let parsed = {}
    if(string != '') {
        string = string.substring(string.indexOf('?')+1)
        let p1 = string.split('&')
        p1.map(function(value) {
            let params = value.split('=')
            parsed[params[0]] = params[1]
        });
    }
    return parsed
}

And you can call it from anywhere using:

var params = this.queryStringParse(this.props.location.search);

Hope this helps.

Use of Application.DoEvents()

Application.DoEvents can create problems, if something other than graphics processing is put in the message queue.

It can be useful for updating progress bars and notifying the user of progress in something like MainForm construction and loading, if that takes a while.

In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.

How to get cumulative sum

Try this:

CREATE TABLE #t(
 [name] varchar NULL,
 [val] [int] NULL,
 [ID] [int] NULL
) ON [PRIMARY]

insert into #t (id,name,val) values
 (1,'A',10), (2,'B',20), (3,'C',30)

select t1.id, t1.val, SUM(t2.val) as cumSum
 from #t t1 inner join #t t2 on t1.id >= t2.id
 group by t1.id, t1.val order by t1.id

Append text to input field

You are probably looking for val()

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

Add a summary row with totals

You could use the ROLLUP operator

SELECT  CASE 
            WHEN (GROUPING([Type]) = 1) THEN 'Total'
            ELSE [Type] END AS [TYPE]
        ,SUM([Total Sales]) as Total_Sales
From    Before
GROUP BY
        [Type] WITH ROLLUP

How to detect a textbox's content has changed

Use the onchange event in HTML/standard JavaScript.

In jQuery that is the change() event. For example:

$('element').change(function() { // do something } );

EDIT

After reading some comments, what about:

$(function() {
    var content = $('#myContent').val();

    $('#myContent').keyup(function() { 
        if ($('#myContent').val() != content) {
            content = $('#myContent').val();
            alert('Content has been changed');
        }
    });
});

How to set text color in submit button?

you try this:

<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">

How do I merge a specific commit from one branch into another in Git?

The git cherry-pick <commit> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.

Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)

Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.