Programs & Examples On #Init parameters

Check if decimal value is null

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

Allow 2 decimal places in <input type="number">

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the HTML code

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer

Creating a triangle with for loops

This lets you have a little more control and an easier time making it:

public static int biggestoddnum = 31;

public static void main(String[] args) {
    for (int i=1; i<biggestoddnum; i += 2)
    {
        for (int k=0; k < ((biggestoddnum / 2) - i / 2); k++)
        {
            System.out.print(" ");
        }
        for (int j=0; j<i; j++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }
}

Just change public static int biggestoddnum's value to whatever odd number you want it to be, and the for(int k...) has been tested to work.

Docker how to change repository name or rename image?

docker tag CURRENT_IMAGE_NAME DESIRED_IMAGE_NAME

Sending email through Gmail SMTP server with C#

You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).

Java Compare Two Lists

You can try intersection() and subtract() methods from CollectionUtils.

intersection() method gives you a collection containing common elements and the subtract() method gives you all the uncommon ones.

They should also take care of similar elements

How to correctly use the extern keyword in C

When you have that function defined on a different dll or lib, so that the compiler defers to the linker to find it. Typical case is when you are calling functions from the OS API.

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

How to split strings over multiple lines in Bash?

This isn't exactly what the user asked, but another way to create a long string that spans multiple lines is by incrementally building it up, like so:

$ greeting="Hello"
$ greeting="$greeting, World"
$ echo $greeting
Hello, World

Obviously in this case it would have been simpler to build it one go, but this style can be very lightweight and understandable when dealing with longer strings.

Export to CSV via PHP

pre-made code attached here. you can use it by just copying and pasting in your code:

https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

Disable webkit's spin buttons on input type="number"?

The below css works for both Chrome and Firefox

input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type=number] {
    -moz-appearance:textfield;
}

Multiple conditions in ngClass - Angular 4

<section [ngClass]="{'class1': expression1, 'class2': expression2, 
'class3': expression3}">

Don't forget to add single quotes around class names.

How do I retrieve query parameters in Spring Boot?

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
    @GetMapping("/system/resource")
    // this is for swagger docs
    @ApiOperation(value = "Get the resource identified by id and person")
    ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {

        InterestingResource resource = getMyInterestingResourc(id, name);
        logger.info("Request to get an id of "+id+" with a name of person: "+name);

        return new ResponseEntity<Object>(resource, HttpStatus.OK);
    }

See here also

USB Debugging option greyed out

You have to enable USB debugging before plugging your device in to the computer. Unplug device then try to enable USB debugging. This should work. If so, you can then plug it back into the computer and it should work

How do I loop through a date range?

1 Year later, may it help someone,

This version includes a predicate, to be more flexible.

Usage

var today = DateTime.UtcNow;
var birthday = new DateTime(2018, 01, 01);

Daily to my birthday

var toBirthday = today.RangeTo(birthday);  

Monthly to my birthday, Step 2 months

var toBirthday = today.RangeTo(birthday, x => x.AddMonths(2));

Yearly to my birthday

var toBirthday = today.RangeTo(birthday, x => x.AddYears(1));

Use RangeFrom instead

// same result
var fromToday = birthday.RangeFrom(today);
var toBirthday = today.RangeTo(birthday);

Implementation

public static class DateTimeExtensions 
{

    public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime> step = null)
    {
        if (step == null)
        {
            step = x => x.AddDays(1);
        }

        while (from < to)
        {
            yield return from;
            from = step(from);
        }
    }

    public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime> step = null)
    {
        return from.RangeTo(to, step);
    }
}

Extras

You could throw an Exception if the fromDate > toDate, but I prefer to return an empty range instead []

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

In my case I cloned a git-project where both Java and Kotlin included. Then checked another branch and pressed "Sync Project with Gradle Files". Android Studio 3.0.1.

How can I regenerate ios folder in React Native project?

It seems like react-native eject is no more available. The only way I could find for recreating the ios folder was to generate it from scratch.

Take a backup of your ios folder

mv /path_to_your_old_project/ios /path_to_your_backup_dir/ios_backup

Navigate to a temporary directory and create a new project with the same name as your current project

react-native init project_name
mv project_name/ios /path_to_your_old_project/ios

Install the pod dependencies inside the ios folder within your project

cd /path_to_your_old_project/ios
pod install

CSS Selector "(A or B) and C"?

Not yet, but there is the experimental :matches() pseudo-class function that does just that:

:matches(.a .b) .c {
  /* stuff goes here */
}

You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

Changing the size of a column referenced by a schema-bound view in SQL Server

Check the column collation. This script might change the collation to the table default. Add the current collation to the script.

Determine which MySQL configuration file is being used

For people running windows server with mysql as a service, an easy way to find out what config file you are running is to open up the services control panel, find your mysql service (in my case 'MYSQL56'), right click and click properties. Then from here you can check the "Path to Executable" which should have a defaults-file switch which points to where your config file is.

Find all stored procedures that reference a specific column in some table

try this..

SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%'
GO

or you can generate a scripts of all procedures and search from there.

PKIX path building failed: unable to find valid certification path to requested target

This error can also happen if the server only sends its leaf certificate and does not send all the chain certificates needed to build the trust chain to the root CA. Unfortunately this is a common misconfiguration of servers.

Most browsers work around this problem if they already know the missing chain certificate from earlier visits or maybe download the missing certificate if the leaf certificate contains a URL for CA issuers in Authority Information Access (AIA). But this behavior is usually restricted to desktop browsers and other tools simply fail because they cannot build the trust chain.

You can make the JRE to automatically download the intermediate certificate by setting com.sun.security.enableAIAcaIssuers to true

To verify if the server is sending all the chain certificates you can enter the host in the following SSL certificate validation tool https://www.digicert.com/help/

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

jQuery/JavaScript to replace broken images

Pure JS. My task was: if image 'bl-once.png' is empty -> insert the first one (that hasn't 404 status) image from array list (in current dir):

_x000D_
_x000D_
<img src="http://localhost:63342/GetImage/bl-once.png" width="200" onerror="replaceEmptyImage.insertImg(this)">
_x000D_
_x000D_
_x000D_

Maybe it needs to be improved, but:

_x000D_
_x000D_
var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array_x000D_
    var path;_x000D_
    var imgNotFounded = true; // to mark when success_x000D_
_x000D_
    var replaceEmptyImage = {_x000D_
        insertImg: function (elem) {_x000D_
_x000D_
            if (srcToInsertArr.length == 0) { // if there are no more src to try return_x000D_
                return "no-image.png";_x000D_
            }_x000D_
            if(!/undefined/.test(elem.src)) { // remember path_x000D_
                path = elem.src.split("/").slice(0, -1).join("/"); // "http://localhost:63342/GetImage"_x000D_
            }_x000D_
            var url = path + "/" + srcToInsertArr[0];_x000D_
_x000D_
            srcToInsertArr.splice(0, 1); // tried 1 src_x000D_
_x000D_
            _x000D_
                if(imgNotFounded){ // while not success_x000D_
                    replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE_x000D_
                }_x000D_
            _x000D_
_x000D_
        },_x000D_
        getImg: function (src, path, elem) { // GET IMAGE_x000D_
_x000D_
            if (src && path && elem) { // src = "http://localhost:63342/GetImage/needed.png"_x000D_
                _x000D_
                var pathArr = src.split("/"); // ["http:", "", "localhost:63342", "GetImage", "needed.png"]_x000D_
                var name = pathArr[pathArr.length - 1]; // "needed.png"_x000D_
_x000D_
                xhr = new XMLHttpRequest();_x000D_
                xhr.open('GET', src, true);_x000D_
                xhr.send();_x000D_
_x000D_
                xhr.onreadystatechange = function () {_x000D_
_x000D_
                    if (xhr.status == 200) {_x000D_
                        elem.src = src; // insert correct src_x000D_
                        imgNotFounded = false; // mark success_x000D_
                    }_x000D_
                    else {_x000D_
                        console.log(name + " doesn't exist!");_x000D_
                        elem.onerror();_x000D_
                    }_x000D_
_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
    };
_x000D_
_x000D_
_x000D_

So, it will insert correct 'needed.png' to my src or 'no-image.png' from current dir.

How do I run a single test using Jest?

If you have jest running as a script command, something like npm test, you need to use the following command to make it work:

npm test -- -t "fix order test"

Execute a shell function with timeout

You can create a function which would allow you to do the same as timeout but also for other functions:

function run_cmd { 
    cmd="$1"; timeout="$2";
    grep -qP '^\d+$' <<< $timeout || timeout=10

    ( 
        eval "$cmd" &
        child=$!
        trap -- "" SIGTERM 
        (       
                sleep $timeout
                kill $child 2> /dev/null 
        ) &     
        wait $child
    )
}

And could run as below:

run_cmd "echoFooBar" 10

Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

The program can't start because libgcc_s_dw2-1.dll is missing

I believe this is a MinGW/gcc compiler issue, rather than a Microsoft Visual Studio setup.

The libgcc_s_dw2-1.dll should be in the compiler's bin directory. You can add this directory to your PATH environment variable for runtime linking, or you can avoid the problem by adding "-static-libgcc -static-libstdc++" to your compiler flags.

If you plan to distribute the executable, the latter probably makes the most sense. If you only plan to run it on your own machine, the changing the PATH environment variable is an attractive option (keeps down the size of the executable).

Updated:

Based on feedback from Greg Treleaven (see comments below), I'm adding links to:

[Screenshot of Code::Blocks "Project build options"]

[GNU gcc link options]

The latter discussion includes -static-libgcc and -static-libstdc++ linker options.

Create aar file in Android Studio

To create AAR

while creating follow below steps.

File->New->New Module->Android Library and create.

To generate AAR

Go to gradle at top right pane in android studio follow below steps.

Gradle->Drop down library name -> tasks-> build-> assemble or assemble release

AAR will be generated in build/outputs/aar/

But if we want AAR to get generated in specific folder in project directory with name you want, modify your app level build.gradle like below

defaultConfig {
    minSdkVersion 26
    targetSdkVersion 28
    versionCode System.getenv("BUILD_NUMBER") as Integer ?: 1
    versionName "0.0.${versionCode}"


    libraryVariants.all { variant ->

        variant.outputs.all { output ->
            outputFileName = "/../../../../release/" + ("your_recommended_name.aar")
        }
    }
}

Now it will create folder with name "release" in project directory which will be having AAR.

To import "aar" into project,check below link.

How to manually include external aar package using new Gradle Android Build System

mysql_config not found when installing mysqldb python interface

On my Fedora 23 machine I had to run the following:

sudo dnf install mysql-devel

How do you pass a function as a parameter in C?

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22

Finding local maxima/minima with Numpy in a 1D numpy array

Another solution using essentially a dilate operator:

import numpy as np
from scipy.ndimage import rank_filter

def find_local_maxima(x):
   x_dilate = rank_filter(x, -1, size=3)
   return x_dilate == x

and for the minima:

def find_local_minima(x):
   x_erode = rank_filter(x, -0, size=3)
   return x_erode == x

Also, from scipy.ndimage you can replace rank_filter(x, -1, size=3) with grey_dilation and rank_filter(x, 0, size=3) with grey_erosion. This won't require a local sort, so it is slightly faster.

IE9 jQuery AJAX with CORS returns "Access is denied"

Complete instructions on how to do this using the "jQuery-ajaxTransport-XDomainRequest" plugin can be found here: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest#instructions

This plugin is actively supported, and handles HTML, JSON and XML. The file is also hosted on CDNJS, so you can directly drop the script into your page with no additional setup: http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js

FileSystemWatcher Changed event is raised twice

Well. This question is old, i was here today...but in the end i used an way simpler approach.

  1. Boolean - if something is being done, true. When it ends, false.
  2. Before processing , add it to a HashSet. This way i won't be repeating elements.
  3. Every 30 minutes the elapsed event of an timer runs, and if there's no job being executed it will clear the list (just hashset = new hashset).

I hope i contributed with something =)

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Python: Converting string into decimal number

use the built in float() function in a list comprehension.

A2 = [float(v.replace('"','').strip()) for v in A1]

Select a row from html table and send values onclick of a button

$("#table tr").click(function(){
   $(this).addClass('selected').siblings().removeClass('selected');    
   var value=$(this).find('td:first').html();
   alert(value);    
});

$('.ok').on('click', function(e){
    alert($("#table tr.selected td:first").html());
});

Demo:

http://jsfiddle.net/65JPw/2/

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

Error while trying to run project: Unable to start program. Cannot find the file specified

I personally have this issue in Visual 2012 with x64 applications when I check the option "Managed C++ Compatibility Mode" of Debugging->General options of Tools->Options menu. => Unchecking this option fixes the problem.

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

How can I add a class to a DOM element in JavaScript?

new_row.className = "aClassName";

Here's more information on MDN: className

System.BadImageFormatException: Could not load file or assembly

I had the same exception installing using correct framework.

My solution was running cmd as administrator .... then it worked fine.

Preserve Line Breaks From TextArea When Writing To MySQL

This works:

function getBreakText($t) {
    return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}

Git log to get commits only for a specific branch

I'm using the following commands:

git shortlog --no-merges --graph --abbrev-commit master..<mybranch>

or

git log --no-merges --graph --oneline --decorate master..<mybranch>

Unable to specify the compiler with CMake

I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)

It should be

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)

The same applies for g++.

How do I update a Mongo document after inserting it?

In pymongo you can update with:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
Upsert parameter will insert instead of updating if the post is not found in the database.
Documentation is available at mongodb site.

UPDATE For version > 3 use update_one instead of update:

mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)

How do you run a Python script as a service in Windows?

I started hosting as a service with pywin32.

Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge. Error messages were:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.

I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

How to encode URL to avoid special characters in Java?

Here is my solution which is pretty easy:

Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)

String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
    review = URLEncoder.encode(review,"utf-8");
    review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

How to get the size of a JavaScript object?

If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.

Mozilla provides on its wiki a list of tools to analyze memory leaks.

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

how to store Image as blob in Sqlite & how to retrieve it?

you may also want to encode and decode to/from base64

    function uncompress(str:String):ByteArray {
            import mx.utils.Base64Decoder;
            var dec:Base64Decoder = new Base64Decoder();
            dec.decode(str);
            var newByteArr:ByteArray=dec.toByteArray();        
            return newByteArr;
        }


    // Compress a ByteArray into a Base64 String.
    function compress(bytes:ByteArray):String { 
        import mx.utils.Base64Decoder; //Transform String in a ByteArray.
        import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
        var enc:Base64Encoder = new Base64Encoder();    
        enc.encodeBytes(bytes);
        return enc.drain().split("\n").join("");
    }

Pandas: Appending a row to a dataframe and specify its index label

There is another solution. The next code is bad (although I think pandas needs this feature):

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}

But the next code runs fine:

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

Git push error: "origin does not appear to be a git repository"

As it has already been mentioned in che's answer about adding the remote part, which I believe you are still missing.

Regarding your edit for adding remote on your local USB drive. First of all you must have a 'bare repository' if you want your repository to be a shared repository i.e. to be able to push/pull/fetch/merge etc..

To create a bare/shared repository, go to your desired location. In your case:

$ cd /Volumes/500gb/   
$ git init --bare myproject.git

See here for more info on creating bare repository

Once you have a bare repository set up in your desired location you can now add it to your working copy as a remote.

$ git remote add origin /Volumes/500gb/myproject.git

And now you can push your changes to your repository

$ git push origin master

set environment variable in python script

You can add elements to your environment by using

os.environ['LD_LIBRARY_PATH'] = 'my_path'

and run subprocesses in a shell (that uses your os.environ) by using

subprocess.call('sqsub -np ' + var1 + '/homedir/anotherdir/executable', shell=True)

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Remove DNS Prefetch will solve this issue.

If you're using WordPress, add this line in your theme's functions.php

remove_action( 'wp_head', 'wp_resource_hints', 2 );

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Running code in main thread from another thread

NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:

1. If your background thread has a reference to a Context object:

Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

2. If your background thread does not have (or need) a Context object

(suggested by @dzeikei):

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

Is there a label/goto in Python?

I was looking for some thing similar to

for a in xrange(1,10):
A_LOOP
    for b in xrange(1,5):
        for c in xrange(1,5):
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    goto B_LOOP;

So my approach was to use a boolean to help breaking out from the nested for loops:

for a in xrange(1,10):
    get_out = False
    for b in xrange(1,5):
        if(get_out): break
        for c in xrange(1,5):
            if(get_out): break
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    get_out = True
                    break

Writing a dictionary to a csv file with one line for every 'key: value'

Have you tried to add the "s" on: w.writerow(mydict) like this: w.writerows(mydict)? This issue happened to me but with lists, I was using singular instead of plural.

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

Easy way to export multiple data.frame to multiple Excel worksheets

I do it in this way for openxlsx using following function

mywritexlsx<-function(fname="temp.xlsx",sheetname="Sheet1",data,
                  startCol = 1, startRow = 1, colNames = TRUE, rowNames = FALSE)
{
  if(! file.exists(fname))
    wb = createWorkbook()
  else
   wb <- loadWorkbook(file =fname)
  sheet = addWorksheet(wb, sheetname)

  writeData(wb,sheet,data,startCol = startCol, startRow = startRow, 
          colNames = colNames, rowNames = rowNames)
  saveWorkbook(wb, fname,overwrite = TRUE)
}

File changed listener in Java

There is a commercial cross-desktop library for files and folders watching called JxFileWatcher. It can be downloaded from here: http://www.teamdev.com/jxfilewatcher/

Also you can see it in action online: http://www.teamdev.com/jxfilewatcher/onlinedemo/

How do I "commit" changes in a git submodule?

You can treat a submodule exactly like an ordinary repository. To propagate your changes upstream just commit and push as you would normally within that directory.

copying all contents of folder to another folder using batch file?

if you want remove the message that tells if the destination is a file or folder you just add a slash:

xcopy /s c:\Folder1 d:\Folder2\

Imitating a blink tag with CSS3 animations

If you want smooth blinking text or something a like you can use following code:

_x000D_
_x000D_
 .blinking {
    -webkit-animation: 1s blink ease infinite;
    -moz-animation: 1s blink ease infinite;
    -ms-animation: 1s blink ease infinite;
    -o-animation: 1s blink ease infinite;
    animation: 1s blink ease infinite;
  }

  @keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-moz-keyframes blink {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-webkit-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-ms-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-o-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }
_x000D_
<span class="blinking">I am smoothly blinking</span>
_x000D_
_x000D_
_x000D_

How do I use Safe Area Layout programmatically?

I'm actually using an extension for it and controlling if it is ios 11 or not.

extension UIView {

  var safeTopAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.topAnchor
    }
    return self.topAnchor
  }

  var safeLeftAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *){
      return self.safeAreaLayoutGuide.leftAnchor
    }
    return self.leftAnchor
  }

  var safeRightAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *){
      return self.safeAreaLayoutGuide.rightAnchor
    }
    return self.rightAnchor
  }

  var safeBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.bottomAnchor
    }
    return self.bottomAnchor
  }
}

Left join only selected columns in R with the merge() function

Nothing elegant but this could be another satisfactory answer.

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]

This will be useful especially when you don't need the keys that were used to join the tables in your results.

How do I access refs of a child component in the parent component

Recommended for React versions prior to 16.3

If it cannot be avoided the suggested pattern extracted from the React docs would be:

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

    render() {
        return <Child setRef={this.setRef} />
    }
}

The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

Recommended for React >= 16.3

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

import React from "react";

const LibraryButton = React.forwardRef((props, ref) => (
  <button ref={ref} {...props}>
    FancyButton
  </button>
));

class AutoFocus extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    this.childRef.current.focus();
  }

  onClick() {
    console.log("fancy!");
  }

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
  }
}

Forwarding refs HOC example

Created Components are forwarding their ref to a child node.

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

See Forwarding Refs in React docs.

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

How to change mysql to mysqli?

The first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.

To help with that, the MySQLi Extension Function Summary is definitely something that will prove helpful.

For instance:

Note: For some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)

For instance:

  • with mysql, you have to use the mysql_select_db once connected, to indicate on which database you want to do your queries
  • mysqli, on the other side, allows you to specify that database name as the fourth parameter to mysqli_connect.
  • Still, there is also a mysqli_select_db function that you can use, if you prefer.

Once you are done with that, try to execute the new version of your script... And check if everything works ; if not... Time for bug hunting ;-)

Set transparent background of an imageview on Android

In xml

@android:color/transparent

In code

mComponentName.setBackgroundResource(android.R.color.transparent);

How can I create a table with borders in Android?

I used this solution: in TableRow, I created for every cell LinearLayout with vertical line and actual cell in it, and after every TableRow, I added a horizontal line.

Look at the code below:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

Hope it will help.

running a command as a super user from a python script

Try giving the full path to apache2ctl.

Push eclipse project to GitHub with EGit

The key lies in when you create the project in eclipse.

First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.

In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. enter image description here Then you can push to github.

N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

How to convert int[] into List<Integer> in Java?

Streams

In Java 8 you can do this

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

git recover deleted file where no commit was made after the delete

The output tells you what you need to do. git reset HEAD cc.properties etc.

This will unstage the rm operation. After that, running a git status again will tell you that you need to do a git checkout -- cc.properties to get the file back.

Update: I have this in my config file

$ git config alias.unstage
reset HEAD

which I usually use to unstage stuff.

Removing unwanted table cell borders with CSS

Set the cellspacing attribute of the table to 0.

You can also use the CSS style, border-spacing: 0, but only if you don't need to support older versions of IE.

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I was facing the same issue. I noticed that in my index i had both the "on device ready" and the "document.ready" function, so removing one of them fixed my problem :)

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

SQL ORDER BY date problem

Following answer may help you

perform your date ordering by your date identifier but use to_char() function in select clause and use some other identifier in select clause for date

e.g.

SELECT TO_CHAR(DISPDATE1,'DD/MM/YYYY') AS DISPDATE,
SUM(APPLCOUNT) AS APPLIED,
SUM(CONFCOUNT) AS CONFIRMED
FROM
    (
        SELECT COUNT(ID) AS APPLCOUNT,
                   0 AS CONFCOUNT,
                   STUDENT.APPLIED_ON AS DISPDATE1
            FROM STUDENT
            WHERE STUDENT.ID = P_ID
            GROUP BY STUDENT.APPLIED_ON
        UNION
            SELECT 0 AS APPLCOUNT,
                   COUNT(ID) AS CONFCOUNT,
                   STUDENT.CONFIRMED_ON AS DISPDATE1
            FROM STUDENT
            WHERE STUDENT.ID = P_ID
            GROUP BY STUDENT.CONFIRMED_ON
    )
GROUP BY DISPDATE1
ORDER BY DISPDATE1;

Benefits of inline functions in C++?

Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.

So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

ssh_exchange_identification: Connection closed by remote host under Git bash

We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.

Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

This will help if you are connecting to some or all servers via a jump host server.

Earlier in my ~/.ssh/config file, my setting to connect were:

Host * !ssh.somejumphost.my.company.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.

To FIX the issue, all I did was, change the config to ignore git server as well:

Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.

How to debug a referenced dll (having pdb)

The most straigh forward way I found using VisualStudio 2019 to debug an external library to which you are referencing in NuGet, is by taking the following steps:

  1. Tools > Options > Debugging > General > Untick 'Enable Just My Code'

  2. Go to Assembly Explorer > Open from NuGet Packages Cache List item

  3. Type the NuGet package name you want to debug in the search field & click 'OK' enter image description here

  4. From the Assembly Explorer, right-click on the assembly imported and select 'Generate Pdb' enter image description here

  5. Select a custom path where you want to save the .PDB file and the framework you want this to be generated for

    enter image description here

  6. Copy the .PDB file from the folder generated to your Debug folder and you can now set breakpoints on this assembly's library code

Best way to change the background color for an NSView

Just set backgroundColor on the layer (after making the view layer backed).

view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

Screenshot sizes for publishing android app on Google Play

When I publish apps I use the following screenshot sizes:

Phone: 1080 x 1920 I prepare 8 images with title, some fancy background and a screenshot inside a smartphone mockup. So it's more than a simple screenshot. It gives some nice branding and helps you to stand out from other apps out there.

Tablet 7": 1200 x 1920 - I do actually a couple of raw screenshots of 7" emulator so that the user could know how the layout will appear on his device. No fancy design with titles etc.

Tablet 10": 1800 x 2560 - same thing here, just a couple of raw screenshots.

all in .png format. Hope this helps.

How to display table data more clearly in oracle sqlplus

In case you have a dump made with sqlplus and the output is garbled as someone did not set those 3 values before, there's a way out.

Just a couple hours ago DB admin send me that ugly looking output of query executed in sqlplus (I dunno, maybe he hates me...). I had to find a way out: this is an awk script to parse that output to make it at least more readable. It's far not perfect, but I did not have enough time to polish it properly. Anyway, it does the job quite well.

awk ' function isDashed(ln){return ln ~ /^---+/};function addLn(){ln2=ln1; ln1=ln0;ln0=$0};function isLoaded(){return l==1||ln2!=""}; function printHeader(){hdr=hnames"\n"hdash;if(hdr!=lastHeader){lastHeader=hdr;print hdr};hnames="";hdash=""};function isHeaderFirstLn(){return isDashed(ln0) && !isDashed(ln1) && !isDashed(ln2) }; function isDataFirstLn(){return isDashed(ln2)&&!isDashed(ln1)&&!isDashed(ln0)}                         BEGIN{_d=1;h=1;hnames="";hdash="";val="";ln2="";ln1="";ln0="";fheadln=""}                                 { addLn();  if(!isLoaded()){next}; l=1;             if(h==1){if(!isDataFirstLn()){if(_d==0){hnames=hnames" "ln1;_d=1;}else{hdash=hdash" "ln1;_d=0}}else{_d=0;h=0;val=ln1;printHeader()}}else{if(!isHeaderFirstLn()){val=val" "ln1}else{print val;val="";_d=1;h=1;hnames=ln1}}   }END{if(val!="")print val}'

In case anyone else would like to try improve this script, below are the variables: hnames -- column names in the header, hdash - dashed below the header, h -- whether I'm currently parsing header (then ==1), val -- the data, _d - - to swap between hnames and hdash, ln0 - last line read, ln1 - line read previously (it's the one i'm actually working with), ln2 - line read before ln1

Happy parsing!

Oh, almost forgot... I use this to prettify sqlplus output myself:

[oracle@ora ~]$ cat prettify_sql 
set lines 256
set trimout on
set tab off
set pagesize 100
set colsep " | "

colsep is optional, but it makes output look like sqlite which is easier to parse using scripts.

EDIT: A little preview of parsed and non-parsed output

A little preview of parsed and non-parsed output

How to update UI from another thread running in another class

You are going to have to come back to your main thread (also called UI thread) in order to update the UI. Any other thread trying to update your UI will just cause exceptions to be thrown all over the place.

So because you are in WPF, you can use the Dispatcher and more specifically a beginInvoke on this dispatcher. This will allow you to execute what needs done (typically Update the UI) in the UI thread.

You migh also want to "register" the UI in your business, by maintaining a reference to a control/form, so you can use its dispatcher.

Scala: write string to file in one statement

This is concise enough, I guess:

scala> import java.io._
import java.io._

scala> val w = new BufferedWriter(new FileWriter("output.txt"))
w: java.io.BufferedWriter = java.io.BufferedWriter@44ba4f

scala> w.write("Alice\r\nBob\r\nCharlie\r\n")

scala> w.close()

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

What does "implements" do on a class?

In Java a class can implement an interface. See http://en.wikipedia.org/wiki/Interface_(Java) for more details. Not sure about PHP.

Hope this helps.

Python decorators in classes

Here's an expansion on Michael Speer's answer to take it a few steps further:

An instance method decorator which takes arguments and acts on a function with arguments and a return value.

class Test(object):
    "Prints if x == y. Throws an error otherwise."
    def __init__(self, x):
        self.x = x

    def _outer_decorator(y):
        def _decorator(foo):
            def magic(self, *args, **kwargs) :
                print("start magic")
                if self.x == y:
                    return foo(self, *args, **kwargs)
                else:
                    raise ValueError("x ({}) != y ({})".format(self.x, y))
                print("end magic")
            return magic

        return _decorator

    @_outer_decorator(y=3)
    def bar(self, *args, **kwargs) :
        print("normal call")
        print("args: {}".format(args))
        print("kwargs: {}".format(kwargs))

        return 27

And then

In [2]:

    test = Test(3)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )
    ?
    start magic
    normal call
    args: (13, 'Test')
    kwargs: {'q': 9, 'lollipop': [1, 2, 3]}
Out[2]:
    27
In [3]:

    test = Test(4)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )
    ?
    start magic
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-3-576146b3d37e> in <module>()
          4     'Test',
          5     q=9,
    ----> 6     lollipop=[1,2,3]
          7 )

    <ipython-input-1-428f22ac6c9b> in magic(self, *args, **kwargs)
         11                     return foo(self, *args, **kwargs)
         12                 else:
    ---> 13                     raise ValueError("x ({}) != y ({})".format(self.x, y))
         14                 print("end magic")
         15             return magic

    ValueError: x (4) != y (3)

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

getResources().getColor() is deprecated

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

It is not deprecated in API Level 21, according to the documentation.

It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor() that takes the color resource ID and a Resources.Theme object) is only available in the M Developer Preview.

Hence, right now, continue using the single-parameter getColor() method. Later this year, consider using the two-parameter getColor() method on Android M devices, falling back to the deprecated single-parameter getColor() method on older devices.

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

How to pass command line arguments to a shell alias?

You may also find this command useful:

mkdir dirname && cd $_

where dirname is the name of the directory you want to create

to_string is not a member of std, says g++ (mingw)

For anyone wondering why this happens on Android, it's probably because you're using a wrong c++ standard library. Try changing the c++ library in your build.gradle from gnustl_static to c++_static and the c++ standard in your CMakeLists.txt from -std=gnu++11 to -std=c++11

Bad Gateway 502 error with Apache mod_proxy and Tomcat

You can avoid global timeouts or having to virtual hosts by specifying the proxy timeouts in the ProxyPass directive as follows:

ProxyPass /svc http://example.com/svc timeout=600
ProxyPassReverse /svc http://example.com/svc timeout=600

Notice timeout=600 seconds.

However this does not always work when you have load balancer. In that case you must add the timeouts in both the places (tested in Apache 2.2.31)

Load Balancer example:

<Proxy "balancer://mycluster">
     BalancerMember "http://member1:8080/svc" timeout=600
     BalancerMember "http://member2:8080/svc" timeout=600
</Proxy> 

ProxyPass /svc "balancer://mycluster" timeout=600
ProxyPassReverse /svc "balancer://mycluster" timeout=600

A side note: the timeout=600 on ProxyPass was not required when Chrome was the client (I don;t know why) but without this timeout on ProxyPass Internet Explorer (11) aborts saying connection reset by server.

My theory is that the :

ProxyPass timeout is used between the client(browser) and the Apache.

BalancerMember timeout is used between the Apache and the backend.

To those who use Tomcat or other backed you may also want to pay attention to the HTTP Connector timeouts.

Find nearest latitude/longitude with an SQL query

MS SQL Edition here:

        DECLARE @SLAT AS FLOAT
        DECLARE @SLON AS FLOAT

        SET @SLAT = 38.150785
        SET @SLON = 27.360249

        SELECT TOP 10 [LATITUDE], [LONGITUDE], SQRT(
            POWER(69.1 * ([LATITUDE] - @SLAT), 2) +
            POWER(69.1 * (@SLON - [LONGITUDE]) * COS([LATITUDE] / 57.3), 2)) AS distance
        FROM [TABLE] ORDER BY 3

How to determine the content size of a UIWebView?

I'm using a UIWebView that isn't a subview (and thus isn't part of the window hierarchy) to determine the sizes of HTML content for UITableViewCells. I found that the disconnected UIWebView doesn't report its size properly with -[UIWebView sizeThatFits:]. Additionally, as mentioned in https://stackoverflow.com/a/3937599/9636, you must set the UIWebView's frame height to 1 in order to get the proper height at all.

If the UIWebView's height is too big (i.e. you have it set to 1000, but the HTML content size is only 500):

UIWebView.scrollView.contentSize.height
-[UIWebView stringByEvaluatingJavaScriptFromString:@"document.height"]
-[UIWebView sizeThatFits:]

All return a height of 1000.

To solve my problem in this case, I used https://stackoverflow.com/a/11770883/9636, which I dutifully voted up. However, I only use this solution when my UIWebView.frame.width is the same as the -[UIWebView sizeThatFits:] width.

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Android Layout Animations from bottom to top and top to bottom on ImageView click

Try this :

Create anim folder inside your res folder and copy this four files :

slide_in_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>  

slide_out_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0" 
android:duration="@android:integer/config_longAnimTime" /> 

slide_in_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />

slide_out_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />

When you click on image view call:

overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);

When you click on original place call:

overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);

Main Activity :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);


    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, test.class));

        }
    });


}
    }

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

test.java :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class test extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    btn1 = (Button) findViewById(R.id.btn1);

    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         finish();
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);
            startActivity(new Intent(test.this, MainActivity.class));


        }
    });
}

    }

test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

Hope this helps.

Remove git mapping in Visual Studio 2015

The above answer did not work for me. The registry entries would just be automatically re-added when I opened the solution in Visual Studio. I found the resolution in one of the links in Matthews answer though so credit still goes to him for the correct answer.

Remove Git binding from Visual Studio 2013 solution?

Remove the hidden .git folder in your solutionfolder.

I also removed the .gitattributes and .gitignore files just to keep my folder clean.

What is pipe() function in Angular

Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

Transport endpoint is not connected

Now this answer is for those lost souls that got here with this problem because they force-unmounted the drive but their hard drive is NTFS Formatted. Assuming you have ntfs-3g installed (sudo apt-get install ntfs-3g).

sudo ntfs-3g /dev/hdd /mnt/mount_point -o force

Where hdd is the hard drive in question and the "/mnt/mount_point" directory exists.

NOTES: This fixed the issue on an Ubuntu 18.04 machine using NTFS drives that had their journal files reset through sudo ntfsfix /dev/hdd and unmounted by force using sudo umount -l /mnt/mount_point

Leaving my answer here in case this fix can aid anyone!

How to get current CPU and RAM usage in Python?

  • For CPU details use psutil library

    https://psutil.readthedocs.io/en/latest/#cpu

  • For RAM Frequency (in MHz) use the built in Linux library dmidecode and manipulate the output a bit ;). this command needs root permission hence supply your password too. just copy the following commend replacing mypass with your password

import os

os.system("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2")

------------------- Output ---------------------------
1600 MT/s
Unknown
1600 MT/s
Unknown 0

  • more specificly
    [i for i in os.popen("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2").read().split(' ') if i.isdigit()]

-------------------------- output -------------------------
['1600', '1600']

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

What is the difference between Collection and List in Java?

Java API is the best to answer this

Collection

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

List (extends Collection)

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

What is the point of "final class" in Java?

Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."

VARCHAR to DECIMAL

create function [Sistema].[fParseDecimal]
(
    @Valor nvarchar(4000)
)
returns decimal(18, 4) as begin
    declare @Valores table (Valor varchar(50));

    insert into @Valores values (@Valor);

    declare @Resultado decimal(18, 4) = (select top 1 
        cast('' as xml).value('sql:column("Valor") cast as xs:decimal ?', 'decimal(18, 4)')
    from @Valores);
    
    return @Resultado;
END

How do I sort arrays using vbscript?

When having large ("wide") arrays, instead of moving each element of a long row of data around, use a one-dimensional array with indexes of the array.

initialize ptr_arr with 0,1,2,3,..uBound(arr) then access data with

arr(field_index,ptr_arr(row_index))

instead of

arr(field_index,row_index)

and just swap the elements of ptr_arr instead of swapping the rows.

If you are processing the array row by row, eg displaying it as a , you can take the lookout out of the inner loop:

max_col=uBound(arr,1)
response.write "<table>"
for n = 0 to uBound(arr,2)
  response.write "<tr>"
  row=ptr_arr(n)
  for i=0 to max_col
    response.write "<td>"&arr(i,row)&"</td>"
  next
  response.write "</tr>
next
response.write "</table>" 

HTML input - name vs. id

name is used for form submission in DOM (Document Object Model).

ID is used to unique name of html controls in DOM specially for Javascript & CSS

Difference between SurfaceView and View?

A SurfaceView is a custom view in Android that can be used to drawn inside it.

The main difference between a View and a SurfaceView is that a View is drawn in the UI Thread, which is used for all the user interaction.

If you want to update the UI rapidly enough and render a good amount of information in it, a SurfaceView is a better choice.

But there are a few technical insides to the SurfaceView:

1. They are not hardware accelerated.

2. Normal views are rendered when you call the methods invalidate or postInvalidate(), but this does not mean the view will be immediately updated (A VSYNC will be sent, and the OS decides when it gets updated. The SurfaceView can be immediately updated.

3. A SurfaceView has an allocated surface buffer, so it is more costly

format statement in a string resource file

For me it worked like that in Kotlin:

my string.xml

 <string name="price" formatted="false">Price:U$ %.2f%n</string>

my class.kt

 var formatPrice: CharSequence? = null
 var unitPrice = 9990
 formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 99,90

For an even better result, we can do so

 <string name="price_to_string">Price:U$ %1$s</string>

 var formatPrice: CharSequence? = null
 var unitPrice = 199990
 val numberFormat = (unitPrice/100.0).toString()
 formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))

  fun formatValue(value: String) :String{
    val mDecimalFormat = DecimalFormat("###,###,##0.00")
    val s1 = value.toDouble()
    return mDecimalFormat.format(s1)
 }

 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 1.999,90

Could not complete the operation due to error 80020101. IE

when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?

wrap it in

if (window.myTimeout) { 
  clearTimeout(myTimeout);
  myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(.. and this is a matter of variable scope. If so, try this:

window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
    window.message="Logged out";   
}
function timerReset()
{


    clearTimeout(window.myTimeout);
    window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

How do I concatenate strings in Swift?

From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.” :

To combine (concatenate) two strings, the simplest approach is to use the + operator:

let s = "hello"
let s2 = " world"
let greeting = s + s2

This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation). The + operator comes with a += assignment shortcut; naturally, the variable on the left side must have been declared with var:

var s = "hello"
let s2 = " world"
s += s2

As an alternative to +=, you can call the append(_:) instance method:

var s = "hello"
let s2 = " world"
s.append(s2)

Another way of concatenating strings is with the joined(separator:) method. You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:

let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)

IntelliJ IDEA generating serialVersionUID

In addition you can add live template that will do the work.

To do it press Ctrl+Alt+S -> "Live Templates" section -> other (or w/e you wish)

And then create a new one with a definition like this:

private static final long serialVersionUID = 1L;
$END$

Then select definition scope and save it as 'serial'

Now you can type serialTAB in class body.

Delete the first three rows of a dataframe in pandas

df = df.iloc[n:]

n drops the first n rows.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

You can do the following with Unnamed Columns:

  1. Delete unnamed columns
  2. Rename them (if you want to use them)

file.csv

,A,B,C
0,1,2,3
1,4,5,6
2,7,8,9

#read file df = pd.read_csv('file.csv')

Method 1: Delete Unnamed Columns

# delete one by one like column is 'Unnamed: 0' so use it's name
df.drop('Unnamed: 0', axis=1, inplace=True)

#delete all Unnamed Columns in a single code of line using regex
df.drop(df.filter(regex="Unnamed"),axis=1, inplace=True)

Method 2: Rename Unnamed Columns

df.rename(columns = {'Unnamed: 0':'Name'}, inplace = True)

If you want to write out with a blank header as in the input file, just choose 'Name' above to be ''.

RegEx to exclude a specific string constant

You could use negative lookahead, or something like this:

^([^A]|A([^B]|B([^C]|$)|$)|$).*$

Maybe it could be simplified a bit.

How can I generate a 6 digit unique number?

<?php echo rand(100000,999999); ?>

you can generate random number

Multiple radio button groups in MVC 4 Razor

You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B

Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);

At View , you can foreach Keys in dataMap and process your action

Box shadow in IE7 and IE8

use this for fixing issue with shadow box

filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='2', OffY='2', Color='#F13434', Positive='true');

Integer to hex string in C++

My solution. Only integral types are allowed.

Update. You can set optional prefix 0x in second parameter.

definition.h

#include  <iomanip>
#include <sstream>

template <class T, class T2 = typename std::enable_if<std::is_integral<T>::value>::type>
static std::string ToHex(const T & data, bool addPrefix = true);



template<class T, class>
inline std::string Convert::ToHex(const T & data, bool addPrefix)
{
    std::stringstream sstream;
    sstream << std::hex;
    std::string ret;
    if (typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char) || sizeof(T)==1)
    {
        sstream << static_cast<int>(data);
        ret = sstream.str();
        if (ret.length() > 2)
        {
            ret = ret.substr(ret.length() - 2, 2);
        }
    }
    else
    {
        sstream << data;
        ret = sstream.str();
    }
    return (addPrefix ? u8"0x" : u8"") + ret;
}

main.cpp

#include <definition.h>
int main()
{
    std::cout << ToHex<unsigned char>(254) << std::endl;
    std::cout << ToHex<char>(-2) << std::endl;
    std::cout << ToHex<int>(-2) << std::endl;
    std::cout << ToHex<long long>(-2) << std::endl;

    std::cout<< std::endl;
    std::cout << ToHex<unsigned char>(254, false) << std::endl;
    std::cout << ToHex<char>(-2, false) << std::endl;
    std::cout << ToHex<int>(-2, false) << std::endl;
    std::cout << ToHex<long long>(-2, false) << std::endl;
    return 0;
}

Results:
0xfe
0xfe
0xfffffffe
0xfffffffffffffffe

fe
fe fffffffe
fffffffffffffffe

Reading in a JSON File Using Swift

This worked great with me

func readjson(fileName: String) -> NSData{

    let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "json")
    let jsonData = NSData(contentsOfMappedFile: path!)

    return jsonData!
}

How to convert hex strings to byte values in Java

Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?

If yes, then for each string item I would do the following:

  1. check that a string consists only of 2 characters
  2. these chars are in '0'..'9' or 'a'..'f' interval (take their case into account as well)
  3. convert each character to a corresponding number, subtracting code value of '0' or 'a'
  4. build a byte value, where first char is higher bits and second char is lower ones. E.g.

    int byteVal = (firstCharNumber << 4) | secondCharNumber;
    

Getting values from JSON using Python

Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.

data = json.loads('{"lat":444, "lon":555}')
    ret = ''
    for j in data:
        ret = ret+" "+data[j]
return ret

When you use for in this manor you get the key of the object, not the value, so you can get the value, by using the key as an index.

Show values from a MySQL database table inside a HTML table on a webpage

Here is an easy way to fetch data from a MySQL database using PDO.

define("DB_HOST", "localhost");    // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");

$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);

$print = ""; // assign an empty string

$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);

$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';

while ($names = $stmt->fetch()) { // loop and display data
    $print .= '<tr>';
    $print .= "<td>{$names->firstname}</td>";
    $print .= "<td>{$names->lastname}</td>";
    $print .= '</tr>';
}

$print .= "</table>";
echo $print;

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

Went into nuget package manager and updated my packages. Now it works. The main one I updated was the Microsoft.AspNet.WebApi.Core. May need to do this with both projects to sync up the proper references.

How do you compare two version Strings in Java?

This code try to resolve this type of comparison versions.

Most of the version specifiers, like >= 1.0, are self-explanatory. The specifier ~> has a special meaning, best shown by example. ~> 2.0.3 is identical to >= 2.0.3 and < 2.1. ~> 2.1 is identical to >= 2.1 and < 3.0.

public static boolean apply(String cmpDeviceVersion, String reqDeviceVersion)
{
    Boolean equal           = !cmpDeviceVersion.contains(">") && !cmpDeviceVersion.contains(">=") &&
                              !cmpDeviceVersion.contains("<") && !cmpDeviceVersion.contains("<=") &&
                              !cmpDeviceVersion.contains("~>");

    Boolean between         = cmpDeviceVersion.contains("~>");
    Boolean higher          = cmpDeviceVersion.contains(">") && !cmpDeviceVersion.contains(">=") && !cmpDeviceVersion.contains("~>");
    Boolean higherOrEqual   = cmpDeviceVersion.contains(">=");

    Boolean less            = cmpDeviceVersion.contains("<") && !cmpDeviceVersion.contains("<=");
    Boolean lessOrEqual     = cmpDeviceVersion.contains("<=");

    cmpDeviceVersion        = cmpDeviceVersion.replaceAll("[<>=~]", "");
    cmpDeviceVersion        = cmpDeviceVersion.trim();

    String[] version        = cmpDeviceVersion.split("\\.");
    String[] reqVersion     = reqDeviceVersion.split("\\.");

    if(equal)
    {
        return isEqual(version, reqVersion);
    }
    else if(between)
    {
        return isBetween(version, reqVersion);
    }
    else if(higher)
    {
        return isHigher(version, reqVersion);
    }
    else if(higherOrEqual)
    {
        return isEqual(version, reqVersion) || isHigher(version, reqVersion);
    }
    else if(less)
    {
        return isLess(version, reqVersion);
    }
    else if(lessOrEqual)
    {
        return isEqual(version, reqVersion) || isLess(version, reqVersion);
    }

    return false;
}

private static boolean isEqual(String[] version, String[] reqVersion)
{
    String strVersion = StringUtils.join(version);
    String strReqVersion = StringUtils.join(reqVersion);
    if(version.length > reqVersion.length)
    {
        Integer diff = version.length - reqVersion.length;
        strReqVersion += StringUtils.repeat(".0", diff);
    }
    else if(reqVersion.length > version.length)
    {
        Integer diff = reqVersion.length - version.length;
        strVersion += StringUtils.repeat(".0", diff);
    }

    return strVersion.equals(strReqVersion);
}

private static boolean isHigher(String[] version, String[] reqVersion)
{
    String strVersion = StringUtils.join(version);
    String strReqVersion = StringUtils.join(reqVersion);
    if(version.length > reqVersion.length)
    {
        Integer diff = version.length - reqVersion.length;
        strReqVersion += StringUtils.repeat(".0", diff);
    }
    else if(reqVersion.length > version.length)
    {
        Integer diff = reqVersion.length - version.length;
        strVersion += StringUtils.repeat(".0", diff);
    }

    return strReqVersion.compareTo(strVersion) > 0;
}

private static boolean isLess(String[] version, String[] reqVersion)
{
    String strVersion = StringUtils.join(version);
    String strReqVersion = StringUtils.join(reqVersion);
    if(version.length > reqVersion.length)
    {
        Integer diff = version.length - reqVersion.length;
        strReqVersion += StringUtils.repeat(".0", diff);
    }
    else if(reqVersion.length > version.length)
    {
        Integer diff = reqVersion.length - version.length;
        strVersion += StringUtils.repeat(".0", diff);
    }

    return strReqVersion.compareTo(strVersion) < 0;
}

private static boolean isBetween(String[] version, String[] reqVersion)
{
    return (isEqual(version, reqVersion) || isHigher(version, reqVersion)) &&
            isLess(getNextVersion(version), reqVersion);
}

private static String[] getNextVersion(String[] version)
{
    String[] nextVersion = new String[version.length];
    for(int i = version.length - 1; i >= 0 ; i--)
    {
        if(i == version.length - 1)
        {
            nextVersion[i] = "0";
        }
        else if((i == version.length - 2) && NumberUtils.isNumber(version[i]))
        {
            nextVersion[i] = String.valueOf(NumberUtils.toInt(version[i]) + 1);
        }
        else
        {
            nextVersion[i] = version[i];
        }
    }
    return nextVersion;
}

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

# select '2010-01-01 12:00:00'::timestamp;
      timestamp      
---------------------
 2010-01-01 12:00:00

Now we'll cast it to a date:

wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
    date    
------------
 2010-01-01

On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

=> select date_trunc('day', now());
       date_trunc
------------------------
 2015-12-15 00:00:00+02
(1 row)

Make TextBox uneditable

You can try using:

textBox.ReadOnly = true;
textBox.BackColor = System.Drawing.SystemColors.Window;

The last line is only neccessary if you want a non-grey background color.

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

PHP Array to CSV

Instead of writing out values consider using fputcsv().

This may solve your problem immediately.

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Delete the last two characters of the String

You may use the following method to remove last n character -

public String removeLast(String s, int n) {
    if (null != s && !s.isEmpty()) {
        s = s.substring(0, s.length()-n);
    }
    return s;
}

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Print specific part of webpage

You can use simple JavaScript to print a specific div from a page.

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

How to delete file from public folder in laravel 5.1

this method worked for me
First, put the line below at the beginning of your controller:

use File;

below namespace in your php file Second:

 $destinationPath = 'your_path';
 File::delete($destinationPath.'/your_file');

$destinationPath --> the folder inside folder public.

How can I convert JSON to a HashMap using Gson?

With google's Gson 2.7 (probably earlier versions too, but I tested with the current version 2.7) it's as simple as:

Map map = gson.fromJson(jsonString, Map.class);

Which returns a Map of type com.google.gson.internal.LinkedTreeMap and works recursively on nested objects, arrays, etc.

I ran the OP example like so (simply replaced double- with single-quotes and removed whitespace):

String jsonString = "{'header': {'alerts': [{'AlertID': '2', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}, {'AlertID': '3', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}], 'session': '0bc8d0835f93ac3ebbf11560b2c5be9a'}, 'result': '4be26bc400d3c'}";
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map.getClass().toString());
System.out.println(map);

And got the following output:

class com.google.gson.internal.LinkedTreeMap
{header={alerts=[{AlertID=2, TSExpires=null, Target=1, Text=woot, Type=1}, {AlertID=3, TSExpires=null, Target=1, Text=woot, Type=1}], session=0bc8d0835f93ac3ebbf11560b2c5be9a}, result=4be26bc400d3c}

How can I check MySQL engine type for a specific table?

If you're using MySQL Workbench, right-click a table and select alter table.

In that window you can see your table Engine and also change it.

Is there a way to break a list into columns?

If you can support it CSS Grid is probably the cleanest way for making a one-dimensional list into a two column layout with responsive interiors.

_x000D_
_x000D_
ul {_x000D_
  max-width: 400px;_x000D_
  display: grid;_x000D_
  grid-template-columns: 50% 50%;_x000D_
  padding-left: 0;_x000D_
  border: 1px solid blue;_x000D_
}_x000D_
_x000D_
li {_x000D_
  list-style: inside;_x000D_
  border: 1px dashed red;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
  <li>6</li>_x000D_
  <li>7</li>_x000D_
  <li>8</li>_x000D_
  <li>9</li>_x000D_
<ul>
_x000D_
_x000D_
_x000D_

These are the two key lines which will give you your 2 column layout

display: grid;
grid-template-columns: 50% 50%;

Matplotlib - global legend and title aside subplots

For legend labels can use something like below. Legendlabels are the plot lines saved. modFreq are where the name of the actual labels corresponding to the plot lines. Then the third parameter is the location of the legend. Lastly, you can pass in any arguments as I've down here but mainly need the first three. Also, you are supposed to if you set the labels correctly in the plot command. To just call legend with the location parameter and it finds the labels in each of the lines. I have had better luck making my own legend as below. Seems to work in all cases where have never seemed to get the other way going properly. If you don't understand let me know:

legendLabels = []
for i in range(modSize):
    legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]       
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)

You can also use the leg to change fontsizes or nearly any parameter of the legend.

Global title as stated in the above comment can be done with adding text per the link provided: http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html

f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
       verticalalignment='top')

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code
});

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

I have faced the same issue. The error output window looks like this: authentication failed Image

Following the steps resolved the issue:

  1. Go to Control Panel --> Credential Manager --> Windows Credentials
  2. Below Generic Credential, choose an entry of the git & update password.

    solution window

  3. Password should be same as windows(system) login password.

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I also had to update the version of Tomcat I was using from Tomcat 7 to Tomcat 8.

Send POST data via raw json with postman

I was facing the same problem, following code worked for me:

$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);

Git error when trying to push -- pre-receive hook declined

A default branch (e.g. master) does not yet exist for your remote. So you first need to create master branch in the git remote server (e.g. creating a default README.md file) then try to push all your existing local branches using this command:

git push -u origin --all

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.

How to remove numbers from a string?

You're remarkably close.

Here's the code you wrote in the question:

questionText.replace(/[0-9]/g, '');

The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.

However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:

questionText = questionText.replace(/[0-9]/g, '');

Location of sqlite database on the device

well this might be late but it will help. You can access the database without rooting your device through adb

start the adb using cmd and type the following commands

-run-as com.your.package  
-shell@android:/data/data/com.your.package $ ls  
cache  
databases  
lib  
shared_prefs  

Now you can open from here on.

How to grep recursively, but only in files with certain extensions?

ag (the silver searcher) has pretty simple syntax for this

       -G --file-search-regex PATTERN
          Only search files whose names match PATTERN.

so

ag -G *.h -G *.cpp CP_Image <path>

How can I permanently enable line numbers in IntelliJ?

For 9.0.4

File > Settings

In the tree view group

------------IDE Settings ---------

Click the Editor [+]

Select Appearance... Its there.

How to use WPF Background Worker

  1. Add using
using System.ComponentModel;
  1. Declare Background Worker:
private readonly BackgroundWorker worker = new BackgroundWorker();
  1. Subscribe to events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
  1. Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                           RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
  1. Run worker async whenever your need.
worker.RunWorkerAsync();
  1. Track progress (optional, but often useful)

    a) subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork

    b) set worker.WorkerReportsProgress = true; (credits to @zagy)

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

If you only need to remove the first character you would do:

s = ":dfa:sif:e"
fixed = s[1:]

If you want to remove a character at a particular position, you would do:

s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]

If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

How to pass multiple parameters in thread in VB

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

How can I set Image source with base64

In case you prefer to use jQuery to set the image from Base64:

$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');

jQuery Button.click() event is triggered twice

If you're using AngularJS:

If you're using AngularJS and your jQuery click event is INSIDE THE CONTROLLER, it will get disturbed by the Angular's framework itself and fire twice. To solve this, move it out of the controller and do the following:

// Make sure you're using $(document), or else it won't fire.
$(document).on("click", "#myTemplateId #myButtonId", function () {
   console.log("#myButtonId is fired!");
   // Do something else.
});

angular.module("myModuleName")
   .controller("myController", bla bla bla)

Extract the filename from a path

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

How do I declare a two dimensional array?

For a simple, "fill as you go" kind of solution:

$foo = array(array());

This will get you a flexible pseudo two dimensional array that can hold $foo[n][n] where n <= 8 (of course your limited by the usual constraints of memory size, but you get the idea I hope). This could, in theory, be extended to create as many sub arrays as you need.

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

Can't import javax.servlet.annotation.WebServlet

Copy servlet-api.jar from your tomcat server lib folder.

enter image description here

Paste it to WEB-INF > lib folder

enter image description here

Error was solved!!!

How to get parameters from a URL string?

you can use below code to get email address after ? in the URL

_x000D_
_x000D_
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
    echo $_GET['email'];_x000D_
}
_x000D_
_x000D_
_x000D_

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

Printing integer variable and string on same line in SQL

You may try this one,

declare @Number INT = 5                            
print 'There are ' + CONVERT(VARCHAR, @Number) + ' alias combinations did not match a record'

SQL Server using wildcard within IN

  1. I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z

  2. I had to write a script to pull the current user (declare them) and pull the masks for the declared user.

  3. Create some temporary tables just basic ones to rank the row numbers for this current user

  4. loop through each result (YOUR Or this Or that etc...)

  5. Insert into the test Table.

Here is the script I used:

Drop Table #UserMasks 
Drop Table #TESTUserMasks 

Create Table #TESTUserMasks (
    [User] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

Create Table #UserMasks (
    [RN] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

DECLARE @User INT
SET @User = 74054

Insert Into #UserMasks 
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
       REPLACE(mask,'?','') Mask
from dbo.Access_Masks 
where prontouserid = @User

DECLARE @TopFlag INT
SET @TopFlag = 1

WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
    Insert Into #TestUserMasks 
    select (@User),Code from dbo.MaskArrayLookupTable 
    where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)

    SET @TopFlag = @TopFlag + 1
END
GO

select * from #TESTUserMasks

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

The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.

It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.


Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart() method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?

How to Implement DOM Data Binding in JavaScript

Changing an element's value can trigger a DOM event. Listeners that respond to events can be used to implement data binding in JavaScript.

For example:

function bindValues(id1, id2) {
  const e1 = document.getElementById(id1);
  const e2 = document.getElementById(id2);
  e1.addEventListener('input', function(event) {
    e2.value = event.target.value;
  });
  e2.addEventListener('input', function(event) {
    e1.value = event.target.value;
  });
}

Here is code and a demo that shows how DOM elements can be bound with each other or with a JavaScript object.

Plotting a 2D heatmap with Matplotlib

Seaborn takes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()

enter image description here

Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()

enter image description here

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

How to check the Angular version?

Angular CLI ng v does output few more thing than just the version.

If you only want the version from it the you can add pipe grep and filter for angular like:

ng v | grep 'Angular:'

OUTPUT:

Angular: #.#.# <-- VERSION

For this, I have an alias which is

alias ngv='ng v | grep 'Angular:''

Then just use ngv

How to parse JSON without JSON.NET library?

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OTL
{
    /// <summary>
    /// Before usage: Define your class, sample:
    /// [DataContract]
    ///public class MusicInfo
    ///{
    ///   [DataMember(Name="music_name")]
    ///   public string Name { get; set; }
    ///   [DataMember]
    ///   public string Artist{get; set;}
    ///}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class OTLJSON<T> where T : class
    {
        /// <summary>
        /// Serializes an object to JSON
        /// Usage: string serialized = OTLJSON&lt;MusicInfo&gt;.Serialize(musicInfo);
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string Serialize(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// DeSerializes an object from JSON
        /// Usage:  MusicInfo deserialized = OTLJSON&lt;MusicInfo&gt;.Deserialize(json);
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
                throw new Exception("Json can't empty");
            else
                try
                {
                    using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
                    {

                        var serializer = new DataContractJsonSerializer(typeof(T));
                        return serializer.ReadObject(stream) as T;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Json can't convert to Object because it isn't correct format.");
                }
        }
    }
}

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

"Are you missing an assembly reference?" compile error - Visual Studio

I encountered this error with an Azure DevOps Services (MS-hosted) build pipeline on a TFVC repo.

In my case, I was working within a branch and had accidentally added the reference from the package folder in trunk instead of from the branch. Once I added the reference from within the branch, it started compiling successfully.

I.e., while working on \branch-beta\sierra.csproj, I accidentally referenced \trunk\packages\delta.dll. Obviously, I needed to reference \branch-beta\packages\delta.dll instead. The mixup occurred because the path is not prominently displayed in the Add Reference window and I didn’t check carefully enough.

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

How to convert a string with Unicode encoding to a string of letters

I wrote a performanced and error-proof solution:

public static final String decode(final String in) {
    int p1 = in.indexOf("\\u");
    if (p1 < 0)
        return in;
    StringBuilder sb = new StringBuilder();
    while (true) {
        int p2 = p1 + 6;
        if (p2 > in.length()) {
            sb.append(in.subSequence(p1, in.length()));
            break;
        }
        try {
            int c = Integer.parseInt(in.substring(p1 + 2, p1 + 6), 16);
            sb.append((char) c);
            p1 += 6;
        } catch (Exception e) {
            sb.append(in.subSequence(p1, p1 + 2));
            p1 += 2;
        }
        int p0 = in.indexOf("\\u", p1);
        if (p0 < 0) {
            sb.append(in.subSequence(p1, in.length()));
            break;
        } else {
            sb.append(in.subSequence(p1, p0));
            p1 = p0;
        }
    }
    return sb.toString();
}

WP -- Get posts by category?

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>

Working with huge files in VIM

Old thread. But nevertheless( pun :) ).

 $less filename

less works efficiently if you don't want to edit and just look around which is the case for examining huge log files.

Search in less works like vi

Best part, it's available by default on most distros. So won't be problem for production environment as well.

C++ Double Address Operator? (&&)

&& is new in C++11, and it signifies that the function accepts an RValue-Reference -- that is, a reference to an argument that is about to be destroyed.

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

How to Replace Multiple Characters in SQL?

I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.