Programs & Examples On #Spell checking

Flagging words in a document that may not be spelled correctly.

Spell Checker for Python

spell corrector->

you need to import a corpus on to your desktop if you store elsewhere change the path in the code i have added a few graphics as well using tkinter and this is only to tackle non word errors!!

def min_edit_dist(word1,word2):
    len_1=len(word1)
    len_2=len(word2)
    x = [[0]*(len_2+1) for _ in range(len_1+1)]#the matrix whose last element ->edit distance
    for i in range(0,len_1+1):  
        #initialization of base case values
        x[i][0]=i
        for j in range(0,len_2+1):
            x[0][j]=j
    for i in range (1,len_1+1):
        for j in range(1,len_2+1):
            if word1[i-1]==word2[j-1]:
                x[i][j] = x[i-1][j-1]
            else :
                x[i][j]= min(x[i][j-1],x[i-1][j],x[i-1][j-1])+1
    return x[i][j]
from Tkinter import *


def retrieve_text():
    global word1
    word1=(app_entry.get())
    path="C:\Documents and Settings\Owner\Desktop\Dictionary.txt"
    ffile=open(path,'r')
    lines=ffile.readlines()
    distance_list=[]
    print "Suggestions coming right up count till 10"
    for i in range(0,58109):
        dist=min_edit_dist(word1,lines[i])
        distance_list.append(dist)
    for j in range(0,58109):
        if distance_list[j]<=2:
            print lines[j]
            print" "   
    ffile.close()
if __name__ == "__main__":
    app_win = Tk()
    app_win.title("spell")
    app_label = Label(app_win, text="Enter the incorrect word")
    app_label.pack()
    app_entry = Entry(app_win)
    app_entry.pack()
    app_button = Button(app_win, text="Get Suggestions", command=retrieve_text)
    app_button.pack()
    # Initialize GUI loop
    app_win.mainloop()

How to stop app that node.js express 'npm start'

All the other solutions here are OS dependent. An independent solution for any OS uses socket.io as follows.

package.json has two scripts:

"scripts": {
  "start": "node server.js",
  "stop": "node server.stop.js"
}

server.js - Your usual express stuff lives here

const express = require('express');
const app = express();
const server = http.createServer(app);
server.listen(80, () => {
  console.log('HTTP server listening on port 80');
});

// Now for the socket.io stuff - NOTE THIS IS A RESTFUL HTTP SERVER
// We are only using socket.io here to respond to the npmStop signal
// To support IPC (Inter Process Communication) AKA RPC (Remote P.C.)

const io = require('socket.io')(server);
io.on('connection', (socketServer) => {
  socketServer.on('npmStop', () => {
    process.exit(0);
  });
});

server.stop.js

const io = require('socket.io-client');
const socketClient = io.connect('http://localhost'); // Specify port if your express server is not using default port 80

socketClient.on('connect', () => {
  socketClient.emit('npmStop');
  setTimeout(() => {
    process.exit(0);
  }, 1000);
});

Test it out

npm start (to start your server as usual)

npm stop (this will now stop your running server)

The above code has not been tested (it is a cut down version of my code, my code does work) but hopefully it works as is. Either way, it provides the general direction to take if you want to use socket.io to stop your server.

Change PictureBox's image to image from my resources?

You must specify the full path of the resource file as the name of 'image within the resources of your application, see example below.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    PictureBox1.Image = My.Resources.Chrysanthemum
End Sub

In the path assigned to the Image property after MyResources specify the name of the resource.

But before you do whatever you have to import in the resource section of your application from an image file exists or it can create your own.

Bye

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

try giving AppPool ID or Network Services whichever applicable access HKLM\SYSTEM\CurrentControlSet\services\eventlog\security also. I was getting the same error .. this worked for me. See the error is also saying that the inaccessible logs are Security Logs.

I also gave permission in eventlog\application .

I gave full access everywhere.

How to read a config file using python

A convenient solution in your case would be to include the configs in a yaml file named **your_config_name.yml** which would look like this:

path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"

In your python code you can then load the config params into a dictionary by doing this:

import yaml
with open('your_config_name.yml') as stream:
    config = yaml.safe_load(stream)

You then access e.g. path1 like this from your dictionary config:

config['path1']

To import yaml you first have to install the package as such: pip install pyyaml into your chosen virtual environment.

How to change the Spyder editor background to dark?

At First click on preferences(Ctrl+Shift+alt+p) then click the option of syntax coloring and change the scheme to "Monokai".Now apply it and you will get the dark scheme.

LINQ Joining in C# with multiple conditions

As far as I know you can only join this way:

var query = from obj_i in set1
join obj_j in set2 on 
    new { 
      JoinProperty1 = obj_i.SomeField1,
      JoinProperty2 = obj_i.SomeField2,
      JoinProperty3 = obj_i.SomeField3,
      JoinProperty4 = obj_i.SomeField4
    } 
    equals 
    new { 
      JoinProperty1 = obj_j.SomeOtherField1,
      JoinProperty2 = obj_j.SomeOtherField2,
      JoinProperty3 = obj_j.SomeOtherField3,
      JoinProperty4 = obj_j.SomeOtherField4
    }

The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.

You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.

More advanced stuff in this LinqPad example:

class c1 
    {
    public int someIntField;
    public string someStringField;
    }
    
class c2 
    {
    public Int64 someInt64Property {get;set;}
    private object someField;
    public string someStringFunction(){return someField.ToString();}
    }
    
void Main()
{
    var set1 = new List<c1>();
    var set2 = new List<c2>();
    
    var query = from obj_i in set1
    join obj_j in set2 on 
        new { 
                JoinProperty1 = (Int64) obj_i.someIntField,
                JoinProperty2 = obj_i.someStringField
            } 
        equals 
        new { 
                JoinProperty1 = obj_j.someInt64Property,
                JoinProperty2 = obj_j.someStringFunction()
            }
    select new {obj1 = obj_i, obj2 = obj_j};
}

Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.

Change the current directory from a Bash script

This approach is easier for me.

Suppose on a personal iMac where you are an admin, under the default directory when a command window is opened, /Users/jdoe, this will be the directory to go to: /Users/jdoe/Desktop/Mongo/db.3.2.1/bin.

These are the steps that can have the job done:

  1. vi mongobin, in which I entered: cd /Users/jdoe/Desktop/Mongo/db.3.2.1/bin as the first line.
  2. chmod 755 mongobin
  3. source mongobin
  4. pwd

Voila!

How do I use MySQL through XAMPP?

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.

After the successful installation navigate to your xampp folder and execute the xampp-control.exe

Press the start Button at the mysql row.

enter image description here

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.

But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.

Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.

enter image description here

Can someone explain the dollar sign in Javascript?

The $ sign is an identifier for variables and functions.

https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign

That has a clear explanation of what the dollar sign is for.

Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html

Remove all constraints affecting a UIView

I use the following method to remove all constraints from a view:

.h file:

+ (void)RemoveContraintsFromView:(UIView*)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child;

.m file:

+ (void)RemoveContraintsFromView:(UIView *)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child
{
    if (parent) {
        // Remove constraints between view and its parent.
        UIView *superview = view.superview;
        [view removeFromSuperview];
        [superview addSubview:view];
    }

    if (child) {
        // Remove constraints between view and its children.
        [view removeConstraints:[view constraints]];
    }
}

You can also read this post on my blog to better understand how it works behind the hood.

If you need more granular control, I'd strongly advise switching to Masonry, a powerful framework class you could use whenever you need to properly handle constraints programmatically.

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

How to filter multiple values (OR operation) in angularJS

You can also use ngIf if the situation permits:

<div ng-repeat="p in [
 { name: 'Justin' }, 
 { name: 'Jimi' }, 
 { name: 'Bob' }
 ]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
 {{ p.name }} is cool
</div>

How to add a new object (key-value pair) to an array in javascript?

New solution with ES6

Default object

object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];

Another object

object =  {'id': 5};

Object assign ES6

resultObject = {...obj, ...newobj};

Result

[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];

android get real path by Uri.getPath()

Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI() and ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path.

download file using an ajax request

Your needs are covered by window.location('download.php');
But I think that you need to pass the file to be downloaded, not always download the same file, and that's why you are using a request, one option is to create a php file as simple as showfile.php and do a request like

var myfile = filetodownload.txt
var url = "shofile.php?file=" + myfile ;
ajaxRequest.open("GET", url, true);

showfile.php

<?php
$file = $_GET["file"] 
echo $file;

where file is the file name passed via Get or Post in the request and then catch the response in a function simply

if(ajaxRequest.readyState == 4){
                        var file = ajaxRequest.responseText;
                        window.location = 'downfile.php?file=' + file;  
                    }
                }

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

C++ Get name of type in template

I just leave it there. If someone will still need it, then you can use this:

template <class T>
bool isString(T* t) { return false;  } // normal case returns false

template <>
bool isString(char* t) { return true; }  // but for char* or String.c_str() returns true
.
.
.

This will only CHECK type not GET it and only for 1 type or 2.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Death is a simple library that uses channels and a wait group to wait for shutdown signals. Once the signal has been received it will then call a close method on all of your structs that you want to cleanup.

Fragment transaction animation: slide in and slide out

This is another solution which I use:

public class CustomAnimator {
    private static final String TAG = "com.example.CustomAnimator";

    private static Stack<AnimationEntry> animation_stack    = new Stack<>();

    public static final int                 DIRECTION_LEFT  = 1;
    public static final int                 DIRECTION_RIGHT = -1;
    public static final int                 DIRECTION_UP    = 2;
    public static final int                 DIRECTION_DOWN  = -2;

    static class AnimationEntry {
        View in;
        View    out;
        int     direction;
        long    duration;
    }

    public static boolean hasHistory() {
        return !animation_stack.empty();
    }

    public static void reversePrevious() {
        if (!animation_stack.empty()) {
            AnimationEntry entry = animation_stack.pop();
            slide(entry.out, entry.in, -entry.direction, entry.duration, false);
        }
    }

    public static void clearHistory() {
        animation_stack.clear();
    }

    public static void slide(final View in, View out, final int direction, long duration) {
        slide(in, out, direction, duration, true);
    }

    private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {

        ViewGroup in_parent = (ViewGroup) in.getParent();
        ViewGroup out_parent = (ViewGroup) out.getParent();

        if (!in_parent.equals(out_parent)) {
            return;
        }

        int parent_width = in_parent.getWidth();
        int parent_height = in_parent.getHeight();

        ObjectAnimator slide_out;
        ObjectAnimator slide_in;

        switch (direction) {
            case DIRECTION_LEFT:
            default:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
                break;
            case DIRECTION_RIGHT:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
                break;
            case DIRECTION_UP:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
                break;
            case DIRECTION_DOWN:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
                break;
        }

        AnimatorSet animations = new AnimatorSet();
        animations.setDuration(duration);
        animations.playTogether(slide_in, slide_out);
        animations.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                out.setVisibility(View.INVISIBLE);
                if (save) {
                    AnimationEntry ae = new AnimationEntry();
                    ae.in = in;
                    ae.out = out;
                    ae.direction = direction;
                    ae.duration = duration;
                    animation_stack.push(ae);
                }
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {
                in.setVisibility(View.VISIBLE);
            }
        });
        animations.start();
    }
}

The usage of class. Let's say you have two fragments (list and details fragments)as shown below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/list_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/details_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</FrameLayout>

Usage

View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);

You can use the function CustomAnimator.reversePrevious();to get the previous view when the user pressed back.

How can I output UTF-8 from Perl?

You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL but also PERL5OPT=-Mutf8.

Mapping US zip code to time zone

If you want, you can also get a feel for the timezone by asking the browser Josh Fraser has a nice write up on it here

var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);

The second thing that you need to know is whether the location observes daylight savings time (DST) or not. Since DST is always observed during the summer, we can compare the time offset between two dates in January, to the time offset between two dates in June. If the offsets are different, then we know that the location observes DST. If the offsets are the same, then we know that the location DOES NOT observe DST.

var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
temp = june1.toGMTString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
    dst = "0"; // daylight savings time is NOT observed
} else {
    dst = "1"; // daylight savings time is observed
}

All credit for this goes to Josh Fraser.

This might help you with customers outside the US, and it might complement your zip approach.

Here is a SO questions that touch on getting the timezone from javascript

How can javascript upload a blob?

I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107

function uploadAudio( blob ) {
  var reader = new FileReader();
  reader.onload = function(event){
    var fd = {};
    fd["fname"] = "test.wav";
    fd["data"] = event.target.result;
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: fd,
      dataType: 'text'
    }).done(function(data) {
        console.log(data);
    });
  };
  reader.readAsDataURL(blob);
}

Contents of upload.php

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

jQuery Button.click() event is triggered twice

If you use

$( document ).ready({ })

or

$(function() { });

more than once, the click function will trigger as many times as it is used.

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Passing HTML input value as a JavaScript Function Parameter

Use this it will work,

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    var m = document.getElementById("a").value;
    var n = document.getElementById("b").value;
    var sum = m + n;
    alert(sum);
  }
</script>
</body>

Targeting .NET Framework 4.5 via Visual Studio 2010

Each version of Visual Studio prior to Visual Studio 2010 is tied to a specific .NET framework. (VS2008 is .NET 3.5, VS2005 is .NET 2.0, VS2003 is .NET1.1) Visual Studio 2010 and beyond allow for targeting of prior framework versions but cannot be used for future releases. You must use Visual Studio 2012 in order to utilize .NET 4.5.

Ansible: copy a directory content to another directory

I got involved whole a day, too! and finally found the solution in shell command instead of copy: or command: as below:

- hosts: remote-server-name
  gather_facts: no
  vars:
    src_path: "/path/to/source/"
    des_path: "/path/to/dest/"
  tasks:
  - name: Ansible copy files remote to remote
    shell: 'cp -r {{ src_path }}/. {{ des_path }}'

strictly notice to: 1. src_path and des_path end by / symbol 2. in shell command src_path ends by . which shows all content of directory 3. I used my remote-server-name both in hosts: and execute shell section of jenkins, instead of remote_src: specifier in playbook.

I guess it is a good advice to run below command in Execute Shell section in jenkins:

ansible-playbook  copy-payment.yml -i remote-server-name

Creating SolidColorBrush from hex color value

vb.net version

Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)

Java reflection: how to get field value from an object, not knowing its class

I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>.

However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:

List<Object> list = new ArrayList<Object>();

list.add("some value");
list.add(3);

for(Object obj : list)
{
    Class<?> clazz = obj.getClass();

    Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
    org.springframework.util.ReflectionUtils.makeAccessible(field);

    System.out.println("value=" + field.get(obj));
}

Running this has an output of:

value=[C@1b67f74
value=3

Convert tuple to list and back

Just using the command list did not work for me.

if you have a tuple just iterate until you have the elements there are necessary and after that append to a list. And if you go to the element level you can change it easily.

input:

level1 = (
         (1,1,1,1,1,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,1,1,1,1,1))

level1_as_list=[]
for i in level1:
    inside_list=[]
    for j in i:
        inside_list.append(j)
    level1_as_list.append(inside_list)

print(level1_as_list)enter code here

output:

[[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1]]

How to listen for a WebView finishing loading a URL?

If you want show a progress bar you need to listen for a progress change event, not just for the completion of page:

mWebView.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                //change your progress bar
            }


        });

BTW if you want display just an Indeterminate ProgressBar overriding the method onPageFinished is enough

What's the best way to detect a 'touch screen' device using JavaScript?

The practical answer seems to be one that considers the context:

1) Public site (no login)
Code the UI to work with both options together.

2) Login site
Capture whether a mouse-move occurred on the login form, and save this into a hidden input. The value is passed with the login credentials and added to the user's session, so it can be used for the duration of the session.

Jquery to add to login page only:

$('#istouch').val(1); // <-- value will be submitted with login form

if (window.addEventListener) {
    window.addEventListener('mousemove', function mouseMoveListener(){
        // Update hidden input value to false, and stop listening
        $('#istouch').val(0); 
        window.removeEventListener('mousemove', mouseMoveListener);
    });
} 

(+1 to @Dave Burt and +1 to @Martin Lantzsch on their answers)

Copy/duplicate database without using mysqldump

The best way to clone database tables without mysqldump:

  1. Create a new database.
  2. Create clone-queries with query:

    SET @NewSchema = 'your_new_db';
    SET @OldSchema = 'your_exists_db';
    SELECT CONCAT('CREATE TABLE ',@NewSchema,'.',table_name, ' LIKE ', TABLE_SCHEMA ,'.',table_name,';INSERT INTO ',@NewSchema,'.',table_name,' SELECT * FROM ', TABLE_SCHEMA ,'.',table_name,';') 
    FROM information_schema.TABLES where TABLE_SCHEMA = @OldSchema AND TABLE_TYPE != 'VIEW';
    
  3. Run that output!

But note, script above just fast clone tables - not views, triggers and user-functions: you can fast get structure by mysqldump --no-data --triggers -uroot -ppassword , and then use to clone only insert statement .

Why it is actual question? Because uploading of mysqldumps is ugly slow if DB is over 2Gb. And you can't clone InnoDB tables just by copying DB files (like snapshot backuping).

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Bash script prints "Command Not Found" on empty lines

I ran into this today, absentmindedly copying the dollar command prompt $ (ahead of a command string) into the script.

How can I get the status code from an http error in Axios?

This is a known bug, try to use "axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.

How to get all table names from a database?

public static ArrayList<String> getTablesList(Connection conn)
            throws SQLException {

        ArrayList<String> listofTable = new ArrayList<String>();

        DatabaseMetaData md = conn.getMetaData();

        ResultSet rs = md.getTables(null, null, "%", null);

        while (rs.next()) {
            if (rs.getString(4).equalsIgnoreCase("TABLE")) {
                listofTable.add(rs.getString(3));
            }
        }
        return listofTable;
    }

Android SDK Manager Not Installing Components

I had same problem when I try to install it on my pc (Win7, 64-bit system). I had an error message shown in figure below. But when I check my local folder 'C:\Users\username\AppData\Local\Android\sdk', the Android SDK is already there. Somehow Android studio could not see/link it.

So please check first whether you can find the Android SDK in the local folder. If yes, just follow the next steps.

  1. Chose 'Cancel' and click on 'X' on the top right corner. enter image description here
  2. Chose 'Do not re-run the setup wizard' and click 'OK' enter image description here
  3. Start Android Studio again and go 'Configure'-->'Project Defaults' --> 'Project Structure' enter image description here
  4. Add 'C:\Users\username\AppData\Local\Android\sdk' to 'Android Location' and click 'OK' List item
  5. Click on 'Start a new Android Studio project'.

Hopefully it helps.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

LAST_INSERT_ID() MySQL

Just to add for Rodrigo post, instead of LAST_INSERT_ID() in query you can use SELECT MAX(id) FROM table1;, but you must use (),

INSERT INTO table1 (title,userid) VALUES ('test', 1)
INSERT INTO table2 (parentid,otherid,userid) VALUES ( (SELECT MAX(id) FROM table1), 4, 1)

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

Is it possible to print a variable's type in standard C++?

Very ugly but does the trick if you only want compile time info (e.g. for debugging):

auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;

Returns:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'

How do I get logs from all pods of a Kubernetes replication controller?

I use this simple script to get a log from the pods of a deployment:

#!/usr/bin/env bash

DEPLOYMENT=$1

for p in $(kubectl get pods | grep ^${DEPLOYMENT}- | cut -f 1 -d ' '); do 
    echo --------------------------- 
    echo $p 
    echo --------------------------- 
    kubectl logs $p
done

Gist of the script

Usage: log_deployment.sh "deployment-name".

Script will then show log of all pods that start with that "deployment-name".

Servlet for serving static content

I've had good results with FileServlet, as it supports pretty much all of HTTP (etags, chunking, etc.).

How to change color of ListView items on focus and on click

listview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view,
                final int position, long id) {
            // TODO Auto-generated method stub

             parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));

            return false;
        }
    });

What is the difference between '/' and '//' when used for division?

Python 3.x Clarification

Just to complement some previous answers.

It is important to remark that:

a // b

  • Is floor division. As in:

    math.floor(a/b)

  • Is not int division. As in:

    int(a/b)

  • Is not round to 0 float division. As in:

    round(a/b,0)

As a consequence, the way of behaving is different when it comes to positives an negatives numbers as in the following example:

1 // 2 is 0, as in:

math.floor(1/2)

-1 // 2 is -1, as in:

math.floor(-1/2)

Upgrade version of Pandas

According to an article on Medium, this will work:

install --upgrade pandas==1.0.0rc0

How do I capture the output into a variable from an external process in PowerShell?

Or try this. It will capture output into variable $scriptOutput:

& "netdom.exe" $params | Tee-Object -Variable scriptOutput | Out-Null

$scriptOutput

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

ValueError: math domain error

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.

Java ArrayList replace at specific index

Check out the set(int index, E element) method in the List interface

Location of sqlite database on the device

You can find your database file :

Context.getDatabasePath(getDatabaseName())

getDatabaseName from class SQLiteOpenHelper

Displaying a 3D model in JavaScript/HTML5

I have not played with 3D yet, but I know a good place for ressources on 3D for HTML5.

http://www.html5rocks.com/en/gaming

And here is a tutorial on how to create your 3D models with the Three.js Framework.

http://www.html5rocks.com/en/tutorials/three/intro/

This may help you. Good luck.

How to remove leading zeros using C#

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

After experimenting on that case: android:textColor="@colors/text_color" is wrong since @color is not filename dependant. You can name your resource file foobar.xml, it doesn't matter but if you have defined some colors in it you can access them using @color/some_color.

Update:

file location: res/values/colors.xml The filename is arbitrary. The element's name will be used as the resource ID. (Source)

How do I assign ls to an array in Linux Bash?

This would print the files in those directories line by line.

array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"

Node.js/Express.js App Only Works on Port 3000

In bin/www, there is a line:

var port = normalizePort(process.env.PORT || '3000');

Try to modify it.

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

Maximum execution time in phpMyadmin

Changing php.ini for a web application requires restarting Apache.

You should verify that the change took place by running a PHP script that executes the function phpinfo(). The output of that function will tell you a lot of PHP parameters, including the timeout value.

You might also have changed a copy of php.ini that is not the same file used by Apache.

What is the difference between Digest and Basic Authentication?

Let us see the difference between the two HTTP authentication using Wireshark (Tool to analyse packets sent or received) .

1. Http Basic Authentication

Basic

As soon as the client types in the correct username:password,as requested by the Web-server, the Web-Server checks in the Database if the credentials are correct and gives the access to the resource .

Here is how the packets are sent and received :

enter image description here In the first packet the Client fill the credentials using the POST method at the resource - lab/webapp/basicauth .In return the server replies back with http response code 200 ok ,i.e, the username:password were correct .

Detail of HTTP packet

Now , In the Authorization header it shows that it is Basic Authorization followed by some random string .This String is the encoded (Base64) version of the credentials admin:aadd (including colon ) .

2 . Http Digest Authentication(rfc 2069)

So far we have seen that the Basic Authentication sends username:password in plaintext over the network .But the Digest Auth sends a HASH of the Password using Hash algorithm.

Here are packets showing the requests made by the client and response from the server .

Digest

As soon as the client types the credentials requested by the server , the Password is converted to a response using an algorithm and then is sent to the server , If the server Database has same response as given by the client the server gives the access to the resource , otherwise a 401 error .

Detailed digest auth packet In the above Authorization , the response string is calculated using the values of Username,Realm,Password,http-method,URI and Nonce as shown in the image :

Response algorithm (colons are included)

Hence , we can see that the Digest Authentication is more Secure as it involve Hashing (MD5 encryption) , So the packet sniffer tools cannot sniff the Password although in Basic Auth the exact Password was shown on Wireshark.

Checking if a string array contains a value, and if so, getting its position

IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList<T>.Contains(T item) method the following way:

((IList<string>)stringArray).Contains(value)

Complete code sample:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");

T[] arrays privately implement a few methods of List<T>, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.

Keep in mind not all IList<T> methods work this way. Trying to use IList<T>'s Add method on an array will fail.

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

Make a table fill the entire window

Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>

How to run JUnit test cases from the command line

For JUnit 5.x it's:

java -jar junit-platform-console-standalone-<version>.jar <Options>

Find a brief summary at https://stackoverflow.com/a/52373592/1431016 and full details at https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher

For JUnit 4.X it's really:

java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

But if you are using JUnit 3.X note the class name is different:

java -cp .:/usr/share/java/junit.jar junit.textui.TestRunner [test class name]

You might need to add more JARs or directories with your class files to the classpath and separate that with semicolons (Windows) or colons (UNIX/Linux). It depends on your environment.

Edit: I've added current directory as an example. Depends on your environment and how you build your application (can be bin/ or build/ or even my_application.jar etc). Note Java 6+ does support globs in classpath, you can do:

java -cp lib/*.jar:/usr/share/java/junit.jar ...

Hope it helps. Write tests! :-)

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

How to hash a string into 8 digits?

Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

This means the hash()-based solution suggested, which can be shortened to just:

hash(s) % 10**8

will only return the same value within a given script run:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.

How to replace all spaces in a string

Pure Javascript, without regular expression:

var result = replaceSpacesText.split(" ").join("");

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

Try this:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

How to Generate unique file names in C#

If the readability of the file name isn't important, then the GUID, as suggested by many will do. However, I find that looking into a directory with 1000 GUID file names is very daunting to sort through. So I usually use a combination of a static string which gives the file name some context information, a timestamp, and GUID.

For example:

public string GenerateFileName(string context)
{
    return context + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N");
}

filename1 = GenerateFileName("MeasurementData");
filename2 = GenerateFileName("Image");

This way, when I sort by filename, it will automatically group the files by the context string and sort by timestamp.

Note that the filename limit in windows is 255 characters.

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

Java 8 optional: ifPresent return object orElseThrow exception

I'd prefer mapping after making sure the value is available

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

or one liner

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

What's the difference between ViewData and ViewBag?

Can I recommend to you to not use either?

If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.

If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.

If you are using these consider how you might be able to restructure and just use ViewModels.

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

How to convert a string into double and vice versa?

For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.

int myInt = (int)round( [@"1.6" floatValue] );

NSString* myString = [@(myInt) description];

(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)

What is the Swift equivalent to Objective-C's "@synchronized"?

I like and use many of the answers here, so I'd choose whichever works best for you. That said, the method I prefer when I need something like objective-c's @synchronized uses the defer statement introduced in swift 2.

{ 
    objc_sync_enter(lock)
    defer { objc_sync_exit(lock) }

    //
    // code of critical section goes here
    //

} // <-- lock released when this block is exited

The nice thing about this method, is that your critical section can exit the containing block in any fashion desired (e.g., return, break, continue, throw), and "the statements within the defer statement are executed no matter how program control is transferred."1

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

How to change value of object which is inside an array using JavaScript or jQuery?

You can create your specific function like the below, then use that everywhere you need.

var each    = (arr, func) => 
                Array.from(
                    (function* (){
                        var i = 0;
                        for(var item of arr)
                            yield func(item, i++);
                    })()
                );

Enjoy..

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

Convert SVG to PNG in Python

Here is what I did using cairosvg:

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

And it works like a charm!

See more: cairosvg document

Android: Color To Int conversion

Paint DOES have set color function.

/**
 * Set the paint's color. Note that the color is an int containing alpha
 * as well as r,g,b. This 32bit value is not premultiplied, meaning that
 * its alpha can be any value, regardless of the values of r,g,b.
 * See the Color class for more details.
 *
 * @param color The new color (including alpha) to set in the paint.
 */
public native void setColor(@ColorInt int color);

As an Android developer, I set paint color like this...

paint.setColor(getResources().getColor(R.color.xxx));

I define the color value on color.xml something like...

<color name="xxx">#008fd2</color>

By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm

I hope this helps ! Enjoy coding!

How do I convert a float number to a whole number in JavaScript?

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

How do I show the number keyboard on an EditText in android?

editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

How to comment/uncomment in HTML code

My view templates are generally .php files. This is what I would be using for now.

<?php // Some comment here ?>

The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

Get hours difference between two dates in Moment Js

var __startTime = moment("2016-06-06T09:00").format();
var __endTime = moment("2016-06-06T21:00").format();

var __duration = moment.duration(moment(__endTime).diff(__startTime));
var __hours = __duration.asHours();
console.log(__hours);

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

How do I convert ticks to minutes?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.

So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min

Or you can do it programmaticly with TimeSpan:

    static void Main()
    {
        TimeSpan ts = TimeSpan.FromTicks(28000000000);
        double minutesFromTs = ts.TotalMinutes;
        Console.WriteLine(minutesFromTs);
        Console.Read();
    }

Both give me 46 min and not 480 min...

How to read XML response from a URL in java?

I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.

import org.xml.sax.*;
import javax.xml.parsers.*;

XMLReader        parser;

try {
    SAXParserFactory factory;

    factory = SAXParserFactory.newInstance ();
    factory.setNamespaceAware (true);
    parser = factory.newSAXParser ().getXMLReader ();
    // success!

} catch (FactoryConfigurationError err) {
    System.err.println ("can't create JAXP SAXParserFactory, "
    + err.getMessage ());
} catch (ParserConfigurationException err) {
    System.err.println ("can't create XMLReader with namespaces, "
    + err.getMessage ());
} catch (SAXException err) {
    System.err.println ("Hmm, SAXException, " + err.getMessage ());
}

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

Save Javascript objects in sessionStorage

The solution is to stringify the object before calling setItem on the sessionStorage.

var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);

Better way to find last used row

You should use a with statement to qualify both your Rows and Columns counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.

Last Column

With Sheets("Sheet2")
    .Cells(1, .Columns.Count).End(xlToLeft).Column
End With 

Last Row

With Sheets("Sheet2")
    .Range("A" & .Rows.Count).End(xlUp).Row
End With 

Or

With Sheets("Sheet2")
    .Cells(.Rows.Count, 1).End(xlUp).Row
End With 

Find current directory and file's directory

1.To get the current directory full path

    >>import os
    >>print os.getcwd()

o/p:"C :\Users\admin\myfolder"

1.To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]

o/p:"myfolder"

How to paste into a terminal?

On windows 7:

Ctrl + Shift + Ins

works for me!

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

php artisan dump-autoload was deprecated on Laravel 5, so you need to use composer dump-autoload

How to remove a row from JTable?

If you need a simple working solution, try using DefaultTableModel.

If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.

For example, if you have used Vector, then it may be something like this:

public class SimpleTableModel extends AbstractTableModel {
    private Vector<String> columnNames = new Vector<String>();
    // Each value in the vector is a row; String[] - row data;
    private Vector<String[]> data = new Vector<String[]>();

    ...

    public String getValueAt(int row, int col) {
        return data.get(row)[col];
    }

    ...

    public void removeRow(int row) {
        data.removeElementAt(row);
    }
}

If you have used List, then it would be very much alike:

// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();

public void removeRow(int row) {
    data.remove(row);
}

HashMap:

//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();

public void removeRow(Integer row) {
    data.remove(row);
}

And if you are using arrays like this one

String[][] data = { { "a", "b" }, { "c", "d" } };

then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.

For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.

Async await in linq select

"Just because you can doesn't mean you should."

You can probably use async/await in LINQ expressions such that it will behave exactly as you want it to, but will any other developer reading your code still understand its behavior and intent?

(In particular: Should the async operations be run in parallel or are they intentionally sequential? Did the original developer even think about it?)

This is also shown clearly by the question, which seems to have been asked by a developer trying to understand someone else's code, without knowing its intent. To make sure this does not happen again, it may be best to rewrite the LINQ expression as a loop statement, if possible.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How to check all checkboxes using jQuery?

if($('#chk_all').is(":checked"))
 {
    $('#'+id).attr('checked', true);
 }
else
 {
    $('#'+id).attr('checked', false);
 }  

Call child component method from parent class - Angular

You can do this by using @ViewChild for more info check this link

With type selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild(ChildCmp) child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

With string selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild('child') child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

Why is 2 * (i * i) faster than 2 * i * i in Java?

Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer

On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:

public static void main(String[] args) {
    int repeat = 10;
    long A = 0;
    long B = 0;
    for (int i = 0; i < repeat; i++) {
        A += test();
        B += testB();
    }

    System.out.println(A / repeat + " ms");
    System.out.println(B / repeat + " ms");
}


private static long test() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multi(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multi(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms A " + n);
    return ms;
}


private static long testB() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multiB(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multiB(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms B " + n);
    return ms;
}

private static int multiB(int i) {
    return 2 * (i * i);
}

private static int multi(int i) {
    return 2 * i * i;
}

Output:

...
405 ms A 785527736
327 ms B 785527736
404 ms A 785527736
329 ms B 785527736
404 ms A 785527736
328 ms B 785527736
404 ms A 785527736
328 ms B 785527736
410 ms
333 ms

So why? The byte code is this:

 private static multiB(int arg0) { // 2 * (i * i)
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         iload0
         imul
         imul
         ireturn
     }
     L2 {
     }
 }

 private static multi(int arg0) { // 2 * i * i
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         imul
         iload0
         imul
         ireturn
     }
     L2 {
     }
 }

The difference being: With brackets (2 * (i * i)):

  • push const stack
  • push local on stack
  • push local on stack
  • multiply top of stack
  • multiply top of stack

Without brackets (2 * i * i):

  • push const stack
  • push local on stack
  • multiply top of stack
  • push local on stack
  • multiply top of stack

Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.

What is the Angular equivalent to an AngularJS $watch?

Try this when your application still demands $parse, $eval, $watch like behavior in Angular

https://github.com/vinayk406/angular-expression-parser

Tower of Hanoi: Recursive Algorithm

There are three towers namely source tower, destination tower and helper tower. The source tower has all the disks and your target is to move all the disks to the destination tower and make sure in doing so, you never put a larger disk on top of a smaller disk. We can solve this problem using recursion in the steps below:

We have n numbers of disks on source tower

Base case: n=1 If there is only one disk in source tower, move it to destination tower.

Recursive case: n >1

  • Move the top n-1 disks from from source tower to helper tower
  • Move the only remaining, the nth disk(after step1) to destination tower
  • Move the n-1 disks that are in helper tower now, to destination
    tower, using source tower as a helper.

Source code in Java:

private void towersOfHanoi(int n, char source, char destination, char helper) {
    //Base case, If there is only one disk move it direct from source to destination
    if(n==1){
        System.out.println("Move from "+source+" to "+destination);
    }
    else{
        //Step1: Move the top n-1 disks from source to helper
        towersOfHanoi(n-1, source, helper, destination);
        //Step2: Move the nth disk from source to destination
        System.out.println("Move from "+source+" to "+destination);
        /*Step3: Move the n-1 disks(those you moved from source to helper in step1) 
         * from helper to destination, using source(empty after step2) as helper
         */
        towersOfHanoi(n-1, helper, destination, source);
    }
}

Determining if Swift dictionary contains key and obtaining any of its values

Here is what works for me on Swift 3

let _ = (dict[key].map { $0 as? String } ?? "")

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

Use URI builder in Android or create URL with variables

Let's say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.myawesomesite.com")
    .appendPath("turtles")
    .appendPath("types")
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
    .fragment("section-name");
String myUrl = builder.build().toString();

How to implement zoom effect for image view in android?

Here is one of the most efficient way, it works smoothly:

https://github.com/MikeOrtiz/TouchImageView

Place TouchImageView.java in your project. It can then be used the same as ImageView.

Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view.

Example:

    <com.example.touch.TouchImageView
            android:id="@+id/img”
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

How to add border radius on table row

Or use box-shadow if table have collapse

How to check if a symlink exists

-L is the test for file exists and is also a symbolic link

If you do not want to test for the file being a symbolic link, but just test to see if it exists regardless of type (file, directory, socket etc) then use -e

So if file is really file and not just a symbolic link you can do all these tests and get an exit status whose value indicates the error condition.

if [ ! \( -e "${file}" \) ]
then
     echo "%ERROR: file ${file} does not exist!" >&2
     exit 1
elif [ ! \( -f "${file}" \) ]
then
     echo "%ERROR: ${file} is not a file!" >&2
     exit 2
elif [ ! \( -r "${file}" \) ]
then
     echo "%ERROR: file ${file} is not readable!" >&2
     exit 3
elif [ ! \( -s "${file}" \) ]
then
     echo "%ERROR: file ${file} is empty!" >&2
     exit 4
fi

In SQL, how can you "group by" in ranges?

declare @RangeWidth int

set @RangeWidth = 10

select
   Floor(Score/@RangeWidth) as LowerBound,
   Floor(Score/@RangeWidth)+@RangeWidth as UpperBound,
   Count(*)
From
   ScoreTable
group by
   Floor(Score/@RangeWidth)

When does a process get SIGABRT (signal 6)?

It usually happens when there is a problem with memory allocation.

It happened to me when my program was trying to allocate an array with negative size.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Displaying a flash message after redirect in Codeigniter

In Your Controller set this

<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Please check below link for Displaying a flash message after redirect in Codeigniter

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

This error happened to me when I was using Visual Studio Code. I think it must have been because I was trying to build a project while there was an executable running in the same bin\debug folder. I stopped the executable, closed the folder, reopened, rebuilt, and the error went away.

REST API 404: Bad URI, or Missing Resource?

404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13 that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.

To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.

VB.net Need Text Box to Only Accept Numbers

Use this in your Textbox Keydown event.

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    'you can enter decimal "if nonNumberEntered(e, TextBox1, True) then" 
    'otherwise just numbers "if nonNumberEntered(e, TextBox1) then"
    If nonNumberEntered(e, TextBox1, True) Then
        e.SuppressKeyPress = True
    End If
    If e.KeyCode = Keys.Enter Then
        'put your code here
    End If

End Sub

Copy this function in any module inside your vb.net project.

Public Function nonNumberEntered(ByVal e As System.Windows.Forms.KeyEventArgs, _
                          ByVal ob As TextBox, _
                          Optional ByVal decim As Boolean = False) As Boolean
    nonNumberEntered = False

    If decim Then
        ' Determine whether the keystroke is a number from the top of the keyboard.
        If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
            ' Determine whether the keystroke is a number from the keypad.
            If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
                If e.KeyCode <> Keys.Decimal And e.KeyCode <> Keys.OemPeriod Then
                    If e.KeyCode <> Keys.Divide And e.KeyCode <> Keys.OemQuestion Then
                        ' Determine whether the keystroke is a backspace.
                        If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
                        And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
                            ' A non-numerical keystroke was pressed. 
                            nonNumberEntered = True
                        End If
                    ElseIf ob.Text.Contains("/") Or ob.Text.Length = 0 Then
                        nonNumberEntered = True
                    End If
                ElseIf ob.Text.Contains(".") Or ob.Text.Length = 0 Then
                    nonNumberEntered = True
                End If
            End If
        End If
    Else
        ' Determine whether the keystroke is a number from the top of the keyboard.
        If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
            ' Determine whether the keystroke is a number from the keypad.
            If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
                ' Determine whether the keystroke is a backspace.
                If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
                    And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
                    ' A non-numerical keystroke was pressed. 
                    nonNumberEntered = True
                End If
            End If
        End If
    End If

    'If shift key was pressed, it's not a number.
    If Control.ModifierKeys = Keys.Shift Then
        nonNumberEntered = True
    End If

End Function

This will allow numbers like 2/4 or numbers like 3.5 to be entered in your textbox if using decim "nonNumberEntered(e,Textbox1, True)".

Allows only numbers to be entered in textbox if using "nonNumberEntered(e,Textbox1, False)" or "nonNumberEntered(e,Textbox1)".

Edit: added text.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How do ACID and database transactions work?

ACID is a set of properties that you would like to apply when modifying a database.

  • Atomicity
  • Consistency
  • Isolation
  • Durability

A transaction is a set of related changes which is used to achieve some of the ACID properties. Transactions are tools to achieve the ACID properties.

Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.

Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.

Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.

Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.

So, transactions are a mechanism for guaranteeing these properties; they are a way of grouping related actions together such that as a whole, a group of operations can be atomic, produce consistent results, be isolated from other operations, and be durably recorded.

Django Admin - change header 'Django administration' text

Update: If you are using Django 1.7+, see the answer below.


Original answer from 2011: You need to create your own admin base_site.html template to do this. The easiest way is to create the file:

/<projectdir>/templates/admin/base_site.html

This should be a copy of the original base_site.html, except putting in your custom title:

{% block branding %}
<h1 id="site-name">{% trans 'my cool admin console' %}</h1>
{% endblock %}

For this to work, you need to have the correct settings for your project, namely in settings.py:

  • Make sure /projectdir/templates/ is added into TEMPLATE_DIRS.
  • Make sure django.template.loaders.filesystem.Loader is added into TEMPLATE_LOADERS.

See docs for more information on settings.py.

How to do a SOAP wsdl web services call from the command line

It's a standard, ordinary SOAP web service. SSH has nothing to do here. I just called it with (one-liner):

$ curl -X POST -H "Content-Type: text/xml" \
    -H 'SOAPAction: "http://api.eyeblaster.com/IAuthenticationService/ClientLogin"' \
    --data-binary @request.xml \
    https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc

Where request.xml file has the following contents:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.eyeblaster.com/">
           <soapenv:Header/>
           <soapenv:Body>
              <api:ClientLogin>
                 <api:username>user</api:username>
                 <api:password>password</api:password>
                 <api:applicationKey>key</api:applicationKey>
              </api:ClientLogin>
          </soapenv:Body>
</soapenv:Envelope>

I get this beautiful 500:

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode>s:Security.Authentication.UserPassIncorrect</faultcode>
      <faultstring xml:lang="en-US">The username, password or application key is incorrect.</faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>

Have you tried ?

Read more

Wait until page is loaded with Selenium WebDriver for Python

The webdriver will wait for a page to load by default via .get() method.

As you may be looking for some specific element as @user227215 said, you should use WebDriverWait to wait for an element located in your page:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
    myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"

I have used it for checking alerts. You can use any other type methods to find the locator.

EDIT 1:

I should mention that the webdriver will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions.

How to drop a list of rows from Pandas dataframe?

Determining the index from the boolean as described above e.g.

df[df['column'].isin(values)].index

can be more memory intensive than determining the index using this method

pd.Index(np.where(df['column'].isin(values))[0])

applied like so

df.drop(pd.Index(np.where(df['column'].isin(values))[0]), inplace = True)

This method is useful when dealing with large dataframes and limited memory.

Can Windows Containers be hosted on linux?

No, you cannot run windows containers directly on Linux.

But you can run Linux on Windows.

Windows Server/10 comes packaged with base image of ubuntu OS (after september 2016 beta service pack). That is the reason you can run linux on windows and not other wise. Check out here. https://thenewstack.io/finally-linux-containers-really-will-run-windows-linuxkit/

You can change between OS containers Linux and windows by right clicking on the docker in tray menu.

enter image description here

enter image description here

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

How to create multiple page app using react

The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:

    entry: {
            outputone: './source/fileone.jsx',
            outputtwo: './source/filetwo.jsx'
            },
    output: {
            path: path.resolve(__dirname, './wwwroot/js/dist'),
            filename: '[name].js'      
            },

This will generate 2 files: outputone.js und outputtwo.js in the target folder.

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

How to get a variable name as a string in PHP?

I know this is old and already answered but I was actually looking for this. I am posting this answer to save people a little time refining some of the answers.

Option 1:

$data = array('$FooBar');  

$vars = [];  
$vars = preg_replace('/^\\$/', '', $data); 

$varname = key(compact($vars));  
echo $varname;

Prints:

FooBar

For whatever reason you would find yourself in a situation like this, it does actually work.

.
Option 2:

$FooBar = "a string";  

$varname = trim(array_search($FooBar, $GLOBALS), " \t.");  
echo $varname;

If $FooBar holds a unique value, it will print 'FooBar'. If $FooBar is empty or null it will print the name of the first empty or null string it finds.

It could be used as such:

if (isset($FooBar) && !is_null($FooBar) && !empty($FooBar)) {
    $FooBar = "a string";
    $varname = trim(array_search($FooBar, $GLOBALS), " \t.");
}

Change span text?

document.getElementById("serverTime").innerHTML = ...;

How to check if an element is off-screen

No need for a plugin to check if outside of view port.

var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();

$.each($("div"),function(){
    p = $(this).position();
    //vertical
    if (p.top > h + d || p.top > h - d){
        console.log($(this))
    }
    //horizontal
    if (p.left < 0 - $(this).width() || p.left > w){
        console.log($(this))
    }
});

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

How do I correctly upgrade angular 2 (npm) to the latest version?

Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final is npm-check-updates

It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated it is also capable to edit your package.json, enabling you to do a npm upgrade later.

Install

sudo npm install -g npm-check-updates

Usage

ncufor display

ncu -u for re-writing your package.json

How to linebreak an svg text within javascript?

I have adapted a bit the solution by @steco, switching the dependency from d3 to jquery and adding the height of the text element as parameter

function wrap(text, width, height) {
  text.each(function(idx,elem) {
    var text = $(elem);
    text.attr("dy",height);
        var words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat( text.attr("dy") ),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (elem.getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

Does Index of Array Exist

You can rather use a List, so you can check the existence.

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

How to open a file for both reading and writing?

I have tried something like this and it works as expected:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

Where:

f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.

And:

f.write(string) writes the contents of string to the file, returning None.

Also if you open Python tutorial about reading and writing files you will find that:

'r+' opens the file for both reading and writing.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

How to convert Double to int directly?

try casting the value

double d = 1.2345;
long l = (long) d;

Turning off hibernate logging console output

Try to set more reasonable logging level. Setting logging level to info means that only log event at info or higher level (warn, error and fatal) are logged, that is debug logging events are ignored.

log4j.logger.org.hibernate=info

or in XML version of log4j config file:

<logger name="org.hibernate">
  <level value="info"/> 
</logger>

See also log4j manual.

Call method in directive controller from other controller

You could also expose the directive's controller to the parent scope, like ngForm with name attribute does: http://docs.angularjs.org/api/ng.directive:ngForm

Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview

In this example I have myDirective with dedicated controller with $clear method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...

Verify a certificate chain using openssl verify

I've had to do a verification of a letsencrypt certificate and I did it like this:

  1. Download the root-cert and the intermediate-cert from the letsencrypt chain of trust.
  2. Issue this command:

    $ openssl verify -CAfile letsencrypt-root-cert/isrgrootx1.pem.txt -untrusted letsencrypt-intermediate-cert/letsencryptauthorityx3.pem.txt /etc/letsencrypt/live/sitename.tld/cert.pem 
    /etc/letsencrypt/live/sitename.tld/cert.pem: OK
    

cannot resolve symbol javafx.application in IntelliJ Idea IDE

You need to download the java-openjfx package from the official Arch Linux repos. (Also, make sure you have the openjdk8-openjdk package). After doing that, open your project in Intellij and go to Project-Structure -> SDKs -> 1.8 -> Classpath and try removing the old JDK you had and clicking on the directory for the new JDK that will now contain jfxrt.jar.

Reverse Contents in Array

I would try to using pointers to solve this problem:

#include <iostream>

void displayArray(int table[], int size);

void rev(int table[], int size);


int main(int argc, char** argv) {

    int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

    rev(a, 10);
    displayArray(a, 10);

    return 0;
}

void displayArray(int table[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << table[i] << " ";
    }
    std::cout << std::endl;
}

void rev(int table[], int size) {

    int *start = table;
    int *end = table + (size - 1);

    for (int i = 0; i < size; i++) {

        if (start < end) {
            int temp = *end;
            *end = *start;
            *start = temp;
        }

        start++;
        end--;
    }
}

How to show shadow around the linearlayout in Android?

There is no such attribute in Android, to show a shadow. But possible ways to do it are:

  1. Add a plain LinearLayout with grey color, over which add your actual layout, with margin at bottom and right equal to 1 or 2 dp

  2. Have a 9-patch image with a shadow and set it as the background to your Linear layout

How do I print the content of a .txt file in Python?

to input a file:

fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'

to output this file you can do:

for element in fin:
    print element 

if the elements are a string you'd better add this before print:

element = element.strip()

strip() remove notations like this: /n

How to print a stack trace in Node.js?

In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link

Then walk through the trace.

  var stackTrace = require('stack-trace');
  .
  .
  .
  var trace = stackTrace.get();
  trace.map(function (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  
  });

Or just simply print the trace:

var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

How do I create a random alpha-numeric string in C++?

Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

#include <iostream>
#include <ctime>
#include <unistd.h>

using namespace std;

string gen_random(const int len) {
    
    string tmp_s;
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    
    srand( (unsigned) time(NULL) * getpid());

    tmp_s.reserve(len);

    for (int i = 0; i < len; ++i) 
        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
    
    
    return tmp_s;
    
}

int main(int argc, char *argv[]) {
    
    cout << gen_random(12) << endl;
    
    return 0;
}

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

How to navigate back to the last cursor position in Visual Studio Code?

I am on Mac OSX, so I can't answer for windows users:

I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).

One can simply modify it in the user keymap settings:

{ "key": "ctrl+left",  "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }

For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?

Combine Date and Time columns using python pandas

You can use this to merge date and time into the same column of dataframe.

import pandas as pd    
data_file = 'data.csv' #path of your file

Reading .csv file with merged columns Date_Time:

data = pd.read_csv(data_file, parse_dates=[['Date', 'Time']]) 

You can use this line to keep both other columns also.

data.set_index(['Date', 'Time'], drop=False)

Resolving a Git conflict with binary files

mipadi's answer didn't quite work for me, I needed to do this :

git checkout --ours path/to/file.bin

or, to keep the version being merged in:

git checkout --theirs path/to/file.bin

then

git add path/to/file.bin

And then I was able to do "git mergetool" again and continue onto the next conflict.

How do I add a bullet symbol in TextView?

Another best way to add bullet in any text view is stated below two steps:

First, create a drawable

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <!--set color of the bullet-->
   <solid 
       android:color="#666666"/> //set color of bullet

    <!--set size of the bullet-->
   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

Then add this drawable in textview and set its pedding by using below properties

android:drawableStart="@drawable/bullet"
android:drawablePadding="10dp"

Ruby on Rails: Where to define global constants?

I typically have a 'lookup' model/table in my rails program and use it for the constants. It is very useful if the constants are going to be different for different environments. In addition, if you have a plan to extend them, say you want to add 'yellow' on a later date, you could simply add a new row to the lookup table and be done with it.

If you give the admin permissions to modify this table, they will not come to you for maintenance. :) DRY.

Here is how my migration code looks like:

class CreateLookups < ActiveRecord::Migration
  def change
    create_table :lookups do |t|
      t.string :group_key
      t.string :lookup_key
      t.string :lookup_value
      t.timestamps
    end
  end
end

I use seeds.rb to pre-populate it.

Lookup.find_or_create_by_group_key_and_lookup_key_and_lookup_value!(group_key: 'development_COLORS', lookup_key: 'color1', lookup_value: 'red');

How do I efficiently iterate over each entry in a Java Map?

This is the easiest way of doing it I believe...

/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();

// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);

/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
    Map.Entry pair = (Map.Entry) o;
    // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}

Javascript - Track mouse position

Here is the simplest way to track your mouse position

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

know more

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

What I can do to resolve "1 commit behind master"?

If the branch is behind master, then delete the remote branch. Then go to local branch and run :

git pull origin master --rebase

Then, again push the branch to origin:

git push -u origin <branch-name>

How to pass arguments from command line to gradle

Building on Peter N's answer, this is an example of how to add (optional) user-specified arguments to pass to Java main for a JavaExec task (since you can't set the 'args' property manually for the reason he cites.)

Add this to the task:

task(runProgram, type: JavaExec) {

  [...]

  if (project.hasProperty('myargs')) {
      args(myargs.split(','))
  }

... and run at the command line like this

% ./gradlew runProgram '-Pmyargs=-x,7,--no-kidding,/Users/rogers/tests/file.txt'

Replace all 0 values to NA

dplyr::na_if() is an option:

library(dplyr)  

df <- data_frame(col1 = c(1, 2, 3, 0),
                 col2 = c(0, 2, 3, 4),
                 col3 = c(1, 0, 3, 0),
                 col4 = c('a', 'b', 'c', 'd'))

na_if(df, 0)
# A tibble: 4 x 4
   col1  col2  col3 col4 
  <dbl> <dbl> <dbl> <chr>
1     1    NA     1 a    
2     2     2    NA b    
3     3     3     3 c    
4    NA     4    NA d

java.lang.ClassNotFoundException on working app

We have a couple of projects where this issue was logged from time to time on the Android Market. I found the following issues in the manifests:

  1. If the package name is com.test then activities names should be .ActivityName (with a leading dot), not just ActivityName.

  2. For some classes, those that appeared in the logs most often, the class name was specified as com.test.Name while it should have been .Name.

I guess many implementations of Android handle these minor issues successfully (this is why the exception never happened in testing), while others few are throwing the exception.

Regular expression to match balanced parentheses

This one also worked

re.findall(r'\(.+\)', s)

Number prime test in JavaScript

very simple

const isPrime = num => {
  for (var i = 2; i < num; i++) if (num % i == 0) return false;
  return num >= 2; 
}

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

How do I programmatically determine operating system in Java?

The following JavaFX classes have static methods to determine current OS (isWindows(),isLinux()...):

  • com.sun.javafx.PlatformUtil
  • com.sun.media.jfxmediaimpl.HostUtils
  • com.sun.javafx.util.Utils

Example:

if (PlatformUtil.isWindows()){
           ...
}

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

How to replace a character with a newline in Emacs?

inline just: C-M-S-% (if binding keys still default) than replace-string^J

How to add Active Directory user group as login in SQL Server

Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

How to pass a textbox value from view to a controller in MVC 4?

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
    {
        int _id = Convert.ToInt32(txtDelete); // put your code           
    }

This code is in my controller's cshtml

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
 {
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

./configure : /bin/sh^M : bad interpreter

Or if you want to do this with a script:

sed -i 's/\r//' filename

Resizable table columns with jQuery

So I started writing my own, just bare bones functionality for now, will be working on it next week... http://jsfiddle.net/ydTCZ/

Remove quotes from a character vector in R

There are no quotes in the return value, only in the default output from print() when you display the value. Try

> print(char[1], quote=FALSE)
[1] one

or

> cat(char[1], "\n")
one

to see the value without quotes.

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

'NOT NULL constraint failed' after adding to models.py

if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.

When does Git refresh the list of remote branches?

If you are using Eclipse,

  1. Open "Git Repositories"
  2. Find your Repository.
  3. Open up "Branches" then "Remote Tracking".

Git

They should all be in there. Right click and "checkout."

Javascript/Jquery to change class onclick?

I think you mean that you want want an onclick event that changes a class.

Here is the answer if someone visits this question and is literally looking to assign a class and it's onclick with JQUERY.

It is somewhat counter-intuitive, but if you want to change the onclick event by changing the class you need to declare the onclick event to apply to elements of a parent object.

HTML

<div id="containerid">
     Text <a class="myClass" href="#" />info</a>
     Other Text <div class="myClass">other info</div>
</div>
<div id="showhide" class="meta-info">hide info</div>

Document Ready

$(function() {
     $("#containerid").on("click",".myclass",function(e){ /*do stuff*/ }
     $("#containerid").on("click",".mynewclass",function(e){ /*do different stuff*/ }
     $("#showhide").click(function() {changeclass()}
});

Slight Tweak to Your Javascript

<script>
function changeclass() {
        $(".myClass,.myNewClass").toggleClass('myNewClass').toggleClass('myClass');
} 
</script>

If you can't reliably identify a parent object you can do something like this.

$(function() {
     $(document).on("click",".myclass",function(e){}
     $(document).on("click",".mynewclass",function(e){}
});

If you just want to hide the items you might find it simpler to use .hide() and .show().

What is a good way to handle exceptions when trying to read a file in python?

fname = 'filenotfound.txt'
try:
    f = open(fname, 'rb')
except FileNotFoundError:
    print("file {} does not exist".format(fname))

file filenotfound.txt does not exist

exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

https://docs.python.org/3/library/exceptions.html
This exception does not exist in Python 2.

Spring boot - Not a managed type

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

UIScrollView not scrolling

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.

Reading the selected value from asp:RadioButtonList using jQuery

According to me it'll be working fine...

Just try with this

   var GetValue=$('#radiobuttonListId').find(":checked").val();

The Radiobuttonlist value to be stored on GetValue(Variable).

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

In the following, user is your username.

mkdir -p /home/user/.ssh
ssh-keygen -t rsa
touch /home/user/.ssh/authorized_keys
touch /home/user/.ssh/known_hosts
chown -R user:user /home/user/.ssh
chmod 700 /home/user/.ssh
chmod 600 /home/user/.ssh/id*
chmod 644 /home/user/.ssh/id*.pub
chmod 644 /home/user/.ssh/authorized_keys
chmod 644 /home/user/.ssh/known_hosts

Where are Docker images stored on the host machine?

For "Docker Desktop", click on docker system tray icon and click "Settings". enter image description here

On the Advanced tab, you can see the disk image location.

enter image description here

Running multiple commands in one line in shell

Try this..

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple