Programs & Examples On #Nokia wrt

Web Run time (WRT) is a portable application framework that allows creating widgets on the S60 Platform; it is an extension to the S60 WebKit based browser that allows launching multiple browser instances as separate JavaScript applications.

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

Programmatically generate video or animated GIF in Python?

It's not a python library, but mencoder can do that: Encoding from multiple input image files. You can execute mencoder from python like this:

import os

os.system("mencoder ...")

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

Difference between "process.stdout.write" and "console.log" in node.js?

I've just noticed something while researching this after getting help with https.request for post method. Thought I share some input to help understand.

process.stdout.write doesn't add a new line while console.log does, like others had mentioned. But there's also this which is easier to explain with examples.

var req = https.request(options, (res) => {
    res.on('data', (d) => {
        process.stdout.write(d);
        console.log(d)
    });
});

process.stdout.write(d); will print the data properly without a new line. However console.log(d) will print a new line but the data won't show correctly, giving this <Buffer 12 34 56... for example.

To make console.log(d) show the information correctly, I would have to do this.

var req = https.request(options, (res) => {
    var dataQueue = "";    
    res.on("data", function (d) {
        dataQueue += d;
    });
    res.on("end", function () {
        console.log(dataQueue);
    });
});

So basically:

  • process.stdout.write continuously prints the information as the data being retrieved and doesn't add a new line.

  • console.log prints the information what was obtained at the point of retrieval and adds a new line.

That's the best way I can explain it.

How can I check if a single character appears in a string?

You can use 2 methods from the String class.

  • String.contains() which checks if the string contains a specified sequence of char values
  • String.indexOf() which returns the index within the string of the first occurence of the specified character or substring or returns -1 if the character is not found (there are 4 variations of this method)

Method 1:

String myString = "foobar";
if (myString.contains("x") {
    // Do something.
}

Method 2:

String myString = "foobar";
if (myString.indexOf("x") >= 0 {
    // Do something.
}

Links by: Zach Scrivena

Global variables in c#.net

/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";

/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;

/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
    return _globalValue;
}
set
{
    _globalValue = value;
}
}

/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

How to delete a module in Android Studio

In android-studio version 2. just go

Right Click on Project-->Open Module Option-->Click Your Module --> click sign done then press ok button.

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

laravel Eloquent ORM delete() method

Before delete , there are several methods in laravel.

User::find(1) and User::first() return an instance.

User::where('id',1)->get and User::all() return a collection of instance.

call delete on an model instance will returns true/false

$user=User::find(1);
$user->delete(); //returns true/false

call delete on a collection of instance will returns a number which represents the number of the records had been deleted

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

What is the main difference between Inheritance and Polymorphism?

Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).

E.g.

// This assignment is possible because B extends A
A a = new B();
// polymorphic call/ access
a.foo();

-> Though the static/ declaration type of a is A, the actual dynamic/ runtime type is B and thus a.foo() will execute foo as defined in B not in A.

Can I recover a branch after its deletion in Git?

Adding to tfe answer: there is also the git-resurrect.sh script in the contrib/ area of the Git sources (in git.git repository), which might help you.

git-resurrect <name> attempts to find traces of a branch tip called <name>, and tries to resurrect it. Currently, the reflog is searched for checkout messages, and with -r also merge messages. With -m and -t, the history of all refs is scanned for Merge <name> into other/Merge <other> into <name> (respectively) commit subjects, which is rather slow but allows you to resurrect other people's topic branches.

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

In iOS SDK When your API call time-outs, you get status 0 for that.

How to push both value and key into PHP array

I wonder why the simplest method hasn't been posted yet:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];

De-obfuscate Javascript code to make it readable again

Here it is:

function call_func(input) {
    var evaled = eval('(' + input + ')');
    var newDiv = document.createElement('div');
    var id = evaled.id;
    var name = evaled.Student_name;
    var dob = evaled.student_dob;
    var html = '<b>ID:</b>';
    html += '<a href="/learningyii/index.php?r=student/view&amp; id=' + id + '">' + id + '</a>';
    html += '<br/>';
    html += '<b>Student Name:</b>';
    html += name;
    html += '<br/>';
    html += '<b>Student DOB:</b>';
    html += dob;
    html += '<br/>';
    newDiv.innerHTML = html;
    newDiv.setAttribute('class', 'view');
    $('#StudentGridViewId').find('.items').prepend(newDiv);
};

Kill a postgresql session/connection

MacOS, if postgresql was installed with brew:

brew services restart postgresql

Source: Kill a postgresql session/connection

Shorten string without cutting words in JavaScript

With boundary conditions like empty sentence and very long first word. Also, it uses no language specific string api/library.

_x000D_
_x000D_
function solution(message, k) {_x000D_
    if(!message){_x000D_
        return ""; //when message is empty_x000D_
    }_x000D_
    const messageWords = message.split(" ");_x000D_
    let result = messageWords[0];_x000D_
    if(result.length>k){_x000D_
        return ""; //when length of first word itself is greater that k_x000D_
    }_x000D_
    for(let i = 1; i<messageWords.length; i++){_x000D_
        let next = result + " " + messageWords[i];_x000D_
_x000D_
        if(next.length<=k){_x000D_
            result = next;_x000D_
        }else{_x000D_
            break;_x000D_
        }_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
console.log(solution("this is a long string i cant display", 10));
_x000D_
_x000D_
_x000D_

Why does "npm install" rewrite package-lock.json?

Use the newly introduced

npm ci

npm ci promises the most benefit to large teams. Giving developers the ability to “sign off” on a package lock promotes more efficient collaboration across large teams, and the ability to install exactly what is in a lockfile has the potential to save tens if not hundreds of developer hours a month, freeing teams up to spend more time building and shipping amazing things.

Introducing npm ci for faster, more reliable builds

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Leaflet changing Marker color

In R, use the addAwesomeMarkers() function. Sample code producing red marker:

leaflet() %>%
addTiles() %>%
addAwesomeMarkers(lng = -77.03654, lat = 38.8973, icon = awesomeIcons(icon = 'ion-ionic', library = 'ion', markerColor = 'red'))

Link for ion icons: http://ionicons.com/

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

How to check for null in Twig?

You can also use one line to do that:

{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}

How do I undo 'git add' before commit?

In Sourcetree you can do this easily via the GUI. You can check which command Sourcetree uses to unstage a file.

I created a new file and added it to Git. Then I unstaged it using the Sourcetree GUI. This is the result:

Unstaging files [08/12/15 10:43] git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree reset -q -- path/to/file/filename.java

Sourcetree uses reset to unstage new files.

File loading by getClass().getResource()

getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.

When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:

  • .java files are compiled into .class files that go the the bin directory (by default)
  • other files are copied to the bin directory (respecting the package/folder hirearchy)

When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource() or getResourceAsStream().

If it doesn't work from the command line, it's thus because the file is not in the classpath.

Note that you should NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));

to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")

And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")

will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")

will load a Test.properties file located in the package com.foo.bar.

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

Display label text with line breaks in c#

You may append HTML <br /> in between your lines. Something like:

MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";

With StringBuilder you can try:

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");

View content of H2 or HSQLDB in-memory database

This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:

jdbcTemplate.getDataSource().getConnection();

So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:

org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());

Eclipse Expressions View

H2 Console

Convert string to float?

Using Float.parseFloat()?

class Test {
    public static void main(String[] args) {
        String s = "3.14";
        float f = Float.parseFloat(s);
        System.out.println(f);
    }
}

Tick symbol in HTML/XHTML

I run into the same problem and none of the suggestions worked (Firefox on Windows XP).

So I found a possible workaround using image data to display a little checkmark:

span:before {
    content:url("data:image/gif;base64,R0lGODlhCgAKAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAKAAoAAAISlG8AeMq5nnsiSlsjzmpzmj0FADs=");
}

Of course you can create your own checkmark image and use a converter to add it as data:image/gif. Hope this helps.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

This error message

error: (-215)size.width>0 && size.height>0 in function imshow

simply means that imshow() is not getting video frame from input-device. You can try using

cap = cv2.VideoCapture(1) 

instead of

cap = cv2.VideoCapture(0) 

& see if the problem still persists.

Capture screenshot of active window?

Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
    using(Graphics g = Graphics.FromImage(bitmap))
    {
         g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
    }
    bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

for capturing current window use

 Rectangle bounds = this.Bounds;
 using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
 {
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
    }
    bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
 }

Pandas: convert dtype 'object' to int

It's simple

pd.factorize(df.purchase)[0]

Example:

labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
labels
# array([0, 0, 1, 2, 0])
uniques
# array(['b', 'a', 'c'], dtype=object)

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How do I fill arrays in Java?

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};

How do I use sudo to redirect output to a location I don't have permission to write to?

How about writing a script?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

Then use sudo to run the script:

sudo ./myscript

How to read specific lines from a file (by line number)?

If the file to read is big, and you don't want to read the whole file in memory at once:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()

Note that i == n-1 for the nth line.


In Python 2.6 or later:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break

Apply CSS style attribute dynamically in Angular JS

The easiest way is to call a function for the style, and have the function return the correct style.

<div style="{{functionThatReturnsStyle()}}"></div>

And in your controller:

$scope.functionThatReturnsStyle = function() {
  var style1 = "width: 300px";
  var style2 = "width: 200px";
  if(condition1)
     return style1;
  if(condition2)
     return style2;
}

Execute raw SQL using Doctrine 2

I got it to work by doing this, assuming you are using PDO.

//Place query here, let's say you want all the users that have blue as their favorite color
$sql = "SELECT name FROM user WHERE favorite_color = :color";

//set parameters 
//you may set as many parameters as you have on your query
$params['color'] = blue;


//create the prepared statement, by getting the doctrine connection
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt->execute($params);
//I used FETCH_COLUMN because I only needed one Column.
return $stmt->fetchAll(PDO::FETCH_COLUMN);

You can change the FETCH_TYPE to suit your needs.

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

rand() between 0 and 1

In my case (I'm using VS 2017) works fine the following simple code:

#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(NULL));

    for (int i = 1000; i > 0; i--) //try it thousand times
    {
        int randnum = (double)rand() / ((double)RAND_MAX + 1);
        std::cout << " rnum: " << rand()%2 ;
    }
} 

How do I give text or an image a transparent background using CSS?

As per my point of view, the best way to use a background color with opacity is as below. If we use this, then we will not lose opacity for the other elements, like test color, border, etc.

background-color: rgba(71, 158, 0, 0.8);

Use background color with opacity

background-color: rgba(R, G, B, Opacity);

Enter image description here

Programmatically get height of navigation bar

The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.

I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.

For example, on one UIView, I have, from top to bottom:

UIView – both springs set (default case) and no struts

UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.

UILabel and UIImage next vertically – top strut set, flexible everywhere else

Just to complete the picture for the few that have a UIWebView:

UIWebView - Struts: top, left, right Springs: both

UIButton – nothing set, i.e., flexible everywhere

Although my light bulb is dim, there appears to be hope.

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

How to read a line from the console in C?

You might need to use a character by character (getc()) loop to ensure you have no buffer overflows and don't truncate the input.

Wait for a process to finish

On a system like OSX you might not have pgrep so you can try this appraoch, when looking for processes by name:

while ps axg | grep process_name$ > /dev/null; do sleep 1; done

The $ symbol at the end of the process name ensures that grep matches only process_name to the end of line in the ps output and not itself.

What does it mean to bind a multicast (UDP) socket?

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application. (Same holds true for TCP sockets).

When you bind to "0.0.0.0" (INADDR_ANY), you are basically telling the TCP/IP layer to use all available adapters for listening and to choose the best adapter for sending. This is standard practice for most socket code. The only time you wouldn't specify 0 for the IP address is when you want to send/receive on a specific network adapter.

Similarly if you specify a port value of 0 during bind, the OS will assign a randomly available port number for that socket. So I would expect for UDP multicast, you bind to INADDR_ANY on a specific port number where multicast traffic is expected to be sent to.

The "join multicast group" operation (IP_ADD_MEMBERSHIP) is needed because it basically tells your network adapter to listen not only for ethernet frames where the destination MAC address is your own, it also tells the ethernet adapter (NIC) to listen for IP multicast traffic as well for the corresponding multicast ethernet address. Each multicast IP maps to a multicast ethernet address. When you use a socket to send to a specific multicast IP, the destination MAC address on the ethernet frame is set to the corresponding multicast MAC address for the multicast IP. When you join a multicast group, you are configuring the NIC to listen for traffic sent to that same MAC address (in addition to its own).

Without the hardware support, multicast wouldn't be any more efficient than plain broadcast IP messages. The join operation also tells your router/gateway to forward multicast traffic from other networks. (Anyone remember MBONE?)

If you join a multicast group, all the multicast traffic for all ports on that IP address will be received by the NIC. Only the traffic destined for your binded listening port will get passed up the TCP/IP stack to your app. In regards to why ports are specified during a multicast subscription - it's because multicast IP is just that - IP only. "ports" are a property of the upper protocols (UDP and TCP).

You can read more about how multicast IP addresses map to multicast ethernet addresses at various sites. The Wikipedia article is about as good as it gets:

The IANA owns the OUI MAC address 01:00:5e, therefore multicast packets are delivered by using the Ethernet MAC address range 01:00:5e:00:00:00 - 01:00:5e:7f:ff:ff. This is 23 bits of available address space. The first octet (01) includes the broadcast/multicast bit. The lower 23 bits of the 28-bit multicast IP address are mapped into the 23 bits of available Ethernet address space.

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

Pipenv: Command Not Found

If you've done a user installation, you'll need to add the right folder to your PATH variable.

PYTHON_BIN_PATH="$(python3 -m site --user-base)/bin"
PATH="$PATH:$PYTHON_BIN_PATH"

See pipenv's installation instructions

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Expanding on your comment to SquareCog's reply, you could do:

INSERT INTO X VALUES(Y,Z)    WHERE Y  NOT IN (SELECT Y FROM X)
INSERT INTO X2 VALUES(Y2,Z2) WHERE Y2 NOT IN (SELECT Y FROM X2)
INSERT INTO X3 VALUES(Y3,Z3) WHERE Y3 NOT IN (SELECT Y FROM X3)

Here, I assume that column Y is present in all three tables. Note that performance will be poor if the tables are not indexed on Y.

Oh yeah, Y has a unique constraint on it--so they're indexed, and this should perform optimally.

Query grants for a table in postgres

This query will list all of the tables in all of the databases and schemas (uncomment the line(s) in the WHERE clause to filter for specific databases, schemas, or tables), with the privileges shown in order so that it's easy to see if a specific privilege is granted or not:

SELECT grantee
      ,table_catalog
      ,table_schema
      ,table_name
      ,string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants 
WHERE grantee != 'postgres' 
--  and table_catalog = 'somedatabase' /* uncomment line to filter database */
--  and table_schema  = 'someschema'   /* uncomment line to filter schema  */
--  and table_name    = 'sometable'    /* uncomment line to filter table  */
GROUP BY 1, 2, 3, 4;

Sample output:

grantee |table_catalog   |table_schema  |table_name     |privileges     |
--------|----------------|--------------|---------------|---------------|
PUBLIC  |adventure_works |pg_catalog    |pg_sequence    |SELECT         |
PUBLIC  |adventure_works |pg_catalog    |pg_sequences   |SELECT         |
PUBLIC  |adventure_works |pg_catalog    |pg_settings    |SELECT, UPDATE |
...

UnicodeDecodeError when reading CSV file in Pandas with Python

This answer seems to be the catch-all for CSV encoding issues. If you are getting a strange encoding problem with your header like this:

>>> f = open(filename,"r")
>>> reader = DictReader(f)
>>> next(reader)
OrderedDict([('\ufeffid', '1'), ... ])

Then you have a byte order mark (BOM) character at the beginning of your CSV file. This answer addresses the issue:

Python read csv - BOM embedded into the first key

The solution is to load the CSV with encoding="utf-8-sig":

>>> f = open(filename,"r", encoding="utf-8-sig")
>>> reader = DictReader(f)
>>> next(reader)
OrderedDict([('id', '1'), ... ])

Hopefully this helps someone.

How to handle calendar TimeZones using Java?

Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:

// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
    currentDt.get(Calendar.ERA), 
    currentDt.get(Calendar.YEAR), 
    currentDt.get(Calendar.MONTH), 
    currentDt.get(Calendar.DAY_OF_MONTH), 
    currentDt.get(Calendar.DAY_OF_WEEK), 
    currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
    + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
    .format(issueDate.getTime()));

The code's output is: (User entered 5/1/2008 6:12PM (EST)

Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)

How do I find the CPU and RAM usage using PowerShell?

You can also use the Get-Counter cmdlet (PowerShell 2.0):

Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'

To get a list of memory counters:

Get-Counter -ListSet *memory* | Select-Object -ExpandProperty  Counter

Are SSL certificates bound to the servers ip address?

The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.

Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Quote (read [here][1])-

When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.

So, something like this should work-

report := CAST(report_clob AS VARCHAR2(100));

Or better yet use it as CAST(report_clob AS VARCHAR2(100)) where ever you are trying to use the BLOB as VARCHAR [1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

How can I check if an ip is in a network in Python?

Thank you for your script!
I have work quite a long on it to make everything working... So I'm sharing it here

  • Using netaddr Class is 10 times slower than using binary conversion, so if you'd like to use it on a big list of IP, you should consider not using netaddr class
  • makeMask function is not working! Only working for /8,/16,/24
    Ex:

    bits = "21" ; socket.inet_ntoa(struct.pack('=L',(2L << int(bits)-1) - 1))
    '255.255.31.0' whereas it should be 255.255.248.0

    So I have used another function calcDottedNetmask(mask) from http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/
    Ex:


#!/usr/bin/python
>>> calcDottedNetmask(21)
>>> '255.255.248.0'
  • Another problem is the process of matching if an IP belongs to a network! Basic Operation should be to compare (ipaddr & netmask) and (network & netmask).
    Ex: for the time being, the function is wrong

#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
>>>True which is completely WRONG!!

So my new addressInNetwork function looks-like:


#!/usr/bin/python
import socket,struct
def addressInNetwork(ip,net):
    '''This function allows you to check if on IP belogs to a Network'''
    ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(bits)))[0]
    network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)

def calcDottedNetmask(mask):
    bits = 0
    for i in xrange(32-int(mask),32):
        bits |= (1 > 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))


And now, answer is right!!


#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
False

I hope that it will help other people, saving time for them!

How to enable external request in IIS Express?

I remember running into the same problems while trying this workflow a few months ago.

Which is why I wrote a simple proxy utility specifically for this kind of scenario: https://github.com/icflorescu/iisexpress-proxy.

Using the IIS Express Proxy, it all becomes quite simple – no need to “netsh http add urlacl url=vaidesg:8080/ user=everyone” or to mess up with your “applicationhost.config”.

Just issue this in command prompt:

iisexpress-proxy 8080 to 3000

…and then you can point your remote devices to http://vaidesg:3000.

Most of the times simpler IS better.

Custom domain for GitHub project pages

Overview

The documentation is a little confusing when it comes to project pages, as opposed to user pages. It feels like you should have to do more, but actually the process is very easy.

It involves:

  1. Setting up 2 static A records for the naked (no www) domain.
  2. Creating one CNAME record for www which will point to a GitHub URL. This will handle www redirection for you.
  3. Creating a file called CNAME (capitalised) in your project root on the gh-pages branch. This will tell Github what URL to respond to.
  4. Wait for everything to propagate.

What you will get

Your content will be served from a URL of the form http://nicholasjohnson.com.

Visiting http://www.nicholasjohnson.com will return a 301 redirect to the naked domain.

The path will be respected by the redirect, so traffic to http://www.nicholasjohnson.com/angular will be redirected to http://nicholasjohnson.com/angular.

You can have one project page per repository, so if your repos are open you can have as many as you like.

Here's the process:

1. Create A records

For the A records, point @ to the following ip addresses:

@: 185.199.108.153
@: 185.199.109.153
@: 185.199.110.153
@: 185.199.111.153

These are the static Github IP addresses from which your content will be served.

2. Create a CNAME Record

For the CNAME record, point www to yourusername.github.io. Note the trailing full stop. Note also, this is the username, not the project name. You don't need to specify the project name yet. Github will use the CNAME file to determine which project to serve content from.

e.g.

www: forwardadvance.github.io.

The purpose of the CNAME is to redirect all www subdomain traffic to a GitHub page which will 301 redirect to the naked domain.

Here's a screenshot of the configuration I use for my own site http://nicholasjohnson.com:

A and CNAME records required for Github Static Pages

3. Create a CNAME file

Add a file called CNAME to your project root in the gh-pages branch. This should contain the domain you want to serve. Make sure you commit and push.

e.g.

nicholasjohnson.com

This file tells GitHub to use this repo to handle traffic to this domain.

4. Wait

Now wait 5 minutes, your project page should now be live.

How to display loading message when an iFrame is loading?

<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo - IFRAME Loader</title>
<style>
#frameWrap {
    position:relative;
    height: 360px;
    width: 640px;
    border: 1px solid #777777;
    background:#f0f0f0;
    box-shadow:0px 0px 10px #777777;
}

#iframe1 {
    height: 360px;
    width: 640px;
    margin:0;
    padding:0;
    border:0;
}

#loader1 {
    position:absolute;
    left:40%;
    top:35%;
    border-radius:20px;
    padding:25px;
    border:1px solid #777777;
    background:#ffffff;
    box-shadow:0px 0px 10px #777777;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>

<div id="frameWrap">
<img id="loader1" src="loading.gif" width="36" height="36" alt="loading gif"/>
<iframe id="iframe1" src="https://bots.actcorp.in/ACTAppChat/[email protected]&authToken=69d1afc8d06fb97bdb5a9275edbc53b375c3c7662c88b78239ba0cd8a940d59e" ></iframe>
</div>
<script>
    $(document).ready(function () {
        $('#iframe1').on('load', function () {
            $('#loader1').hide();
        });
    });
</script>

</body>
</html>

Why check both isset() and !empty()

The accepted answer is not correct.

isset() is NOT equivalent to !empty().

You will create some rather unpleasant and hard to debug bugs if you go down this route. e.g. try running this code:

<?php

$s = '';

print "isset: '" . isset($s) . "'. ";
print "!empty: '" . !empty($s) . "'";

?>

https://3v4l.org/J4nBb

Moment Js UTC to Local Time

Here is what I do using Intl api:

let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney

this will return a time zone name. Pass this parameter to the following function to get the time

let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});

let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});

you can also format the time with moment like this:

moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');

How to create a session using JavaScript?

You can use sessionStorage it is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

What is the difference between Python's list methods append and extend?

You can use "+" for returning extend, instead of extending in place.

l1=range(10)

l1+[11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

l2=range(10,1,-1)

l1+l2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]

Similarly += for in place behavior, but with slight differences from append & extend. One of the biggest differences of += from append and extend is when it is used in function scopes, see this blog post.

Get the records of last month in SQL server

I don't think the accepted solution is very index friendly I use the following lines instead

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date <= dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

Or simply (this is the best).

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date < SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);

Some help

-- Get the first of last month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
-- Get the first of current month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
--Get the last of last month except the last 3milli seconds. (3miliseconds being used as SQL express otherwise round it up to the full second (SERIUSLY MS)
SELECT dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

Get access to parent control from user control - C#

A generic way to get a parent of a control that I have used is:

public static T GetParentOfType<T>(this Control control)
{
    const int loopLimit = 100; // could have outside method
    var current = control;
    var i = 0;

    do
    {
        current = current.Parent;

        if (current == null) throw new Exception("Could not find parent of specified type");
        if (i++ > loopLimit) throw new Exception("Exceeded loop limit");

    } while (current.GetType() != typeof(T));

    return (T)Convert.ChangeType(current, typeof(T));
}

It needs a bit of work (e.g. returning null if not found or error) ... but hopefully could help someone.

Usage:

var parent = currentControl.GetParentOfType<TypeWanted>();

Enjoy!

Pandas read_csv from url

To Import Data through URL in pandas just apply the simple below code it works actually better.

import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()

If you are having issues with a raw data then just put 'r' before URL

import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()

Is there a way to represent a directory tree in a Github README.md?

Here is a useful git alias that works for me.

git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\//   |/g" -e "s/|\([^ ]\)/|-- \1/"'

Here is the output of git tree

jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
   |-- main
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- AbstractFile.java
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Main.java
   |   |   |   |   |   |   |-- Numeral.java
   |   |   |   |   |   |   |-- RomanNumberInputFile.java
   |   |   |   |   |   |   |-- RomanNumeralToDecimalEvaluator.java
   |-- test
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- InterpretSteps.java
   |   |   |   |   |   |   |-- RunCukesTest.java
   |   |-- resources
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Interpret.feature
   |   |   |-- sample-input.txt

The comparable tree command

jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
+-- pom.xml
+-- src
¦   +-- main
¦   ¦   +-- java
¦   ¦       +-- com
¦   ¦           +-- foxguardsolutions
¦   ¦               +-- jonavon
¦   ¦                   +-- AbstractFile.java
¦   ¦                   +-- roman
¦   ¦                       +-- Main.java
¦   ¦                       +-- Numeral.java
¦   ¦                       +-- RomanNumberInputFile.java
¦   ¦                       +-- RomanNumeralToDecimalEvaluator.java
¦   +-- test
¦       +-- java
¦       ¦   +-- com
¦       ¦       +-- foxguardsolutions
¦       ¦           +-- jonavon
¦       ¦               +-- roman
¦       ¦                   +-- InterpretSteps.java
¦       ¦                   +-- RunCukesTest.java
¦       +-- resources
¦           +-- com
¦           ¦   +-- foxguardsolutions
¦           ¦       +-- jonavon
¦           ¦           +-- roman
¦           ¦               +-- Interpret.feature
¦           +-- sample-input.txt
+-- target
    +-- classes
    ¦   +-- com
    ¦       +-- foxguardsolutions
    ¦           +-- jonavon
    ¦               +-- AbstractFile.class
    ¦               +-- roman
    ¦                   +-- Main.class
    ¦                   +-- Numeral.class
    ¦                   +-- RomanNumberInputFile.class
    ¦                   +-- RomanNumeralToDecimalEvaluator.class
    +-- generated-sources
    ¦   +-- annotations
    +-- maven-status
        +-- maven-compiler-plugin
            +-- compile
                +-- default-compile
                    +-- createdFiles.lst
                    +-- inputFiles.lst

30 directories, 17 files

Clearly tree has better output, but I would like it to use my .gitignore file. So that my compiled content doesn't show

Unit Testing: DateTime.Now

These are all good answers, this is what I did on a different project:

Usage:

Get Today's REAL date Time

var today = SystemTime.Now().Date;

Instead of using DateTime.Now, you need to use SystemTime.Now()... It's not hard change but this solution might not be ideal for all projects.

Time Traveling (Lets go 5 years in the future)

SystemTime.SetDateTime(today.AddYears(5));

Get Our Fake "today" (will be 5 years from 'today')

var fakeToday = SystemTime.Now().Date;

Reset the date

SystemTime.ResetDateTime();

/// <summary>
/// Used for getting DateTime.Now(), time is changeable for unit testing
/// </summary>
public static class SystemTime
{
    /// <summary> Normally this is a pass-through to DateTime.Now, but it can be overridden with SetDateTime( .. ) for testing or debugging.
    /// </summary>
    public static Func<DateTime> Now = () => DateTime.Now;

    /// <summary> Set time to return when SystemTime.Now() is called.
    /// </summary>
    public static void SetDateTime(DateTime dateTimeNow)
    {
        Now = () =>  dateTimeNow;
    }

    /// <summary> Resets SystemTime.Now() to return DateTime.Now.
    /// </summary>
    public static void ResetDateTime()
    {
        Now = () => DateTime.Now;
    }
}

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

Invalid JSON from the server should always be an expected use case. A million things can go wrong during transmission. Gson is a bit tricky, because its error output will give you one problem, and the actual exception you catch will be of a different type.

With all that in mind, the proper fix on the client side is

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  //...

If you want to know why the JSON you received from the server is wrong, you can look inside your catch block at the exception. But even if it is your problem, it's not the client's responsibility to fix JSON it is receiving from the internet.

Either way, it is the client's responsibility to decide what to do when it gets bad JSON. Two possibilities are rejecting the JSON and doing nothing, and trying again.

If you are going to try again, I highly recommend setting a flag inside the try / catch block and then responding to that flag outside the try / catch block. Nested try / catch is likely how Gson got us into this mess with our stack trace and exceptions not matching up.

In other words, even though I'll admit it doesn't look very elegant, I would recommend

boolean failed = false;

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  failed = true;
  //...
}

if (failed)
{
  //...

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<connectionStrings>      
<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

Find Number of CPUs and Cores per CPU using Command Prompt

Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

How to scroll the page when a modal dialog is longer than the screen?

Here.. Works perfectly for me

.modal-body { 
    max-height:500px; 
    overflow-y:auto;
}

Get and Set a Single Cookie with Node.js HTTP Server

First one needs to create cookie (I have wrapped token inside cookie as an example) and then set it in response.To use the cookie in following way install cookieParser

app.use(cookieParser());

The browser will have it saved in its 'Resource' tab and will be used for every request thereafter taking the initial URL as base

var token = student.generateToken('authentication');
        res.cookie('token', token, {
            expires: new Date(Date.now() + 9999999),
            httpOnly: false
        }).status(200).send();

To get cookie from a request on the server side is easy too.You have to extract the cookie from request by calling 'cookie' property of the request object.

var token = req.cookies.token; // Retrieving Token stored in cookies

How can I execute a python script from an html button?

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do :-)

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it ... A chmod, and/or a chown may be necessary.

WPF checkbox binding

Should be easier than that. Just use:

<Checkbox IsChecked="{Binding Path=myVar, UpdateSourceTrigger=PropertyChanged}" />

How to change Elasticsearch max memory size

In elasticsearch path home dir i.e. typically /usr/share/elasticsearch, There is a config file bin/elasticsearch.in.sh. Edit parameter ES_MIN_MEM, ES_MAX_MEM in this file to change -Xms2g, -Xmx4g respectively. And Please make sure you have restarted the node after this config change.

Composer Warning: openssl extension is missing. How to enable in WAMP

opened wamp/bin/apache/apache2.4.4/bin/php config.. wamp/bin/php/php5.4.16/php conf settings, php-ini production, php-ini dev, phpForApache find extension=php_openssl.dll and uncomment by removing ;

How to change bower's default components folder?

Hi i am same problem and resolve this ways.

windows user and vs cant'create .bowerrc file.

in cmd go any folder

install any packages which is contains .bowerrc file forexample

bower install angular-local-storage

this plugin contains .bowerrc file. copy that and go to your project and paste this file.

and in visual studio - solution explorer - show all files and include project seen .bowerrc file

i resolve this ways :)

Strings as Primary Keys in SQL Database

Inserts to a table having a clustered index where the insertion occurs in the middle of the sequence DOES NOT cause the index to be rewritten. It does not cause the pages comprising the data to be rewritten. If there is room on the page where the row will go, then it is placed in that page. The single page will be reformatted to place the row in the right place in the page. When the page is full, a page split will happen, with half of the rows on the page going to one page, and half going on the other. The pages are then relinked into the linked list of pages that comprise a tables data that has the clustered index. At most, you will end up writing 2 pages of database.

How to emulate GPS location in the Android Emulator?

I use eclipse plug DDMS function to send GPS. enter image description here

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

Responsive table handling in Twitter Bootstrap

One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link

How to get substring in C

char originalString[] = "THESTRINGHASNOSPACES";

    char aux[5];
    int j=0;
    for(int i=0;i<strlen(originalString);i++){
        aux[j] = originalString[i];
        if(j==3){
            aux[j+1]='\0'; 
            printf("%s\n",aux);
            j=0;
        }else{
            j++;
        }
    }

How can I use random numbers in groovy?

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Freely convert between List<T> and IEnumerable<T>

A List<T> is an IEnumerable<T>, so actually, there's no need to 'convert' a List<T> to an IEnumerable<T>. Since a List<T> is an IEnumerable<T>, you can simply assign a List<T> to a variable of type IEnumerable<T>.

The other way around, not every IEnumerable<T> is a List<T> offcourse, so then you'll have to call the ToList() member method of the IEnumerable<T>.

How can I concatenate two arrays in Java?

I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):

private static <T> T[] concatOrReturnSame(T[] a, T[] b) {
    final int alen = a.length;
    final int blen = b.length;
    if (alen == 0) {
        return b;
    }
    if (blen == 0) {
        return a;
    }
    final T[] result = (T[]) java.lang.reflect.Array.
            newInstance(a.getClass().getComponentType(), alen + blen);
    System.arraycopy(a, 0, result, 0, alen);
    System.arraycopy(b, 0, result, alen, blen);
    return result;
}

Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

Replace \n with actual new line in Sublime Text

Fool proof method (no RegEx and Ctrl+Enter didn't work for me as it was just jumping to next Find):

First, select an occurrence of \n and hit Ctrl+H (brings up the Replace... dialogue, also accessible through Find -> Replace... menu). This populates the Find what field.

Go to the end of any line of your file (press End if your keyboard has it) and select the end of line by holding down Shift and pressing ? (right arrow) EXACTLY once. Then copy-paste this into the Replace with field.

(the animation is for finding true new lines; works the same for replacing them)

enter image description here

error 1265. Data truncated for column when trying to load data from txt file

I have met this problem with a column that has ENUM values('0','1').
When I was trying to save a new record, I was assigning value 0 for the ENUM variable.

For the solution: I have changed ENUM variable value from 0 to 1, and 1 to 2.

How to coerce a list object to type 'double'

There are problems with some data. Consider:

as.double(as.character("2.e")) # This results in 2

Another solution:

get_numbers <- function(X) {
    X[toupper(X) != tolower(X)] <- NA
    return(as.double(as.character(X)))
}

Why do we have to specify FromBody and FromUri?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.

There is a lot more information on the web if you google "web api parameter binding".

How to get a password from a shell script without echoing

One liner:

read -s -p "Password: " password

Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.

For more info and options, in bash, type "help read".

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
  ...
  -p prompt output the string PROMPT without a trailing newline before
            attempting to read
  ...
  -s                do not echo input coming from a terminal

How to get dictionary values as a generic list

Another variation you could also use

MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();

Is this how you define a function in jQuery?

The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.

  $(document).ready(function(){
    $.myFunction = function(){ 
      alert('You have successfully defined the function!'); 
    }
    $(".btn").click(function(){
      $.myFunction();
    });
  });

You can see an example here: How to define a function in jQuery?

nginx error connect to php5-fpm.sock failed (13: Permission denied)

@Xander's solution works, but does not persist after a reboot.

I found that I had to change listen.mode to 0660 in /etc/php5/fpm/pool.d/www.conf.

Sample from www.conf:

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0660
;listen.owner = www-data
;listen.group = www-data
;listen.mode = 0660

Edit: Per @Chris Burgess, I've changed this to the more secure method.

I removed the comment for listen.mode, .group and .owner:

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

/var/run Only holds information about the running system since last boot, e.g., currently logged-in users and running daemons. (http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard#Directory_structure).

Side note:

My php5-fpm -v Reports: PHP 5.4.28-1+deb.sury.org~precise+1. The issue did happen after a recent update as well.

How to calculate the IP range when the IP address and the netmask is given?

I'll just post the code:

IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 1 });
int bits = 25;

uint mask = ~(uint.MaxValue >> bits);

// Convert the IP address to bytes.
byte[] ipBytes = ip.GetAddressBytes();

// BitConverter gives bytes in opposite order to GetAddressBytes().
byte[] maskBytes = BitConverter.GetBytes(mask).Reverse().ToArray();

byte[] startIPBytes = new byte[ipBytes.Length];
byte[] endIPBytes = new byte[ipBytes.Length];

// Calculate the bytes of the start and end IP addresses.
for (int i = 0; i < ipBytes.Length; i++)
{
    startIPBytes[i] = (byte)(ipBytes[i] & maskBytes[i]);
    endIPBytes[i] = (byte)(ipBytes[i] | ~maskBytes[i]);
}

// Convert the bytes to IP addresses.
IPAddress startIP = new IPAddress(startIPBytes);
IPAddress endIP = new IPAddress(endIPBytes);

How to use ESLint with Jest

You can also set the test env in your test file as follows:

/* eslint-env jest */

describe(() => {
  /* ... */
})

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How to increase the clickable area of a <a> tag button?

If you're using HTML 5, i.e. the doctype

<!doctype html>

then you can just use block-level links.

<a href="google.com">
  <div class="hello">
    ..
  </div>
</a>

Delete all data in SQL Server database

Below a script that I used to remove all data from an SQL Server database

------------------------------------------------------------
/* Use database */ 
-------------------------------------------------------------

use somedatabase;

GO

------------------------------------------------------------------
/* Script to delete an repopulate the base [init database] */
------------------------------------------------------------------

-------------------------------------------------------------
/* Procedure delete all constraints */ 
-------------------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllConstraints
GO

CREATE PROCEDURE sp_DeleteAllConstraints
AS
    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
GO

-----------------------------------------------------
/* Procedure delete all data from the database */ 
-----------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllData' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllData
GO

CREATE PROCEDURE sp_DeleteAllData
AS
    EXEC sp_MSForEachTable 'DELETE FROM ?'
GO

-----------------------------------------------
/* Procedure enable all constraints */ 
-----------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_EnableAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_EnableAllConstraints
GO
-- ....
-- ....
-- ....

What is the Ruby <=> (spaceship) operator?

It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.

Is there a Google Sheets formula to put the name of the sheet into a cell?

You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:

Option 1: Force the function to run.

A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.

You can use the below script to create a custom function which will retrieve the name:

function mySheetName() {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  return key;
}

and in the cell place the following:

=mySheetName(A1:Z)

Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.

Option 2: Use the OnChange Event

While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.

The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:

function setSheetName(e) {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}

Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.

Inserting NOW() into Database with CodeIgniter's Active Record

$this->db->query("update table_name set ts = now() where 1=1") also works for current time stamp!

Cannot find module '@angular/compiler'

Try this

  1. npm uninstall angular-cli
  2. npm install @angular/cli --save-dev

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

How to override a JavaScript function

You can do it like this:

alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'

Check out a working example here: http://jsfiddle.net/LtjzW/1/

How to use `subprocess` command with pipes

command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

CSS Child vs Descendant selectors

Just think of what the words "child" and "descendant" mean in English:

  • My daughter is both my child and my descendant
  • My granddaughter is not my child, but she is my descendant.

Why am I getting string does not name a type Error?

Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

The namespace in game.cpp is after the header is included.

.NET - Get protocol, host, and port

Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named Uri.GetLeftPart() method.

Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string output = url.GetLeftPart(UriPartial.Authority);

There is one catch to GetLeftPart(), however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of GetLeftPart() in my example above will be http://www.mywebsite.com.

If the port number had been something other than 80, it would be included in the result.

How to rename a table in SQL Server?

If you try exec sp_rename and receieve a LockMatchID error then it might help to add a use [database] statement first:

I tried

 exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
 -- Invalid EXECUTE statement using object "Object", method "LockMatchID".

What I had to do to fix it was to rewrite it to:

use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

Get next / previous element using JavaScript?

Well in pure javascript my thinking is that you would first have to collate them inside a collection.

var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");

So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds

for(var i = 0; i < divs.length;i++)
{
   if(divs[i] == selectionDiv)
   {
     var previous = divs[i - 1];
     var next = divs[i + 1];
   }
}

Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.

This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the tagName property.

Change status bar color with AppCompat ActionBarActivity

There are various ways of changing the status bar color.

1) Using the styles.xml. You can use the android:statusBarColor attribute to do this the easy but static way.

Note: You can also use this attribute with the Material theme.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

2) You can get it done dynamically using the setStatusBarColor(int) method in the Window class. But remember that this method is only available for API 21 or higher. So be sure to check that, or your app will surely crash in lower devices.

Here is a working example of this method.

if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(getResources().getColor(R.color.primaryDark));
}

where primaryDark is the 700 tint of the primary color I am using in my app. You can define this color in the colors.xml file.

Do give it a try and let me know if you have any questions. Hope it helps.

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

How to create a temporary directory and get the path / file name in Python

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

Uncaught TypeError: Cannot read property 'value' of undefined

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

JavaScript REST client Library

You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax function with the type of request you want to make:

$.ajax({
    url: 'http://example.com/',
    type: 'PUT',
    data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
    success: function() { alert('PUT completed'); }
});

You can replace PUT with GET/POST/DELETE or whatever.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

How to edit a text file in my terminal

Try this command:

sudo gedit helloWorld.txt

it, will open up a text editor to edit your file.

OR

sudo nano helloWorld.txt

Here, you can edit your file in the terminal window.

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

How do I create a file and write to it?

This answer is centred on Java 8, and tries to cover all the details needed for the Java Professional Exam. It tries to explain why the different approaches exist. They each have their benefits, and each might be simplest in a given scenario.

Classes involved include:

.
+-- OutputStream
¦   +-- FileOutputStream
+-- Writer
¦   +-- OutputStreamWriter
¦   ¦   +-- FileWriter
¦   +-- BufferedWriter
¦   +-- PrintWriter (Java 5+)
+-- Files (Java 7+)

FileOutputStream

This class is meant for writing streams of raw bytes. All the Writer approaches below rely on this class, either explicitly or under the hood.

try (FileOutputStream stream = new FileOutputStream("file.txt");) {
    byte data[] = "foo".getBytes();
    stream.write(data);
} catch (IOException e) {}

Note that the try-with-resources statement takes care of stream.close() and that closing the stream flushes it, like stream.flush() (all of the examples below use this approach).

OutputStreamWriter

This class is a bridge from character streams to byte streams. It can wrap a FileOutputStream, and write strings:

Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

BufferedWriter

This class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

It can wrap an OutputStreamWriter:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
    writer.write("foo");
    writer.newLine();  // method provided by BufferedWriter
} catch (IOException e) {}

Pre Java 5 this was the best approach for large files (with a regular try/catch block).

FileWriter

This is a subclass of the OutputStreamWriter, and is a convenience class for writing character files:

boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
    writer.write("foo");
    writer.append("bar");
} catch (IOException e) {}

The key benefit is that it has an optional append constructor argument, which determines whether it appends to or overwrites the existing file. Note that the append/overwrite behaviour is not controlled by the write() and append() methods, which behave in nearly the same way.

Note that:

  • There is no buffering, but to handle large files it can be wrapped in a BufferedWriter.
  • FileWriter uses the default encoding. It's often preferable to specify encoding explicitly

PrintWriter

This class prints formatted representations of objects to a text-output stream. Under the hood it is the same as the BufferedWriter approach above (new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))). PrintWriter was introduced in Java 5 as a convenient way to call this idiom, and adds additional methods such as printf() and println().

Methods in this class don't throw I/O exceptions. You can check errors by calling checkError(). The destination of a PrintWriter instance can be a File, OutputStream or Writer. Here is an example of writing to a file:

try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
    writer.print("foo");
    writer.printf("bar %d $", "a", 1);
    writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}

When writing to an OutputStream or Writer there is an optional autoFlush constructor parameter, which is false by default. Unlike the FileWriter, it will overwrite any existing file.

Files.write()

Java 7 introduced java.nio.file.Files. Files.write() lets you create and write to a file in a single call.

@icza's answer shows how to use this method. A couple of examples:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");

try {
    Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
    Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}

This does not involve a buffer, so it's not suitable for large files.

Files.newBufferedWriter()

Java 7 also introduced Files.newBufferedWriter() which makes it easy to get a BufferedWriter:

Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

This is similar to PrintWriter, with the downside of not having PrintWriter's methods, and the benefit that it doesn't swallow exceptions.

Summary

+-----------------------------------------------------------------------------------+
¦                           ¦        Buffer for        ¦ Can specify ¦   Throws     ¦
¦                           ¦       large files?       ¦  encoding?  ¦ IOException? ¦
+---------------------------+--------------------------+-------------+--------------¦
¦ OutputStreamWriter        ¦ Wrap with BufferedWriter ¦ Y           ¦ Y            ¦
¦ FileWriter                ¦ Wrap with BufferedWriter ¦             ¦ Y            ¦
¦ PrintWriter               ¦ Y                        ¦ Y           ¦              ¦
¦ Files.write()             ¦                          ¦ Y           ¦ Y            ¦
¦ Files.newBufferedWriter() ¦ Y                        ¦ Y           ¦ Y            ¦
+-----------------------------------------------------------------------------------+

Can you remove elements from a std::list while iterating through it?

You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:

std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
    bool isActive = (*i)->update();
    if (!isActive)
    {
        items.erase(i++);  // alternatively, i = items.erase(i);
    }
    else
    {
        other_code_involving(*i);
        ++i;
    }
}

Select values from XML field in SQL Server 2008

This post was helpful to solve my problem which has a little different XML format... my XML contains a list of keys like the following example and I store the XML in the SourceKeys column in a table named DeleteBatch:

<k>1</k>
<k>2</k>
<k>3</k>

Create the table and populate it with some data:

CREATE TABLE dbo.DeleteBatch (
    ExecutionKey INT PRIMARY KEY,
    SourceKeys XML)

INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 1, 
    (CAST('<k>1</k><k>2</k><k>3</k>' AS XML))

INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 2, 
    (CAST('<k>100</k><k>101</k>' AS XML))

Here's my SQL to select the keys from the XML:

SELECT ExecutionKey, p.value('.', 'int') AS [Key]
FROM dbo.DeleteBatch
    CROSS APPLY SourceKeys.nodes('/k') t(p)

Here's the query results...

ExecutionKey    Key
1   1
1   2
1   3
2   100
2   101

Postgres DB Size Command

SELECT pg_size_pretty(pg_database_size('name of database'));

Will give you the total size of a particular database however I don't think you can do all databases within a server.

However you could do this...

DO
$$
DECLARE
r   RECORD;
db_size TEXT;
BEGIN
FOR r in
SELECT datname FROM pg_database
WHERE datistemplate = false
LOOP
db_size:= (SELECT pg_size_pretty(pg_database_size(r.datname)));

RAISE NOTICE 'Database:% , Size:%', r.datname , db_size;

END LOOP;
END;
$$

PHP How to fix Notice: Undefined variable:

You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop

           $hn = "";
           $pid = "";
           $datereg = "";
           $prefix = "";
           $fname = "";
           $lname = "";
           $age = "";
           $sex = "";
           while (...){}

alternatively, it looks like you are just expecting a single row back. so you could just say

$row = pg_fetch_array($result);
if(!row) {
    return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];

return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;

How do you cache an image in Javascript

Even though your question says "using javascript", you can use the prefetch attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:

<link rel="prefetch" href="(url)">

More info on support here: http://caniuse.com/#search=prefetch

Note that IE 9,10 aren't listed in the caniuse matrix because Microsoft has discontinued support for them.

So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)

What is the yield keyword used for in C#?

This link has a simple example

Even simpler examples are here

public static IEnumerable<int> testYieldb()
{
    for(int i=0;i<3;i++) yield return 4;
}

Notice that yield return won't return from the method. You can even put a WriteLine after the yield return

The above produces an IEnumerable of 4 ints 4,4,4,4

Here with a WriteLine. Will add 4 to the list, print abc, then add 4 to the list, then complete the method and so really return from the method(once the method has completed, as would happen with a procedure without a return). But this would have a value, an IEnumerable list of ints, that it returns on completion.

public static IEnumerable<int> testYieldb()
{
    yield return 4;
    console.WriteLine("abc");
    yield return 4;
}

Notice also that when you use yield, what you are returning is not of the same type as the function. It's of the type of an element within the IEnumerable list.

You use yield with the method's return type as IEnumerable. If the method's return type is int or List<int> and you use yield, then it won't compile. You can use IEnumerable method return type without yield but it seems maybe you can't use yield without IEnumerable method return type.

And to get it to execute you have to call it in a special way.

static void Main(string[] args)
{
    testA();
    Console.Write("try again. the above won't execute any of the function!\n");

    foreach (var x in testA()) { }


    Console.ReadLine();
}



// static List<int> testA()
static IEnumerable<int> testA()
{
    Console.WriteLine("asdfa");
    yield return 1;
    Console.WriteLine("asdf");
}

How to put a UserControl into Visual Studio toolBox

The issue with my designer was 32 vs 64 bit issue. I could add the control to tool box after following the instructions in Cannot add Controls from 64-bit Assemblies to the Toolbox or Use in Designers Within the Visual Studio IDE MS KB article.

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

I had a struggle getting this to work i've tested it and it's working on lamp server mysql version 5.12

So, steps to success:

  1. sudo vim /etc/mysql/conf.d/mysql.cnf
  2. Scroll to the bottom of file Copy and paste

    [mysqld] sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

to the bottom of the file

  1. save and exit input mode
  2. sudo service mysql restart to restart MySQL.

Done!

cleanest way to skip a foreach if array is empty

I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.

All other solutions are quite dirty hacks to me.

Change CSS properties on click

Try this:

CSS

.style1{
    background-color:red;
    color:white;
    font-size:44px;
}

HTML

<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />

Javascript

function myFunction()
{
    document.getElementById('foo').setAttribute("class", "style1");
}

How to auto resize and adjust Form controls with change in resolution

this.WindowState = FormWindowState.Maximized;

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

Convert alphabet letters to number in Python

Here's something I use to convert excel column letters to numbers (so a limit of 3 letters but it's pretty easy to extend this out if you need more). Probably not the best way but it works for what I need it for.

def letter_to_number(letters):
    letters = letters.lower()
    dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
    strlen = len(letters)
    if strlen == 1:
        number = dictionary[letters]
    elif strlen == 2:
        first_letter = letters[0]
        first_number = dictionary[first_letter]
        second_letter = letters[1]
        second_number = dictionary[second_letter]
        number = (first_number * 26) + second_number
    elif strlen == 3:
        first_letter = letters[0]
        first_number = dictionary[first_letter]
        second_letter = letters[1]
        second_number = dictionary[second_letter]
        third_letter = letters[2]
        third_number = dictionary[third_letter]
        number = (first_number * 26 * 26) + (second_number * 26) + third_number
    return number

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

Escape string Python for MySQL

>>> import MySQLdb
>>> example = r"""I don't like "special" chars ¯\_(?)_/¯"""
>>> example
'I don\'t like "special" chars \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf'
>>> MySQLdb.escape_string(example)
'I don\\\'t like \\"special\\" chars \xc2\xaf\\\\_(\xe3\x83\x84)_/\xc2\xaf'

How do I remove a single file from the staging area (undo git add)?

git rm --cached FILE

,

git rm -r --cached CVS */CVS

Creating a jQuery object from a big HTML-string

You can try something like below

$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();

Google maps Marker Label with multiple characters

OK, here is one solution I have come up with which is pretty messed up.

I put the full label text into the div using the fontFamily label attribute. Then I use querySelectorAll to match the resulting style attributes to pull out the refs and rewrite the tags once the map has loaded:

var label = "A123";
var marker = new google.maps.Marker({
  position: latLon,
  label: {
    text: label,
    // Add in the custom label here
    fontFamily: 'Roboto, Arial, sans-serif, custom-label-' + label
  },
  map: map,
  icon: {
    path: 'custom icon path',
    fillColor: '#000000',
    labelOrigin: new google.maps.Point(26.5, 20),
    anchor: new google.maps.Point(26.5, 43), 
    scale: 1
  }
});

google.maps.event.addListener(map, 'idle', function() {
  var labels = document.querySelectorAll("[style*='custom-label']")
  for (var i = 0; i < labels.length; i++) {
    // Retrieve the custom labels and rewrite the tag content
    var matches = labels[i].getAttribute('style').match(/custom-label-(A\d\d\d)/);
    labels[i].innerHTML = matches[1];
  }
});

This seems pretty brittle. Are there any approaches which are less awful?

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

Single vs double quotes in JSON

As said, JSON is not Python syntax. You need to use double quotes in JSON. Its creator is (in-)famous for using strict subsets of allowable syntax to ease programmer cognitive overload.


Below can fail if one of the JSON strings itself contains a single quote as pointed out by @Jiaaro. DO NOT USE. Left here as an example of what does not work.

It is really useful to know that there are no single quotes in a JSON string. Say, you copied and pasted it from a browser console/whatever. Then, you can just type

a = json.loads('very_long_json_string_pasted_here')

This might otherwise break if it used single quotes, too.

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

You can also use copy con [filename] in a Windows command window (cmd.exe):

C:\copy con yourfile.txt [enter]
C:\CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
    1 Files Copied.

This will create a file named yourfile.txt in the local directory.

A generic error occurred in GDI+, JPEG Image to MemoryStream

One other cause of this error and that solve my problème is that your application doesn't have a write permission on some directory.

so to complete the answer of savindra : https://stackoverflow.com/a/7426516/6444829.

Here is how you Grant File Access to IIS_IUSERS

To provide access to an ASP.NET application, you must grant access to the IIs_IUSERS.

To grant read, write, and modify permissions to a specific File or Folder

  1. In Windows Explorer, locate and select the required file.

  2. Right click the file, and then click Properties.

  3. In the Properties dialog box, click the Security tab.

  4. On the Security tab, examine the list of users. (If your application is running as a Network Service, add the network service account in the list and grant it the permission.

  5. In the Properties dialog box, click IIs_IUSERS, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.

  6. Click Apply, and then click OK.

this worked for me in my IIS of windows server 2016 and local IIS windows 10.

Filter values only if not null using lambda in Java8

You just need to filter the cars that have a null name:

requiredCars = cars.stream()
                   .filter(c -> c.getName() != null)
                   .filter(c -> c.getName().startsWith("M"));

adding a datatable in a dataset

DataSet ds = new DataSet();

DataTable activity = DTsetgvActivity.Copy();
activity.TableName = "activity";
ds.Tables.Add(activity);

DataTable Honer = DTsetgvHoner.Copy();
Honer.TableName = "Honer";
ds.Tables.Add(Honer);

DataTable Property = DTsetgvProperty.Copy();
Property.TableName = "Property";
ds.Tables.Add(Property);


DataTable Income = DTsetgvIncome.Copy();
Income.TableName = "Income";
ds.Tables.Add(Income);

DataTable Dependant = DTsetgvDependant.Copy();
Dependant.TableName = "Dependant";
ds.Tables.Add(Dependant);

DataTable Insurance = DTsetgvInsurance.Copy();
Insurance.TableName = "Insurance";
ds.Tables.Add(Insurance);

DataTable Sacrifice = DTsetgvSacrifice.Copy();
Sacrifice.TableName = "Sacrifice";
ds.Tables.Add(Sacrifice);

DataTable Request = DTsetgvRequest.Copy();
Request.TableName = "Request";
ds.Tables.Add(Request);

DataTable Branchs = DTsetgvBranchs.Copy();
Branchs.TableName = "Branchs";
ds.Tables.Add(Branchs);

Genymotion error at start 'Unable to load virtualbox'

Open Genymotion in Windows as an administrator. My Genymotion works only in this mode

How to use onClick with divs in React.js

For future googlers (thousands have now googled this question):

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.

Getting Django admin url for an object

Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url method:

from django.urls import reverse

def get_admin_url(self):
    return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
                   args=[self.id])

How to set JAVA_HOME environment variable on Mac OS X 10.9?

I did it by putting

export JAVA_HOME=`/usr/libexec/java_home`

(backtics) in my .bashrc. See my comment on Adrian's answer.

Random string generation with upper case letters and digits

>>> import string 
>>> import random

the following logic still generates 6 character random sample

>>> print ''.join(random.sample((string.ascii_uppercase+string.digits),6))
JT7K3Q

No need to multiply by 6

>>> print ''.join(random.sample((string.ascii_uppercase+string.digits)*6,6))

TK82HK

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

Convert object string to JSON

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

Most Useful Attributes

I like [DebuggerStepThrough] from System.Diagnostics.

It's very handy for avoiding stepping into those one-line do-nothing methods or properties (if you're forced to work in an early .Net without automatic properties). Put the attribute on a short method or the getter or setter of a property, and you'll fly right by even when hitting "step into" in the debugger.

How do I base64 encode (decode) in C?

Here's the one I'm using:

#include <stdint.h>
#include <stdlib.h>


static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                '4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};


char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length) {

    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = malloc(*output_length);
    if (encoded_data == NULL) return NULL;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';

    return encoded_data;
}


unsigned char *base64_decode(const char *data,
                             size_t input_length,
                             size_t *output_length) {

    if (decoding_table == NULL) build_decoding_table();

    if (input_length % 4 != 0) return NULL;

    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;

    unsigned char *decoded_data = malloc(*output_length);
    if (decoded_data == NULL) return NULL;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }

    return decoded_data;
}


void build_decoding_table() {

    decoding_table = malloc(256);

    for (int i = 0; i < 64; i++)
        decoding_table[(unsigned char) encoding_table[i]] = i;
}


void base64_cleanup() {
    free(decoding_table);
}

Keep in mind that this doesn't do any error-checking while decoding - non base 64 encoded data will get processed.

Can a table have two foreign keys?

The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.

There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.

SQL query for a carriage return in a string and ultimately removing carriage return

You can also use regular expressions:

SELECT * FROM Parameters WHERE Name REGEXP '\n';

How to delete last character in a string in C#?

paramstr.Remove((paramstr.Length-1),1);

This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:

paramstr.Remove((paramstr.Length-4),1);

As an alternative, I have used this approach instead:

DateFrom = DateFrom.Substring(0, DateFrom.Length-4);

How to insert spaces/tabs in text using HTML/CSS

Go a step further than @Ivar and style my own custom tag like so... For me 'tab' is easier to remember and type.

tab {
    display: inline-block;
    margin-left: 40px;
}

And the HTML implementation...

<p>Left side of the whitespace<tab>Right side of the whitespace</p>

Screenshot of this code sample

And my screenshot...

How to create a HTML Table from a PHP array?

<?php

echo "<table>
<tr>
<th>title</th>
<th>price</th>
<th>number</th>
</tr>";
for ($i=0; $i<count($shop, 0); $i++)
{
    echo '<tr>';
    for ($j=0; $j<3; $j++)
    {
        echo '<td>'.$shop[$i][$j].'</td>';
    }
    echo '</tr>';
}
echo '</table>';

You can optimize it, but that should do.

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

I thing ng-if should work:

<div ng-repeat="product in products" ng-if="product.color === 'red' 
|| product.color === 'blue'">

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

Saving an Object (Data persistence)

I think it's a pretty strong assumption to assume that the object is a class. What if it's not a class? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__ after creation, pickle doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle serializes by reference to the object definition).

In all these cases, pickle and cPickle can fail you horribly.

If you are looking to save an object (arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill, which can serialize almost anything in python.

We start with a class…

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
...     pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
... 
>>> 

Now shut down, and restart...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
...     company1 = pickle.load(f)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>> 

Oops… pickle can't handle it. Let's try dill. We'll throw in another object type (a lambda) for good measure.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill       
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> with open('company_dill.pkl', 'wb') as f:
...     dill.dump(company1, f)
...     dill.dump(company2, f)
... 
>>> 

And now read the file.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
...     company1 = dill.load(f)
...     company2 = dill.load(f)
... 
>>> company1 
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>    

It works. The reason pickle fails, and dill doesn't, is that dill treats __main__ like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle does). The reason dill can pickle a lambda is that it gives it a name… then pickling magic can happen.

Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> dill.dump_session('dill.pkl')
>>> 

Now shut down your computer, go enjoy an espresso or whatever, and come back later...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>

The only major drawback is that dill is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.

However, if you are able to install python packages on your system, you can get the latest dill with git+https://github.com/uqfoundation/dill.git@master#egg=dill. And you can get the latest released version with pip install dill.

Print a variable in hexadecimal in Python

Convert the string to an integer base 16 then to hexadecimal.

print hex(int(string, base=16))

These are built-in functions.

http://docs.python.org/2/library/functions.html#int

Example

>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>> 

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

Getting current date and time in JavaScript

I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;

How do I set the background color of my main screen in Flutter?

I think you can also use a scaffold to do the white background. Here's some piece of code that may help.

import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {

      return new MaterialApp(
        title: 'Testing',
        home: new Scaffold(
        //Here you can set what ever background color you need.
          backgroundColor: Colors.white,
        ),
      );
    }
}

Hope this helps .

In Tkinter is there any way to make a widget not visible?

I'm also extremely late to the party, but I'll leave my version of the answer here for others who may have gotten here, like I did, searching for how to hide something that was placed on the screen with the .place() function, and not .pack() neither .grid().

In short, you can hide a widget by setting the width and height to zero, like this:

widget.place(anchor="nw", x=0, y=0, width=0, height=0)

To give a bit of context so you can see what my requirement was and how I got here. In my program, I have a window that needs to display several things that I've organized into 2 frames, something like this:

[WINDOW - app]
  [FRAME 1 - hMainWndFrame]
    [Buttons and other controls (widgets)]
  [FRAME 2 - hJTensWndFrame]
    [other Buttons and controls (widgets)]

Only one frame needs to be visible at a time, so on application initialisation, i have something like this:

hMainWndFrame = Frame(app, bg="#aababd")
hMainWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
...
hJTensWndFrame = Frame(app, bg="#aababd")

I'm using .place() instead of .pack() or .grid() because i specifically want to set precise coordinates on the window for each widget. So, when i want to hide the main frame and display the other one (along with all the other controls), all i have to do is call the .place() function again, on each frame, but specifying zero for width and height for the one i want to hide and the necessary width and height for the one i want to show, such as:

hMainWndFrame.place(anchor="nw", x=0, y=0, width=0, height=0)
hJTensWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)

Now it's true, I only tested this on Frames, not on other widgets, but I guess it should work on everything.

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

fatal: does not appear to be a git repository

I had a similar problem when using TFS 2017. I was not able to push or pull GIT repositories. Eventually I reinstalled TFS 2017, making sure that I installed TFS 2017 with an SSH Port different from 22 (in my case, I chose 8022). After that, push and pull became possible against TFS using SSH.

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

How to dismiss notification after action has been clicked

You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

How do I get indices of N maximum values in a NumPy array?

If you happen to be working with a multidimensional array then you'll need to flatten and unravel the indices:

def largest_indices(ary, n):
    """Returns the n largest indices from a numpy array."""
    flat = ary.flatten()
    indices = np.argpartition(flat, -n)[-n:]
    indices = indices[np.argsort(-flat[indices])]
    return np.unravel_index(indices, ary.shape)

For example:

>>> xs = np.sin(np.arange(9)).reshape((3, 3))
>>> xs
array([[ 0.        ,  0.84147098,  0.90929743],
       [ 0.14112001, -0.7568025 , -0.95892427],
       [-0.2794155 ,  0.6569866 ,  0.98935825]])
>>> largest_indices(xs, 3)
(array([2, 0, 0]), array([2, 2, 1]))
>>> xs[largest_indices(xs, 3)]
array([ 0.98935825,  0.90929743,  0.84147098])

Cannot set property 'innerHTML' of null

Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.

Converting between datetime, Timestamp and datetime64

You can just use the pd.Timestamp constructor. The following diagram may be useful for this and related questions.

Conversions between time representations

<SELECT multiple> - how to allow only one item selected?

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

Correct use for angular-translate in controllers

To make a translation in the controller you could use $translate service:

$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
    vm.si = translations['COMMON.SI'];
    vm.no = translations['COMMON.NO'];
});

That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope event: $translateChangeSuccess and do the same translation there:

    $rootScope.$on('$translateChangeSuccess', function () {
        $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
            vm.si = translations['COMMON.SI'];
            vm.no = translations['COMMON.NO'];
        });
    });

Of course, you could encapsulate the $translateservice in a method and call it in the controller and in the $translateChangeSucesslistener.

How can I represent an 'Enum' in Python?

I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:

class ConstMeta(type):
    '''
    Metaclass for some class that store constants
    '''
    def __init__(cls, name, bases, dct):
        '''
        init class instance
        '''
        def static_attrs():
            '''
            @rtype: (static_attrs, static_val_set)
            @return: Static attributes in dict format and static value set
            '''
            import types
            attrs = {}
            val_set = set()
            #Maybe more
            filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__'])
            for key, value in dct.iteritems():
                if type(value) != types.FunctionType and key not in filter_names:
                    if len(value) != 2:
                        raise NotImplementedError('not support for values that is not 2 elements!')
                    #Check value[0] duplication.
                    if value[0] not in val_set:
                        val_set.add(value[0])
                    else:
                        raise KeyError("%s 's key: %s is duplicated!" % (dict([(key, value)]), value[0]))
                    attrs[key] = value
            return attrs, val_set

        attrs, val_set = static_attrs()
        #Set STATIC_ATTRS to class instance so that can reuse
        setattr(cls, 'STATIC_ATTRS', attrs)
        setattr(cls, 'static_val_set', val_set)
        super(ConstMeta, cls).__init__(name, bases, dct)

    def __getattribute__(cls, name):
        '''
        Rewrite the special function so as to get correct attribute value
        '''
        static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS')
        if name in static_attrs:
            return static_attrs[name][0]
        return object.__getattribute__(cls, name)

    def static_values(cls):
        '''
        Put values in static attribute into a list, use the function to validate value.
        @return: Set of values
        '''
        return cls.static_val_set

    def __getitem__(cls, key):
        '''
        Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.
        @return: Desc string of related static value
        '''
        for k, v in cls.STATIC_ATTRS.iteritems():
            if v[0] == key:
                return v[1]
        raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls)))


class Const(object):
    '''
    Base class for constant class.

    @usage:

    Definition: (must inherit from Const class!
        >>> class SomeConst(Const):
        >>>   STATUS_NAME_1 = (1, 'desc for the status1')
        >>>   STATUS_NAME_2 = (2, 'desc for the status2')

    Invoke(base upper SomeConst class):
    1) SomeConst.STATUS_NAME_1 returns 1
    2) SomeConst[1] returns 'desc for the status1'
    3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')}
    4) SomeConst.static_values() returns set([1, 2])

    Attention:
    SomeCosnt's value 1, 2 can not be duplicated!
    If WrongConst is like this, it will raise KeyError:
    class WrongConst(Const):
        STATUS_NAME_1 = (1, 'desc for the status1')
        STATUS_NAME_2 = (1, 'desc for the status2')
    '''
    __metaclass__ = ConstMeta
##################################################################
#Const Base Class ends
##################################################################


def main():
    class STATUS(Const):
        ERROR = (-3, '??')
        OK = (0, '??')

    print STATUS.ERROR
    print STATUS.static_values()
    print STATUS.STATIC_ATTRS

    #Usage sample:
    user_input = 1
    #Validate input:
    print user_input in STATUS.static_values()
    #Template render like:
    print '<select>'
    for key, value in STATUS.STATIC_ATTRS.items():
        print '<option value="%s">%s</option>' % (value[0], value[1])
    print '</select>'


if __name__ == '__main__':
    main()

How to save an HTML5 Canvas as an image on a server?

In addition to Salvador Dali's answer:

on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.

Otherwise decoding won't work: the image will be saved but it will be an unreadable file.

Reverse each individual word of "Hello World" string with Java

Some of the above solutions are of the higher run time complexities. With the below algorithm, it can be achieved in O(n) time.

Algorithm:

  1. Parse the String from the end to beginning.
  2. Every time a space character is encountered i.e. " ", put the list of characters parsed till then in an ArrayList which can grow dynamically.
  3. Print the ArrayList in the reverse order which gives you the desired output.

Complexity: O(n) where n is the length of the String.

import java.io.IOException;
import java.util.ArrayList;

public class WordReverse {

    public static void main(String[] args) throws IOException {

        String inputStr = "Hello World";
        String reversed = "";
        ArrayList<String> alist = new ArrayList<String>();

        for (int i = inputStr.length() - 1; i >= 0; i--) {
            if (inputStr.charAt(i) != ' ') {
                reversed = reversed + inputStr.charAt(i);
            } else {
                alist.add(reversed);
                reversed = "";
            }
        }
        alist.add(reversed);
        String result = "";

        for (int i = alist.size() - 1; i >= 0; i--) {
            result = result + alist.get(i);
            result = result + " ";
        }
        System.out.println(result);
    }
}