Programs & Examples On #Atmosphere

The Asynchronous WebSocket/Comet Framework

Can not deserialize instance of java.lang.String out of START_OBJECT token

Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.

MainClass.java

public class MainClass {
  public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

String jsonStr = "{\r\n" + "    \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf- 
             43d6-b598-7c0c550635bb\",\r\n"
            + " \"type\": \"getDashboard\",\r\n" + "    \"data\": {\r\n"
            + "     \"workstationUuid\": \"ddec1caa-a97f-4922-833f- 
            632da07ffc11\"\r\n" + " },\r\n"
            + " \"reply\": true\r\n" + "}";

    ObjectMapper mapper = new ObjectMapper();

    MyPojo details = mapper.readValue(jsonStr, MyPojo.class);

    System.out.println("Value for getFirstName is: " + details.getId());
    System.out.println("Value for getLastName  is: " + details.getSocket());
    System.out.println("Value for getChildren is: " + 
      details.getData().getWorkstationUuid());
    System.out.println("Value for getChildren is: " + details.getReply());

}

MyPojo.java

public class MyPojo {
    private String id;

    private Data data;

    private String reply;

    private String socket;

    private String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public String getReply() {
        return reply;
    }

    public void setReply(String reply) {
        this.reply = reply;
    }

    public String getSocket() {
        return socket;
    }

    public void setSocket(String socket) {
        this.socket = socket;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    } 
}

Data.java

public class Data {
    private String workstationUuid;

    public String getWorkstationUuid() {
        return workstationUuid;
    }

    public void setWorkstationUuid(String workstationUuid) {
        this.workstationUuid = workstationUuid;
    }   
}

RESULTS:

Value for getFirstName is: 2
Value for getLastName  is: 0c317829-69bf-43d6-b598-7c0c550635bb
Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11
Value for getChildren is: true

Calculate percentage Javascript

To get the percentage of a number, we need to multiply the desired percentage percent by that number. In practice we will have:

function percentage(percent, total) {
    return ((percent/ 100) * total).toFixed(2)
}

Example of usage:

const percentResult = percentage(10, 100);
// print 10.00

.toFixed() is optional for monetary formats.

Removing empty lines in Notepad++

  1. notepad++
  2. Ctrl-H
  3. Select Regular Expression
  4. Enter ^[ \t]*$\r?\n into find what, leave replace empty. This will match all lines starting with white space and ending with carriage return (in this case a windows crlf)
  5. Click the Find Next button to see for yourself how it matches only empty lines.

pip install failing with: OSError: [Errno 13] Permission denied on directory

It is due permission problem,

sudo chown -R $USER /path to your python installed directory

default it would be /usr/local/lib/python2.7/

or try,

pip install --user -r package_name

and then say, pip install -r requirements.txt this will install inside your env

dont say, sudo pip install -r requirements.txt this is will install into arbitrary python path.

What is the connection string for localdb for version 11

I have connection string Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;

and even a .NET 3.5 program connects and execute SQL successfully.

But many people say .NET 4.0.2 or 4.5 is required.

java.io.IOException: Server returned HTTP response code: 500

HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode() and in case of errors, read the HttpURLConnection#getErrorStream() instead. It may namely contain information about the problem.

If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.

See also:

Remove Last Comma from a string

Remove last comma. Working example

_x000D_
_x000D_
function truncateText() {_x000D_
  var str= document.getElementById('input').value;_x000D_
  str = str.replace(/,\s*$/, "");_x000D_
  console.log(str);_x000D_
}
_x000D_
<input id="input" value="address line one,"/>_x000D_
<button onclick="truncateText()">Truncate</button>
_x000D_
_x000D_
_x000D_

How do I 'foreach' through a two-dimensional array?

I'm not a big fan of this method because of the memory usage involved, but if you use the arrays it produces, it isn't such a waste.

public static void ForEachRow<T>(this T[,] list, Action<int, T[]> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    T[] e;
    int i, j;

    for (i = 0; i < len; i++)
    {
        e = new T[sub];

        for (j = 0; j < sub; j++)
        {
            e[j] = list[i, j];
        }

        action(i, e);
    }
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    for (var j = 0; j < row.Length; j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, row[j]);
    }
});

The other solution I found is less memory intensive, but will use more CPU, especially when the dimensions of the arrays' entries are larger.

public static void ForEachRow<T>(this T[,] list, Action<int, IEnumerable<T>> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    int i, j;
    IEnumerable<T> e;

    for (i = 0; i < len; i++)
    {
        e = Enumerable.Empty<T>();

        for (j = 0; j < sub; j++)
        {
            e = e.Concat(AsEnumerable(list[i, j]));
        }

        action(i, e);
    }
}

private static IEnumerable<T> AsEnumerable<T>(T add)
{
    yield return add;
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    var j = 0;

    forrach (var o in row)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, o);

        ++j;
    }
});

As a whole, I find the first option to be more intuitive, especially if you want to access the produced array by its indexer.

At the end of the day, this is all just eye candy, neither methods should really be used in favour of directly accessing the source array;

for (var i = 0; i < list.GetLength(0); i++)
{
    foreach (var j = 0; j < list.GetLength(1); j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, list[i, j]);
    }
}

htaccess "order" Deny, Allow, Deny

Update : for the new apache 2.4 jump directly to the end.

The Order keyword and its relation with Deny and Allow Directives is a real nightmare. It would be quite interesting to understand how we ended up with such solution, a non-intuitive one to say the least.

  • The first important point is that the Order keyword will have a big impact on how Allow and Deny directives are used.
  • Secondly, Deny and Allow directives are not applied in the order they are written, they must be seen as two distinct blocks (one the for Deny directives, one for Allow).
  • Thirdly, they are drastically not like firewall rules: all rules are applied, the process is not stopping at the first match.

You have two main modes:

The Order-Deny-Allow-mode, or Allow-anyone-except-this-list-or-maybe-not

Order Deny,Allow
  • This is an allow by default mode. You optionally specify Deny rules.
  • Firstly, the Deny rules reject some requests.
  • If someone gets rejected you can get them back with an Allow.

I would rephrase it as:

Rule Deny
     list of Deny rules
Except
     list of Allow rules
Policy Allow (when no rule fired)

The Order-Allow-Deny-mode, or Reject-everyone-except-this-list-or-maybe-not

Order Allow,Deny
  • This is a deny by default mode. So you usually specify Allow rules.
  • Firstly, someone's request must match at least one Allow rule.
  • If someone matched an Allow, you can still reject them with a Deny.

In the simplified form:

Rule Allow
     list of Allow rules
Except
     list of Deny rules
Policy Deny (when no rule fired)

Back to your case

You need to allow a list of networks which are the country networks. And in this country you want to exclude some proxies' IP addresses.

You have taken the allow-anyone-except-this-list-or-maybe-not mode, so by default anyone can access your server, except proxies' IPs listed in the Deny list, but if they get rejected you still allow the country networks. That's too broad. Not good.

By inverting to order allow,deny you will be in the reject-everyone-except-this-list-or-maybe-not mode. So you will reject access to everyone but allow the country networks and then you will reject the proxies. And of course you must remove the Deny from all as stated by @Gerben and @Michael Slade (this answer only explains what they wrote).

The Deny from all is usually seen with order deny,allow to remove the allow by default access and make a simple, readable configuration. For example, specify a list of allowed IPs after that. You don't need that rule and your question is a perfect case of a 3-way access mode (default policy, exceptions, exceptions to exceptions).

But the guys who designed these settings are certainly insane.

All this is deprecated with Apache 2.4

The whole authorization scheme has been refactored in Apache 2.4 with RequireAll, RequireAny and RequireNone directives. See for example this complex logic example.

So the old strange Order logic becomes a relic, and to quote the new documentation:

Controling how and in what order authorization will be applied has been a bit of a mystery in the past

No module named MySQLdb

If you are running on Vista, you may want to check out the Bitnami Django stack. It is an all-in-one stack of Apache, Python, MySQL, etc. packaged with Bitrock crossplatform installers to make it really easy to get started. It runs on Windows, Mac and Linux. Oh, and is completely free :)

'Incorrect SET Options' Error When Building Database Project

In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

Using DateTime in a SqlParameter for Stored Procedure, format error

Here is how I add parameters:

sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB

I am assuming when you write out DOB there are no quotes.

Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.

Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

Automatically get loop index in foreach loop in Perl

Please consider:

print "Element at index $_ is $x[$_]\n" for keys @x;

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to copy a file to another path?

Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code

 class Program
 {
    static void Main(string[] args)
    {
        //path of file
        string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

        
        //duplicate file path 
        string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
         
          //provide source and destination file paths
        File.Copy(pathToOriginalFile, PathForDuplicateFile);

        Console.ReadKey();

    }
}

Source: File I/O in C# (Read, Write, Delete, Copy file using C#)

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Above answers are correct. This version is easy to follow:

Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:

Step [1] In your file which extends the RoomDatabase, change the line to:

`@Database(entities = ???.class,version = 1, exportSchema = true)`

Or

`@Database(entities = ???.class,version = 1)` 

(because the default value is always true)

Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:

         android{
                defaultConfig{
                      //javaComplieOptions SECTION
                      javaCompileOptions {
                            annotationProcessorOptions {
                                     arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
                            }
                       }
                      //Other SECTION
                      ...
                }
         }

$projectDir:is a variable name, you cannot change it. it will get your own project directory

schemas:is a string, you can change it to any you like. For example: "$projectDir/MyOwnSchemas".toString()

Which header file do you include to use bool type in c in linux?

#include <stdbool.h>

For someone like me here to copy and paste.

How to custom switch button?

You can use the regular Switch widget and just call setTextOn() and setTextOff(), or use the android:textOn and android:textOff attributes.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How to get the element clicked (for the whole document)?

I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.id, ' -->', e.target.innerHTML);
}

How to create a label inside an <input> element?

<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">

A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

Steps to reproduce can be simplified to this:

var contextOne = new EntityContext();
var contextTwo = new EntityContext();

var user = contextOne.Users.FirstOrDefault();

var group = new Group();
group.User = user;

contextTwo.Groups.Add(group);
contextTwo.SaveChanges();

Code without error:

var context = new EntityContext();

var user = context.Users.FirstOrDefault();

var group = new Group();
group.User = user; // Be careful when you set entity properties. 
// Be sure that all objects came from the same context

context.Groups.Add(group);
context.SaveChanges();

Using only one EntityContext can solve this. Refer to other answers for other solutions.

How to sort a Collection<T>?

I came across a similar problem. Had to sort a list of 3rd party class (objects).

List<ThirdPartyClass> tpc = getTpcList(...);

ThirdPartyClass does not implement the Java Comparable interface. I found an excellent illustration from mkyong on how to approach this problem. I had to use the Comparator approach to sorting.

//Sort ThirdPartyClass based on the value of some attribute/function
Collections.sort(tpc, Compare3rdPartyObjects.tpcComp);

where the Comparator is:

public abstract class Compare3rdPartyObjects {

public static Comparator<ThirdPartyClass> tpcComp = new Comparator<ThirdPartyClass>() {

    public int compare(ThirdPartyClass tpc1, ThirdPartyClass tpc2) {

        Integer tpc1Offset = compareUsing(tpc1);
        Integer tpc2Offset = compareUsing(tpc2);

        //ascending order
        return tpc1Offset.compareTo(tpc2Offset);

    }
};

//Fetch the attribute value that you would like to use to compare the ThirdPartyClass instances 
public static Integer compareUsing(ThirdPartyClass tpc) {

    Integer value = tpc.getValueUsingSomeFunction();
    return value;
}
}

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

Regular expression to match standard 10 digit phone number

Above regex is a slight modification of @Francis Gagnon.

Objective : To detect any possible pattern a user can share their US phone number


Version 1:

^\s*(?:\+?(\d{1,3}))?[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d[\W\D\s]*?\d)(?: *x(\d+))?\s*$

Test it over here Codepen: https://codepen.io/kiranbhattarai/pen/NWKMXQO

Explanation of the regex : https://regexr.com/4kt5j


Version 2:

\s*(?:\+?(\d{1,3}))?[\W\D\s]^|()*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d[\W\D\s]*?\d)(?: *x(\d+))?\s*$

What is in it: The test cases can be a part of the string. In version one the test cases should be a start of a line to work.

Codepen: https://codepen.io/kiranbhattarai/pen/GRKGNGG

Explanation of the regex : https://regexr.com/4kt9n


If you can find a pattern that can fail please do comment i will fix it.

Test Cases: Pass

8 0   0  4  4  4  5   55 5
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678
8005551234 x5678
1    800    555-1234
1----800----555-1234
800 (555) 1234
800(555)1234
8 0 0 5 5 5 1 2 3 4
8.0.0.5.5.5.1.2.3.4
8-0-0-5-5-5-1-2-3-4
(8)005551234
(80)05551234
8(00)5551234
8@0@0@5551234
8/0/0/5/5/5/1/2/3/4
8*0*0*5*5*5*1*2*3*4
8:0:0:5:5:5:1:2:3:4
8,0,0,5,5,5,1,2,3,4
800,555,1234
800:555:1234
1-718-444-1122
718-444-1122
(718)-444-1122
17184441122
7184441122
718.444.1122
1718.444.1122
1-123-456-7890
1 123-456-7890
1 (123) 456-7890
1 123 456 7890
1.123.456.7890
+91 (123) 456-7890
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
18001234567
1 800 123 4567
1-800-123-4567
+18001234567
+1 800 123 4567
+1 (800) 123 4567
1(800)1234567
+1800 1234567
1.8001234567
1.800.123.4567
+1 (800) 123-4567
18001234567
1 800 123 4567
+1 800 123-4567
+86 800 123 4567
1-800-123-4567
1 (800) 123-4567
(800)123-4567
(800) 123-4567
(800)1234567
800-123-4567
800.123.4567
1231231231
123-1231231
123123-1231
123-123 1231
123 123-1231
123-123-1231
(123)123-1231
(123) 123-1231
(123) 123 1231
+99 1234567890
+991234567890
(555) 444-6789
555-444-6789
555.444.6789
555 444 6789
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(003) 555-1212
(103) 555-1212
(911) 555-1212
18005551234
1 800 555 1234
+86 800-555-1234
1 (800) 555-1234

Converting RGB to grayscale/intensity

These values vary from person to person, especially for people who are colorblind.

Sort objects in ArrayList by date?

The Date class already implements Comparator interface. Assuming you have the class below:

public class A {

    private Date dateTime;

    public Date getDateTime() {
        return dateTime;
    }

    .... other variables

}

And let's say you have a list of A objects as List<A> aList, you can easily sort it with Java 8's stream API (snippet below):

import java.util.Comparator;
import java.util.stream.Collectors;

...

aList = aList.stream()
        .sorted(Comparator.comparing(A::getDateTime))
        .collect(Collectors.toList())

Register .NET Framework 4.5 in IIS 7.5

You can find the aspnet_regiis in the following directory:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Go to the directory and run the command form there. I guess the path is missing in your PATH variable.

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

Twitter Bootstrap add active class to li

To activate the menus and submenus, even with params in the URL, use the code bellow:

// Highlight the active menu
$(document).ready(function () {
    var action = window.location.pathname.split('/')[1];

    // If there's no action, highlight the first menu item
    if (action == "") {
        $('ul.nav li:first').addClass('active');
    } else {
        // Highlight current menu
        $('ul.nav a[href="/' + action + '"]').parent().addClass('active');

        // Highlight parent menu item
        $('ul.nav a[href="/' + action + '"]').parents('li').addClass('active');
    }
});

This accepts URLs like:

/posts
/posts/1
/posts/1/edit

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

If you are using MultiDex in your App Gradle then change extends application to extends MultiDexApplication in your application class. It will defiantly work

How to determine whether a given Linux is 32 bit or 64 bit?

If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a

To get your specific machine hardware name run

uname -m

You can also call

getconf LONG_BIT

which returns either 32 or 64

How can I include all JavaScript files in a directory via JavaScript file?

@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:

javascripts.php:

<?php
   //sets the content type to javascript 
   header('Content-type: text/javascript');

   // includes all js files of the directory
   foreach(glob("packages/*.js") as $file) {
      readfile($file);
   }
?>


index.php:

<script type="text/javascript" src="javascripts.php"></script>

That's it!
Have fun! :)

New line in Sql Query

You could do Char(13) and Char(10). Cr and Lf.

Char() works in SQL Server, I don't know about other databases.

Best method to download image from url in Android

Step 1: Declaring Permission in Android Manifest

First thing to do in your first Android Project is you declare required permissions in your ‘AndroidManifest.xml’ file.

For Android Download Image from URL, we need permission to access the internet to download file and read and write internal storage to save image to internal storage.

Add following lines of code at the top of tag of AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 2: Request required permission from user

Android allows every app to run in a sandbox. If an app needs to access certain resources or information outside that sandbox, it needs to request permission from user.

From Android 6.0 onward, Google wants developers to request permission from user from within the app, for more details on permissions read this.

Therefore for Android Download Image from URL, you’ll need to request Read Storage and Write

For this, we will use the following lines of code to first check if the required permission is already granted by the user, if not then we will request permission for storage read and write permission.

We’re creating a method ‘Downlaod Image’, you can simple call this wherever you need to download the image.

void DownloadImage(String ImageUrl) {

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
        showToast("Need Permission to access storage for Downloading Image");
    } else {
        showToast("Downloading Image...");
       //Asynctask to create a thread to downlaod image in the background 
        new DownloadsImage().execute(ImageUrl);
    }
}

Now that we have requested and been granted the user permission, to start with android download image from url, we will create an AsyncTask, as you are not allowed to run a background process in the main thread.

class DownloadsImage extends AsyncTask<String, Void,Void>{

    @Override
    protected Void doInBackground(String... strings) {
        URL url = null;
        try {
            url = new URL(strings[0]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Bitmap bm = null;
        try {
            bm =    BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Create Path to save Image
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ "/AndroidDvlpr"); //Creates app specific folder

        if(!path.exists()) {
            path.mkdirs();
        }

        File imageFile = new File(path, String.valueOf(System.currentTimeMillis())+".png"); // Imagename.png
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imageFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try{
            bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
            out.flush();
            out.close();
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(MainActivity.this,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    // Log.i("ExternalStorage", "Scanned " + path + ":");
                    //    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
        } catch(Exception e) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        showToast("Image Saved!");
    }
}

In the above give lines of code, a URL and Bitmap is created, using BitmapFactory.decodeStream, file is downloaded.

The File path is created to save the image (We have created a folder named ‘AndroidDvlpr’ in DIRECTORY_PICTURES) and download is initialized.

After downloading the file MediaScannerConnection, is called to read metadata from the file and add the file to the media content provider so the image is available for the user.

In the above lines of code, we have also created a method, showToast() to show Toast. complete code here:

void showToast(String msg){
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}

Read more here

Json.NET serialize object with root name

I hope this help.

//Sample of Data Contract:

[DataContract(Name="customer")]
internal class Customer {
  [DataMember(Name="email")] internal string Email { get; set; }
  [DataMember(Name="name")] internal string Name { get; set; }
}

//This is an extension method useful for your case:

public static string JsonSerialize<T>(this T o)
{
  MemoryStream jsonStream = new MemoryStream();
  var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
  serializer.WriteObject(jsonStream, o);

  var jsonString = System.Text.Encoding.ASCII.GetString(jsonStream.ToArray());

  var props = o.GetType().GetCustomAttributes(false);
  var rootName = string.Empty;
  foreach (var prop in props)
  {
    if (!(prop is DataContractAttribute)) continue;
    rootName = ((DataContractAttribute)prop).Name;
    break;
  }
  jsonStream.Close();
  jsonStream.Dispose();

  if (!string.IsNullOrEmpty(rootName)) jsonString = string.Format("{{ \"{0}\": {1} }}", rootName, jsonString);
  return jsonString;
}

//Sample of usage

var customer = new customer { 
Name="John",
Email="[email protected]"
};
var serializedObject = customer.JsonSerialize();

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

How can I get the current array index in a foreach loop?

well since this is the first google hit for this problem:

function mb_tell(&$msg) {
    if(count($msg) == 0) {
        return 0;
    }
    //prev($msg);
    $kv = each($msg);
    if(!prev($msg)) {
        end($msg);

        print_r($kv);
        return ($kv[0]+1);
    }
    print_r($kv);
    return ($kv[0]);
}

Html.fromHtml deprecated in Android N

update: as @Andy mentioned below Google has created HtmlCompat which can be used instead of the method below. Add this dependency implementation 'androidx.core:core:1.0.1 to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core.

This allows you to use:

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

You can read more about the different flags on the HtmlCompat-documentation

original answer: In Android N they introduced a new Html.fromHtml method. Html.fromHtml now requires an additional parameter, named flags. This flag gives you more control about how your HTML gets displayed.

On Android N and above you should use this new method. The older method is deprecated and may be removed in the future Android versions.

You can create your own Util-method which will use the old method on older versions and the newer method on Android N and above. If you don't add a version check your app will break on lower Android versions. You can use this method in your Util class.

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    if(html == null){
        // return an empty spannable if the html is null
        return new SpannableString("");
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // FROM_HTML_MODE_LEGACY is the behaviour that was used for versions below android N
        // we are using this flag to give a consistent behaviour
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        return Html.fromHtml(html);
    }
}

You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.

You can read more about the different flags on the Html class documentation

Bulk Insert to Oracle using .NET

Oracle says (http://www.oracle.com/technology/products/database/utilities/htdocs/sql_loader_overview.html)

SQL*Loader is the primary method for quickly populating Oracle tables with data from external files

My experience is that their loader loads their tables faster than anything else.

How to pretty print XML from Java?

a simpler solution based on this answer:

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer(); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

public static String prettyFormat(String input) {
    return prettyFormat(input, 2);
}

testcase:

prettyFormat("<root><child>aaa</child><child/></root>");

returns:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child>aaa</child>
  <child/>
</root>

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use

select into x from db.schema.y where 1=0

to copy the table to a new DB

How do I get today's date in C# in mm/dd/yyyy format?

Or without the year:

DateTime.Now.ToString("M/dd")

If using maven, usually you put log4j.properties under java or resources?

The resources used for initializing the project are preferably put in src/main/resources folder. To enable loading of these resources during the build, one can simply add entries in the pom.xml in maven project as a build resource

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering> 
        </resource>
    </resources>
</build> 

Other .properties files can also be kept in this folder used for initialization. Filtering is set true if you want to have some variables in the properties files of resources folder and populate them from the profile filters properties files, which are kept in src/main/filters which is set as profiles but it is a different use case altogether. For now, you can ignore them.

This is a great resource maven resource plugins, it's useful, just browse through other sections too.

Warning: comparison with string literals results in unspecified behaviour

This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.

String literals like

"a"

or

"This is a string"

are put in the text or data segments of your program.

A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.

So if I have

char *s1 = "This is a string";

then s1 is a pointer to the first byte of the string.

Now, if I have

char *s2 = "This is a string";

this is also a pointer to the same first byte of that string in the text or data segment of the program.

But if I have

char *s3 = malloc( 17 );
strcpy(s3, "This is a string");

then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.

Illustrative examples:

Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:

s1 == s2 // True: we are comparing two pointers that contain the same address

but the following will evaluate to false

s1 == s3 // False: Comparing two pointers that don't hold the same address.

And although it might be tempting to have something like this:

struct Vehicle{
    char *type;
    // other stuff
}

if( type == "Car" )
   //blah1
else if( type == "Motorcycle )
   //blah2

You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.

I have tested it and it works. If I do

A.type = "Car";

then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like

if( A.type == B.type )

but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.

Solutions:

In your case, what you want to do is use strcmp(a,b) == 0 to replace a == b

In the case of my example, you should use an enum.

enum type {CAR = 0, MOTORCYCLE = 1}

The preceding thing with string was useful because you could print the type, so you might have an array like this

char *types[] = {"Car", "Motorcycle"};

And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.

Therefore it might be better to do

char *getTypeString(int type)
{
    switch(type)
    case CAR: return "Car";
    case MOTORCYCLE: return "Motorcycle"
    default: return NULL;
}

How to restart kubernetes nodes?

Get nodes

kubectl get nodes

Result:

NAME            STATUS     AGE
192.168.1.157   NotReady   42d
192.168.1.158   Ready      42d
192.168.1.159   Ready      42d

Describe node

Here is a NotReady on the node of 192.168.1.157. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.

kubectl describe node 192.168.1.157

Partial Result:

Conditions:
Type          Status          LastHeartbeatTime                       LastTransitionTime                      Reason                  Message
----          ------          -----------------                       ------------------                      ------                  -------
OutOfDisk     Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.
Ready         Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.

There is a OutOfDisk on my node, then Kubelet stopped posting node status. So, I must free some disk space, using the command of df on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name under the role of su I can remove the useless images.

Login in node

Login in 192.168.1.157 by using ssh, like ssh [email protected], and switch to the 'su' by sudo su;

Restart kubelet

/etc/init.d/kubelet restart

Result:

stop: Unknown instance: 
kubelet start/running, process 59261

Get nodes again

On the master:

kubectl get nodes

Result:

NAME            STATUS    AGE
192.168.1.157   Ready     42d
192.168.1.158   Ready     42d
192.168.1.159   Ready     42d

Ok, that node works fine.

Here is a reference: Kubernetes

How to replace specific values in a oracle database column?

If you need to update the value in a particular table:

UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');

where

  TABLE-NAME         - The name of the table being updated
  COLUMN-NAME        - The name of the column being updated
  STRING-TO-REPLACE  - The value to replace
  REPLACEMENT-STRING - The replacement

How to insert multiple rows from array using CodeIgniter framework?

You could always use mysql's LOAD DATA:

LOAD DATA LOCAL INFILE '/full/path/to/file/foo.csv' INTO TABLE `footable` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' 

to do bulk inserts rather than using a bunch of INSERT statements.

How to prevent robots from automatically filling up a form?

With the emergence of headless browsers (like phantomjs) which can emulate anything, you can't suppose that :

  • spam bots do not use javascript,
  • you can track mouse events to detect bot,
  • they won't see that a field is visually hidden,
  • they won't wait a given time before submitting.

If that used to be true, it is no longer true.

If you wan't an user friendly solution, just give them a beautiful "i am a spammer" submit button:

 <input type="submit" name="ignore" value="I am a spammer!" />
 <input type="image" name="accept" value="submit.png" alt="I am not a spammer" />

Of course you can play with two image input[type=image] buttons, changing the order after each load, the text alternatives, the content of the images (and their size) or the name of the buttons; which will require some server work.

 <input type="image" name="random125454548" value="random125454548.png"
      alt="I perfectly understand that clicking on this link will send the
      e-mail to the expected person" />
 <input type="image" name="random125452548" value="random125452548.png"
      alt="I really want to cancel the submission of this form" />

For accessibility reasons, you have to put a correct textual alternative, but I think that a long sentence is better for screenreaders users than being considered as a bot.

Additional note: those examples illustrate that understanding english (or any language), and having to make a simple choice, is harder for a spambot than : waiting 10 seconds, handling CSS or javascript, knowing that a field is hidden, emulating mouse move or emulating keyboard typing, ...

How to extract hours and minutes from a datetime.datetime object?

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:

str(tdate.time())[0:5]

Convert seconds to Hour:Minute:Second

function timeToSecond($time){
    $time_parts=explode(":",$time);
    $seconds= ($time_parts[0]*86400) + ($time_parts[1]*3600) + ($time_parts[2]*60) + $time_parts[3] ; 
    return $seconds;
}

function secondToTime($time){
    $seconds  = $time % 60;
    $seconds<10 ? "0".$seconds : $seconds;
    if($seconds<10) {
        $seconds="0".$seconds;
    }
    $time     = ($time - $seconds) / 60;
    $minutes  = $time % 60;
    if($minutes<10) {
        $minutes="0".$minutes;
    }
    $time     = ($time - $minutes) / 60;
    $hours    = $time % 24;
    if($hours<10) {
        $hours="0".$hours;
    }
    $days     = ($time - $hours) / 24;
    if($days<10) {
        $days="0".$days;
    }

    $time_arr = array($days,$hours,$minutes,$seconds);
    return implode(":",$time_arr);
}

How can I get column names from a table in Oracle?

You can query the USER_TAB_COLUMNS table for table column metadata.

SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'MYTABLE'

How to change the style of the title attribute inside an anchor tag?

CSS can't change the tooltip appearance. It is browser/OS-dependent. If you want something different you'll have to use Javascript to generate markup when you hover over the element instead of the default tooltip.

Using NULL in C++?

I never use NULL in my C or C++ code. 0 works just fine, as does if (ptrname). Any competent C or C++ programmer should know what those do.

How to pass arguments to Shell Script through docker run

With Docker, the proper way to pass this sort of information is through environment variables.

So with the same Dockerfile, change the script to

#!/bin/bash
echo $FOO

After building, use the following docker command:

docker run -e FOO="hello world!" test

Can I call methods in constructor in Java?

Can I put my method readConfig() into constructor?

Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private) is really required.

If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.

So it should be private if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private and final if the method is reused inside the package or in the subclasses.

which would give me benefit of one time calling or is there another mechanism to do that ?

You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap copy constructor that constructs a new HashMap with the same mappings as the specified Map parameter :

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

Extracting the logic of the map populating in putMapEntries() is a good thing because it allows :

  • reusing the method in other contexts. For example clone() and putAll() use it too
  • (minor but interesting) giving a meaningful name that conveys the performed logic

Rownum in postgresql

If you have a unique key, you may use COUNT(*) OVER ( ORDER BY unique_key ) as ROWNUM

SELECT t.*, count(*) OVER (ORDER BY k ) ROWNUM 
FROM yourtable t;

| k |     n | rownum |
|---|-------|--------|
| a | TEST1 |      1 |
| b | TEST2 |      2 |
| c | TEST2 |      3 |
| d | TEST4 |      4 |

DEMO

Laravel: Auth::user()->id trying to get a property of a non-object

In Laravel 8.6, the following works for me in a controller:

$id = auth()->user()->id;

How to redirect to the same page in PHP

There are a number of different $_SERVER (docs) properties that return information about the current page, but my preferred method is to use $_SERVER['HTTP_HOST']:

header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . $location);

where $location is the path after the domain, starting with /.

How to read string from keyboard using C?

The following code can be used to read the input string from a user. But it's space is limited to 64.

char word[64] = { '\0' };  //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
    scanf_s("%c", &word[i++], 1);
}

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

How to download and save a file from Internet using Java?

Use apache commons-io, just one line code:

FileUtils.copyURLToFile(URL, File)

Making Enter key on an HTML form submit instead of activating button

I just hit a problem with this. Mine was a fall off from changing the input to a button and I'd had a badly written /> tag terminator:

So I had:

<button name="submit_login" type="submit" class="login" />Login</button>

And have just amended it to:

<button name="submit_login" type="submit" class="login">Login</button>

Now works like a charm, always the annoying small things... HTH

SQLException : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify transaction_status varchar(10) but you actually trying to store _transaction_status which contain 19 characters. that's why you faced this type of error in this code

The total number of locks exceeds the lock table size

I found another way to solve it - use Table Lock. Sure, it can be unappropriate for your application - if you need to update table at same time.

See: Try using LOCK TABLES to lock the entire table, instead of the default action of InnoDB's MVCC row-level locking. If I'm not mistaken, the "lock table" is referring to the InnoDB internal structure storing row and version identifiers for the MVCC implementation with a bit identifying the row is being modified in a statement, and with a table of 60 million rows, probably exceeds the memory allocated to it. The LOCK TABLES command should alleviate this problem by setting a table-level lock instead of row-level:

SET @@AUTOCOMMIT=0;
LOCK TABLES avgvol WRITE, volume READ;
INSERT INTO avgvol(date,vol)
SELECT date,avg(vol) FROM volume
GROUP BY date;
UNLOCK TABLES;

Jay Pipes, Community Relations Manager, North America, MySQL Inc.

How can I draw vertical text with CSS cross-browser?

I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE

.rot-neg-90 {
    -moz-transform:rotate(-270deg); 
    -moz-transform-origin: bottom left;
    -webkit-transform: rotate(-270deg);
    -webkit-transform-origin: bottom left;
    -o-transform: rotate(-270deg);
    -o-transform-origin:  bottom left;
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}

How to change time in DateTime?

DateTime is an immutable type, so you can't change it.

However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.

Something like this:

var newDt = s.Date + TimeSpan.FromHours(2);

Retrieve the maximum length of a VARCHAR column in SQL Server

For sql server (SSMS)

select MAX(LEN(ColumnName)) from table_name

This will returns number of characters.

 select MAX(DATALENGTH(ColumnName)) from table_name

This will returns number of bytes used/required.

IF some one use varchar then use DATALENGTH.More details

Add line break within tooltips

Just add a data attribute

data-html="true"

and you're good to go.

Eg. usage:

<i data-html="true" class="tooltip ficon-help-icon" twipsy-content-set="true" data-original-title= "<b>Hello</b> Stackoverflow" </i>

It has worked in majority of the tooltip plugins i have tried as of now.

How can I check the system version of Android?

Build.VERSION.RELEASE;

That will give you the actual numbers of your version; aka 2.3.3 or 2.2. The problem with using Build.VERSION.SDK_INT is if you have a rooted phone or custom rom, you could have a none standard OS (aka my android is running 2.3.5) and that will return a null when using Build.VERSION.SDK_INT so Build.VERSION.RELEASE will work no matter what!

How do I plot in real-time in a while loop using matplotlib?

I know this question is old, but there's now a package available called drawnow on GitHub as "python-drawnow". This provides an interface similar to MATLAB's drawnow -- you can easily update a figure.

An example for your use case:

import matplotlib.pyplot as plt
from drawnow import drawnow

def make_fig():
    plt.scatter(x, y)  # I think you meant this

plt.ion()  # enable interactivity
fig = plt.figure()  # make a figure

x = list()
y = list()

for i in range(1000):
    temp_y = np.random.random()
    x.append(i)
    y.append(temp_y)  # or any arbitrary update to your figure's data
    i += 1
    drawnow(make_fig)

python-drawnow is a thin wrapper around plt.draw but provides the ability to confirm (or debug) after figure display.

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

How to sort by two fields in Java?

Have your person class implement Comparable<Person> and then implement the compareTo method, for instance:

public int compareTo(Person o) {
    int result = name.compareToIgnoreCase(o.name);
    if(result==0) {
        return Integer.valueOf(age).compareTo(o.age);
    }
    else {
        return result;
    }
}

That will sort first by name (case insensitively) and then by age. You can then run Arrays.sort() or Collections.sort() on the collection or array of Person objects.

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

How to overcome root domain CNAME restrictions?

CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.

Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.

Per RFC:

If a CNAME RR is present at a node, no other data should be present;

And Per IETF 'Common DNS Operational and Configuration Errors' Document:

This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!

References:

How to return 2 values from a Java method?

you have to use collections to return more then one return values

in your case you write your code as

public static List something(){
        List<Integer> list = new ArrayList<Integer>();
        int number1 = 1;
        int number2 = 2;
        list.add(number1);
        list.add(number2);
        return list;
    }

    // Main class code
    public static void main(String[] args) {
      something();
      List<Integer> numList = something();
    }

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

This worked for me! You can convert to datatype you want be it a date or string

to_char(TO_DATE(TO_CHAR(end_date),'MM-DD-YYYY'),'YYYY-MM-DD') AS end_date

Convert interface{} to int

I whole-heartedly agree with zzzz's type assertion answer and I strongly prefer that way over others. That said, here's what I've had to do when the preferred method has not worked... (long story related to cross-serialization of data). You can even chain this into a switch statement with case errInt == nil and similar expressions.

package main

import "fmt"
import "strconv"

func main() {
    var v interface{}
    v = "4"

    i, errInt := strconv.ParseInt(v.(string), 10, 64)

    if errInt == nil {
        fmt.Printf("%d is a int", i)
        /* do what you wish with "i" here */
    }
}

Like I said above, try type assertion first before trying this way.

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Debug JavaScript in Eclipse

In 2015, there are at least six choices for JavaScript debugging in Eclipse:

Adding to the above, here are a couple of videos which focus on "debugging JavaScript using eclipse"

Outdated

Creating columns in listView and add items

Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)

private void initListView()
{
    // Add columns
    lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}

You can also use the other overload, Add(string). E.g:

lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");

Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx

Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.

var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);

You can also store objects in the item's Tag property.

item2.Tag = person;

And then you can extract it

var person = item2.Tag as Person;

Let me know if you have any questions and I hope this helps!

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

according to mysql documentation none of these works! People pay attention! so we will upload test.sql into the test_db type this into the shell:

mysql --user=user_name --password=yourpassword test_db < d:/test.sql

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

pip issue installing almost any library

This video tutorial worked for me:

$ curl https://bootstrap.pypa.io/get-pip.py | python

How do I compare 2 rows from the same table (SQL Server)?

You can join a table to itself as many times as you require, it is called a self join.

An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

SELECT a.SelfJoinTableID
FROM   dbo.SelfJoinTable a
       INNER JOIN dbo.SelfJoinTable b
         ON a.SelfJoinTableID = b.SelfJoinTableID
       INNER JOIN dbo.SelfJoinTable c
         ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE  a.Status = 'Status to filter a'
       AND b.Status = 'Status to filter b'
       AND c.Status = 'Status to filter c' 

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

href around input type submit

It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).

To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).

python xlrd unsupported format, or corrupt file.

I found the similar problem when downloading .xls file and opened it using xlrd library. Then I tried out the solution of converting .xls into .xlsx as detailed here: how to convert xls to xlsx

It works like a charm and rather than opening .xls, I am working with .xlsx file now using openpyxl library.

Hope it helps to solve your issue.

Why when I transfer a file through SFTP, it takes longer than FTP?

Your results make sense. Since FTP operates over a non-encrypted channel it is faster than SFTP (which is subsystem on top of the SSH version 2 protocol). Also remember that SFTP is a packet based protocol unlike FTP which is command based.

Each packet in SFTP is encrypted before being written to the outgoing socket from the client and subsequently decrypted when received by the server. This of-course leads to slow transfer rates but very secure transfer. Using compression such as zlib with SFTP improves the transfer time but still it won't be anywhere near plain text FTP. Perhaps a better comparison is to compare SFTP with FTPS which both use encryption?

Speed for SFTP depends on the cipher used for encryption/decryption, the compression used e.g. zlib, packet sizes and buffer sizes used for the socket connection.

How to Change Margin of TextView

setMargins() sets the INNER margins of the TextView, not the layout-margins. Is that what you want to do? This two different margins can be quite complicated.

If you want to set the layout margins, change the LayoutParams of the TextView (textview.getLayoutParams(), then change the parameters on the returned LayoutParams object).

You don't need to change anything on your LinearLayout.

Regards, Oliver

What is wrong with my SQL here? #1089 - Incorrect prefix key

There is a simple way of doing it. This may not be the expert answer and it may not work for everyone but it did for me.

Uncheck all primary and unique check boxes, jut create a plain simple table.

When phpmyadmin (or other) shows you the table structure, make the column primary by the given button.

Then click on change and edit the settings of that or other colums like 'unique' etc.

What's the function like sum() but for multiplication? product()?

I prefer the answers a and b above using functools.reduce() and the answer using numpy.prod(), but here is yet another solution using itertools.accumulate():

import itertools
import operator
prod = list(itertools.accumulate((3, 4, 5), operator.mul))[-1]

setImmediate vs. nextTick

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

htaccess - How to force the client's browser to clear the cache?

You can not force the browsers to clear the cache.

Your .html file seems to be re-loaded sooner as it expires after 10 days. What you have to do is to update your .html file and move all your files to a new folder such as version-2/ or append a version identifier to each file such as mypicture-2.jpg. Then you reference these new files in your .html file and the browser will load them again because the location changed.

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

How to format column to number format in Excel sheet?

Sorry to bump an old question but the answer is to count the character length of the cell and not its value.

CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If

hope that helps. Cheers

Add items in array angular 4

Your empList is object type but you are trying to push strings

Try this

this.empList.push({this.name,this.empoloyeeID});

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

adding this worked for me.

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

How to add icon inside EditText view in Android ?

If you want to use Android's default drawable, you can use @android:drawable/ic_menu_search like this:

<EditText android:id="@+id/inputSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@android:drawable/ic_menu_search"
    android:hint="Search product.."
    android:inputType="textVisiblePassword"/>

Hibernate-sequence doesn't exist

You need to set for Hibernate5.x <property name="hibernate.id.new_generator_mappings">false</property>.. see and link.

For older version of hibernate 4.x: <prop key="hibernate.id.new_generator_mappings">false</prop>

How do you get the path to the Laravel Storage folder?

In Laravel 3, call path('storage').

In Laravel 4, use the storage_path() helper function.

Hiding a form and showing another when a button is clicked in a Windows Forms application

i believe the following code will only run after form1 is closed

 while (true)
    {
        if (form1.Visible == false)
            form2.Show();
    }

Why not start your form2 from form1 instead?

Form2 form2 = new Form2();
 private void button1_Click_1(object sender, EventArgs e)
    {
        if (richTextBox1.Text != null)
        {
            form1.Visible=false;
            form2.Show();

        }
        else MessageBox.Show("Insert Attributes First !");

    }

Convert XLS to CSV on command line

All of these answers helped me construct the following script which will automatically convert XLS* files to CSV and vice versa, by dropping one or more files on the script (or via command line). Apologies for the janky formatting.

' https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line
' https://gist.github.com/tonyerskine/77250575b166bec997f33a679a0dfbe4

' https://stackoverflow.com/a/36804963/1037948
'* Global Settings and Variables
Set args = Wscript.Arguments

For Each sFilename In args
    iErr = ConvertExcelFormat(sFilename)
    ' 0 for normal success
    ' 404 for file not found
    ' 10 for file skipped (or user abort if script returns 10)
Next

WScript.Quit(0)

Function ConvertExcelFormat(srcFile)

    if IsEmpty(srcFile) OR srcFile = "" Then
        WScript.Echo "Error! Please specify at least one source path. Usage: " & WScript.ScriptName & " SourcePath.xls*|csv"
        ConvertExcelFormat = -1
        Exit Function
        'Wscript.Quit
    End If

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    srcExt = objFSO.GetExtensionName(srcFile)

    ' the 6 is the constant for 'CSV' format, 51 is for 'xlsx'
    ' https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlfileformat-enumeration-excel
    ' https://www.rondebruin.nl/mac/mac020.htm
    Dim outputFormat, srcDest

    If LCase(Mid(srcExt, 1, 2)) = "xl" Then
        outputFormat = 6
        srcDest = "csv"
    Else
        outputFormat = 51
        srcDest = "xlsx"
    End If

    'srcFile = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
    srcFile = objFSO.GetAbsolutePathName(srcFile)
    destFile = Replace(srcFile, srcExt, srcDest)

    Dim oExcel
    Set oExcel = CreateObject("Excel.Application")
    Dim oBook
    Set oBook = oExcel.Workbooks.Open(srcFile)
    ' preserve formatting? https://stackoverflow.com/a/8658845/1037948
    'oBook.Application.Columns("A:J").NumberFormat = "@"
    oBook.SaveAs destFile, outputFormat
    oBook.Close False
    oExcel.Quit
    WScript.Echo "Conversion complete of '" & srcFile & "' to '" & objFSO.GetFileName(destFile) & "'"

End Function

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

How can I change the remote/target repository URL on Windows?

Take a look in .git/config and make the changes you need.

Alternatively you could use

git remote rm [name of the url you sets on adding]

and

git remote add [name] [URL]

Or just

git remote set-url [URL]

Before you do anything wrong, double check with

git help remote

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

phantomjs not waiting for "full" page load

In my program, I use some logic to judge if it was onload: watching it's network request, if there was no new request on past 200ms, I treat it onload.

Use this, after onLoadFinish().

function onLoadComplete(page, callback){
    var waiting = [];  // request id
    var interval = 200;  //ms time waiting new request
    var timer = setTimeout( timeout, interval);
    var max_retry = 3;  //
    var counter_retry = 0;

    function timeout(){
        if(waiting.length && counter_retry < max_retry){
            timer = setTimeout( timeout, interval);
            counter_retry++;
            return;
        }else{
            try{
                callback(null, page);
            }catch(e){}
        }
    }

    //for debug, log time cost
    var tlogger = {};

    bindEvent(page, 'request', function(req){
        waiting.push(req.id);
    });

    bindEvent(page, 'receive', function (res) {
        var cT = res.contentType;
        if(!cT){
            console.log('[contentType] ', cT, ' [url] ', res.url);
        }
        if(!cT) return remove(res.id);
        if(cT.indexOf('application') * cT.indexOf('text') != 0) return remove(res.id);

        if (res.stage === 'start') {
            console.log('!!received start: ', res.id);
            //console.log( JSON.stringify(res) );
            tlogger[res.id] = new Date();
        }else if (res.stage === 'end') {
            console.log('!!received end: ', res.id, (new Date() - tlogger[res.id]) );
            //console.log( JSON.stringify(res) );
            remove(res.id);

            clearTimeout(timer);
            timer = setTimeout(timeout, interval);
        }

    });

    bindEvent(page, 'error', function(err){
        remove(err.id);
        if(waiting.length === 0){
            counter_retry = 0;
        }
    });

    function remove(id){
        var i = waiting.indexOf( id );
        if(i < 0){
            return;
        }else{
            waiting.splice(i,1);
        }
    }

    function bindEvent(page, evt, cb){
        switch(evt){
            case 'request':
                page.onResourceRequested = cb;
                break;
            case 'receive':
                page.onResourceReceived = cb;
                break;
            case 'error':
                page.onResourceError = cb;
                break;
            case 'timeout':
                page.onResourceTimeout = cb;
                break;
        }
    }
}

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

Using SQL LIKE and IN together

SELECT * FROM tablename
  WHERE column IN 
    (select column from  tablename 
    where column like 'M510%' 
    or column like 'M615%' 
    OR column like 'M515%' 
    or column like'M612%'
    )

Convert UTC dates to local time in PHP

Given a local timezone, such as 'America/Denver', you can use DateTime class to convert UTC timestamp to the local date:

$timestamp = *********;
$date = new DateTime("@" . $timestamp);
$date->setTimezone(new DateTimeZone('America/Denver'));
echo $date->format('Y-m-d H:i:s');

How to trigger an event after using event.preventDefault()

If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) :

//Register "custom confirm popin" on click on specific links
$(document).on(
    "click", 
    "A.confirm", 
    function(event){
        //prevent default click action
        event.preventDefault();
        //show "custom confirm popin"
        $.ui.Modal.confirm(
            //popin text
            "Do you confirm ?", 
            //action on click 'ok'
            function() {
                //Unregister handler (prevent loop)
                $(document).off("click", "A.confirm");
                //Do default click action
                $(event.target)[0].click();
            }
        );
    }
);

Multiple Updates in MySQL

Use a temporary table

// Reorder items
function update_items_tempdb(&$items)
{
    shuffle($items);
    $table_name = uniqid('tmp_test_');
    $sql = "CREATE TEMPORARY TABLE `$table_name` ("
        ."  `id` int(10) unsigned NOT NULL AUTO_INCREMENT"
        .", `position` int(10) unsigned NOT NULL"
        .", PRIMARY KEY (`id`)"
        .") ENGINE = MEMORY";
    query($sql);
    $i = 0;
    $sql = '';
    foreach ($items as &$item)
    {
        $item->position = $i++;
        $sql .= ($sql ? ', ' : '')."({$item->id}, {$item->position})";
    }
    if ($sql)
    {
        query("INSERT INTO `$table_name` (id, position) VALUES $sql");
        $sql = "UPDATE `test`, `$table_name` SET `test`.position = `$table_name`.position"
            ." WHERE `$table_name`.id = `test`.id";
        query($sql);
    }
    query("DROP TABLE `$table_name`");
}

Get my phone number in android

Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.

editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}

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

Here is a generic type-safe method which can be called to dump any given Map.

import java.util.Iterator;
import java.util.Map;

public class MapUtils {
    static interface ItemCallback<K, V> {
        void handler(K key, V value, Map<K, V> map);
    }

    public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {
        Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<K, V> entry = it.next();

            callback.handler(entry.getKey(), entry.getValue(), map);
        }
    }

    public static <K, V> void printMap(Map<K, V> map) {
        forEach(map, new ItemCallback<K, V>() {
            @Override
            public void handler(K key, V value, Map<K, V> map) {
                System.out.println(key + " = " + value);
            }
        });
    }
}

Example

Here is an example of its use. Notice that the type of the Map is inferred by the method.

import java.util.*;

public class MapPrinter {
    public static void main(String[] args) {
        List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {
            private static final long serialVersionUID = 1L;
            {
                add(new LinkedHashMap<String, Integer>() {
                    private static final long serialVersionUID = 1L;
                    {
                        put("One", 0);
                        put("Two", 1);
                        put("Three", 3);
                    }
                });

                add(new LinkedHashMap<String, Object>() {
                    private static final long serialVersionUID = 1L;
                    {
                        put("Object", new Object());
                        put("Integer", new Integer(0));
                        put("Double", new Double(0.0));
                    }
                });
            }
        };

        for (Map<?, ?> map : maps) {
            MapUtils.printMap(map);
            System.out.println();
        }
    }
}

Output

One = 0
Two = 1
Three = 3

Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0

Load properties file in JAR?

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

EDIT: Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

Java: export to an .jar file in eclipse

Go to file->export->JAR file, there you may select "Export generated class files and sources" and make sure that your project is selected, and all folder under there are also! Good luck!

WHERE clause on SQL Server "Text" data type

You can use LIKE instead of =. Without any wildcards this will have the same effect.

DECLARE @Village TABLE
        (CastleType TEXT)

INSERT INTO @Village
VALUES
  (
    'foo'
  )

SELECT *
FROM   @Village
WHERE  [CastleType] LIKE 'foo' 

text is deprecated. Changing to varchar(max) will be easier to work with.

Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

PHP - Getting the index of a element from a array

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

        $keys=array_keys($items);
        foreach($keys as $index=>$key){
                    echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                    var_dump($items[$key]);
                    ...
        }

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

MySQL: How to copy rows, but change a few fields?

Let's say your table has two other columns: foo and bar

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, "155"
  FROM Table
 WHERE Event_ID = "120"

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

Basic authentication with fetch?

NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS

  1. npm install base-64 --save
  2. import { encode } from "base-64";
  3.  const response = await fetch(URL, {
      method: 'post',
      headers: new Headers({
        'Authorization': 'Basic ' + encode(username + ":" + password),
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({
        "PassengerMobile": "xxxxxxxxxxxx",
        "Password": "xxxxxxx"
      })
    });
    const posts = await response.json();
    
  4. Don't forget to define this whole function as async

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

Setting the number of map tasks and reduce tasks

The first part has already been answered, "just a suggestion" The second part has also been answered, "remove extra spaces around =" If both these didnt work, are you sure you have implemented ToolRunner ?

Update Top 1 record in table sql server

When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause that is specified in a subselect statement.

TOP cannot be used in an UPDATE and DELETE statements on partitioned views.

TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

Excel VBA: function to turn activecell to bold

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

Eg

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

C - The %x format specifier

The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.

As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.

Using the formatting in your code example in printf, with no additional parameters:

printf ("%08x %08x %08x %08x");

Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.

Extract time from date String

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I have IntelliJ IDEA 12.x on the Mac and I use Maven 3 and I get the red highlighting over my code even though the Maven build is fine. None of the above (re-indexing, force import, etc.) worked for me. I had to do the following:

Intellij -> Preferences -> Maven -> Importing
    [ ] Use Maven3 to import projects

I have to check the Maven3 import option and that fixes the issue.

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

ASP MVC href to a controller/view

how about

<li>
<a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a>
</li>

NodeJS / Express: what is "app.use"?

use is a method to configure the middleware used by the routes of the Express HTTP server object. The method is defined as part of Connect that Express is based upon.

Update Starting with version 4.x, Express no longer depends on Connect.

The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions.

How do I raise the same Exception with a custom message in Python?

Update: For Python 3, check Ben's answer


To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)

For python 2.x where x>=6:

try:
    try:
      raise ValueError  # something bad...
    except ValueError as err:
      err.message=err.message+" hello"
      raise              # re-raise current exception
except ValueError as e:
    print(" got error of type "+ str(type(e))+" with message " +e.message)

This will also do the right thing if err is derived from ValueError. For example UnicodeDecodeError.

Note that you can add whatever you like to err. For example err.problematic_array=[1,2,3].


Edit: @Ducan points in a comment the above does not work with python 3 since .message is not a member of ValueError. Instead you could use this (valid python 2.6 or later or 3.x):

try:
    try:
      raise ValueError
    except ValueError as err:
       if not err.args: 
           err.args=('',)
       err.args = err.args + ("hello",)
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e.args))

Edit2:

Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and python3:

try:
    try:
      raise ValueError
    except ValueError as err:
       err.extra_info = "hello"
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e))
    if 'extra_info' in dir(e):
       print e.extra_info

WPF Datagrid set selected row

// In General to Access all rows //

foreach (var item in dataGrid1.Items)
{
    string str = ((DataRowView)dataGrid1.Items[1]).Row["ColumnName"].ToString();
}

//To Access Selected Rows //

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        string str = ((DataRowView)dataGrid1.SelectedItem).Row["ColumnName"].ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

It's not necessary to rewrite everything. I recommend doing this instead:

Post this inside your .m file of your custom cell.

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,32,32);
}

This should do the trick nicely. :]

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

AngularJS: Service vs provider vs factory

Understanding AngularJS Factory, Service and Provider

All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.

From Docs Service/Factory:

  • Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Factory

A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.

app.factory('MyFactory', function() {
    var serviceObj = {};
    //creating an object with methods/functions or variables
    serviceObj.myFunction = function() {
        //TO DO:
    };
    //return that object
    return serviceObj;
});

Usage

It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.

Service

Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties).

app.service('MyService', function() {
    //directly binding events to this context
    this.myServiceFunction = function() {
        //TO DO:
    };
});

Usage

Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.

Provider

A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular.

app.provider('configurableService', function() {
    var name = '';
    //this method can be be available at configuration time inside app.config.
    this.setName = function(newName) {
        name = newName;
    };
    this.$get = function() {
        var getName = function() {
             return name;
        };
        return {
            getName: getName //exposed object to where it gets injected.
        };
    };
});

Usage

When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like dev, stage or prod

NOTE

Only provider will be available in config phase of angular, while service & factory are not.

Hope this has cleared up your understanding about Factory, Service and Provider.

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

Printing Lists as Tabular Data

A simple way to do this is to loop over all columns, measure their width, create a row_template for that max width, and then print the rows. It's not exactly what you are looking for, because in this case, you first have to put your headings inside the table, but I'm thinking it might be useful to someone else.

table = [
    ["", "Man Utd", "Man City", "T Hotspur"],
    ["Man Utd", 1, 0, 0],
    ["Man City", 1, 1, 0],
    ["T Hotspur", 0, 1, 2],
]
def print_table(table):
    longest_cols = [
        (max([len(str(row[i])) for row in table]) + 3)
        for i in range(len(table[0]))
    ]
    row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row))

You use it like this:

>>> print_table(table)

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2

Can a website detect when you are using Selenium with chromedriver?

Obfuscating JavaScripts result

I have checked the chromedriver source code. That injects some javascript files to the browser.
Every javascript file on this link is injected to the web pages: https://chromium.googlesource.com/chromium/src/+/master/chrome/test/chromedriver/js/

So I used reverse engineering and obfuscated the js files by Hex editing. Now i was sure that no more javascript variable, function names and fixed strings were used to uncover selenium activity. But still some sites and reCaptcha detect selenium!
Maybe they check the modifications that are caused by chromedriver js execution :)


Edit 1:

Chrome 'navigator' parameters modification

I discovered there are some parameters in 'navigator' that briefly uncover using of chromedriver. These are the parameters:

  • "navigator.webdriver" On non-automated mode it is 'undefined'. On automated mode it's 'true'.
  • "navigator.plugins" On headless chrome has 0 length. So I added some fake elements to fool the plugin length checking process.
  • "navigator.languages" was set to default chrome value '["en-US", "en", "es"]' .

So what i needed was a chrome extension to run javascript on the web pages. I made an extension with the js code provided in the article and used another article to add the zipped extension to my project. I have successfully changed the values; But still nothing changed!

I didn't find other variables like these but it doesn't mean that they don't exist. Still reCaptcha detects chromedriver, So there should be more variables to change. The next step should be reverse engineering of the detector services that i don't want to do.

Now I'm not sure does it worth to spend more time on this automation process or search for alternative methods!

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

Eclipse - Failed to create the java virtual machine

You can do a workaround as below:

Create a shortcut for eclipse and right click on the short cut and go to properties of the shortcut.

In the target box update the string:

-vm "C:\Program Files\Java\jdk1.6.0_07\bin"

the path will change according to your java installed directory.

So after changing the target string will be something like below.

D:\adt-bundle-windows-x86-20131030\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_07\bin"

Click apply and try clicking the Eclipse shortcut.

Java - get the current class name?

this answer is late, but i think there is another way to do this in the context of anonymous handler class.

let's say:

class A {
    void foo() {
        obj.addHandler(new Handler() {
            void bar() {
                String className=A.this.getClass().getName();
                // ...
            }
        });
    }
}

it will achieve the same result. additionally, it's actually quite convenience since every class is defined at compile time, so no dynamicity is damaged.

above that, if the class is really nested, i.e. A actually is enclosed by B, the class of B can be easily known as:

B.this.getClass().getName()

How can I align the columns of tables in Bash?

It's easier than you wonder.

If you are working with a separated by semicolon file and header too:

$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t

If you are working with array (using tab as separator):

for((i=0;i<array_size;i++));
do

   echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv

done;

cat file.csv | column -t

How to use ImageBackground to set background image for screen in react-native

To add background Image, React Native is based on component, the ImageBackground Component requires two props style={{}} and source={require('')}

 <ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}> 
<....yourContent Goes here...>
    </ImageBackground>

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

I will share my experience with this problem. I was going crazy because of this, but I found out that the problem was a bug with Eclipse itself, rather than my code: In eclipse, unable to reference an android library project in another android project

So, if you have the Android Support Library in your C: drive and your project in the D: drive on your computer, Eclipse won't function correctly and won't know where the Android Support Library is (green tick turns into red cross). To solve this, you need to move both projects onto the same hard drive.

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

Digital Certificate: How to import .cer file in to .truststore file using?

The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.

You do not have to put an alias and the password of the keystore, you can just type:

keytool -v -import -file somefile.crt  -alias somecrt -keystore my-cacerts

Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.

Update regarding the differences of cer and crt (just to clarify) According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider

CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Here is the solution I found:

How to fix the missing MSVCR711.dll problem

You can find MSVCR71.dll file in following location of your installed SQL Developer 2.1 directory:

sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll

How do I delete all the duplicate records in a MySQL table without temp tables

Add Unique Index on your table:

ALTER IGNORE TABLE TableA   
ADD UNIQUE INDEX (member_id, quiz_num, question_num, answer_num);

is work very well

How do I query for all dates greater than a certain date in SQL Server?

DateTime start1 = DateTime.Parse(txtDate.Text);

SELECT * 
FROM dbo.March2010 A
WHERE A.Date >= start1;

First convert TexBox into the Datetime then....use that variable into the Query

how do you filter pandas dataframes by multiple columns

You can filter by multiple columns (more than two) by using the np.logical_and operator to replace & (or np.logical_or to replace |)

Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:

def filter_df(df, filter_values):
    """Filter df by matching targets for multiple columns.

    Args:
        df (pd.DataFrame): dataframe
        filter_values (None or dict): Dictionary of the form:
                `{<field>: <target_values_list>}`
            used to filter columns data.
    """
    import numpy as np
    if filter_values is None or not filter_values:
        return df
    return df[
        np.logical_and.reduce([
            df[column].isin(target_values) 
            for column, target_values in filter_values.items()
        ])
    ]

Usage:

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})

filter_df(df, {
    'a': [1, 2, 3],
    'b': [1, 2, 4]
})

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

matrix multiplication algorithm time complexity

The standard way of multiplying an m-by-n matrix by an n-by-p matrix has complexity O(mnp). If all of those are "n" to you, it's O(n^3), not O(n^2). EDIT: it will not be O(n^2) in the general case. But there are faster algorithms for particular types of matrices -- if you know more you may be able to do better.

How to use custom packages

For this kind of folder structure:

main.go
mylib/
  mylib.go

The simplest way is to use this:

import (
    "./mylib"
)

How to call same method for a list of objects?

Taking @Ants Aasmas answer one step further, you can create a wrapper that takes any method call and forwards it to all elements of a given list:

class AllOf:
    def __init__(self, elements):
        self.elements = elements
    def __getattr__(self, attr):
        def on_all(*args, **kwargs):
            for obj in self.elements:
                getattr(obj, attr)(*args, **kwargs)
        return on_all

That class can then be used like this:

class Foo:
    def __init__(self, val="quux!"):
        self.val = val
    def foo(self):
        print "foo: " + self.val

a = [ Foo("foo"), Foo("bar"), Foo()]
AllOf(a).foo()

Which produces the following output:

foo: foo
foo: bar
foo: quux!

With some work and ingenuity it could probably be enhanced to handle attributes as well (returning a list of attribute values).

How do I look inside a Python object?

Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:

/usr/lib/python2.5/string.py

I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.

"Cannot GET /" with Connect on Node.js

Had the same issue. It was resolved as described above.

In my index.js

var port = 1338,
express = require('express'),
app = express().use(express.static(__dirname + '/')),
http = require('http').Server(app),
io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log('a user connected');
});

http.listen(port, function(){
    console.log("Node server listening on port " + port);
});

and in my index.html

<!doctype html>
<html>
    <head>
        <title>
            My page
        </title>
    </head>
    <body>
        <script src = "lib/socket.io.js"></script>
        <script src = "lib/three.js"></script>
        <script>
            var socket = io();
        </script>
    </body>
</html>

the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js"> through some dark magic (since there is physically a node_modules and lib directory in between) .

Difference between <input type='button' /> and <input type='submit' />

It should be also mentioned that a named input of type="submit" will be also submitted together with the other form's named fields while a named input type="button" won't.

With other words, in the example below, the named input name=button1 WON'T get submitted while the named input name=submit1 WILL get submitted.

Sample HTML form (index.html):

<form action="checkout.php" method="POST">

  <!-- this won't get submitted despite being named -->
  <input type="button" name="button1" value="a button">

  <!-- this one does; so the input's TYPE is important! -->
  <input type="submit" name="submit1" value="a submit button">

</form>

The PHP script (checkout.php) that process the above form's action:

<?php var_dump($_POST); ?>

Test the above on your local machine by creating the two files in a folder named /tmp/test/ then running the built-in PHP web server from shell:

php -S localhost:3000 -t /tmp/test/

Open your browser at http://localhost:3000 and see for yourself.

One would wonder why would we need to submit a named button? It depends on the back-end script. For instance the WooCommerce WordPress plugin won't process a Checkout page posted unless the Place Order named button is submitted too. If you alter its type from submit to button then this button won't get submitted and thus the Checkout form would never get processed.

This is probably a small detail but you know, the devil is in the details.

Macro to Auto Fill Down to last adjacent cell

This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.

Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Calling Javascript function from server side

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

How do I use .toLocaleTimeString() without displaying seconds?

You can try this, which is working for my needs.

var d = new Date();
d.toLocaleTimeString().replace(/:\d{2}\s/,' ');

or

d.toLocaleString().replace(/:\d{2}\s/,' ');

nginx showing blank PHP pages

location ~ [^/]\.php(/|$) {
         fastcgi_pass unix:/PATH_TO_YOUR_PHPFPM_SOCKET_FILE/php7.0-fpm.sock;
         include fastcgi_params;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}

Good luck

Postgresql tables exists, but getting "relation does not exist" when querying

The error can be caused by access restrictions. Solution:

GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

Android: textview hyperlink

I hit on the same problem and finally find the working solution.

  1. in the string.xml file, define:

    <string name="textWithHtml">The URL link is &lt;a href="http://www.google.com">Google&lt;/a></string>
    

Replace the "<" less than character with HTML escaped character.

  1. In Java code:

    String text = v.getContext().getString(R.string.textWithHtml);
    textView.setText(Html.fromHtml(text));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

And the TextBox will correctly display the text with clickable anchor link

Usage of MySQL's "IF EXISTS"

SELECT IF((
     SELECT count(*) FROM gdata_calendars 
     WHERE `group` =  ? AND id = ?)
,1,0);

For Detail explanation you can visit here

LOAD DATA INFILE Error Code : 13

If you're using cPanel or phpmyadmin to import the CSV using LOAD DATA then be sure to Enable Use LOCAL keyword. This worked for me in a shared server environment.

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

How do I do pagination in ASP.NET MVC?

Well, what is the data source? Your action could take a few defaulted arguments, i.e.

ActionResult Search(string query, int startIndex, int pageSize) {...}

defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:

        routes.MapRoute("Search", "Search/{query}/{startIndex}",
                        new
                        {
                            controller = "Home", action = "Search",
                            startIndex = 0, pageSize = 20
                        });

To split the feed, you can use LINQ quite easily:

var page = source.Skip(startIndex).Take(pageSize);

(or do a multiplication if you use "pageNumber" rather than "startIndex")

With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.

You should then be able to use action-links to the next page (etc):

<%=Html.ActionLink("next page", "Search", new {
                query, startIndex = startIndex + pageSize, pageSize }) %>

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

Sending POST data without form

_x000D_
_x000D_
function redir(data) {_x000D_
  document.getElementById('redirect').innerHTML = '<form style="display:none;" position="absolute" method="post" action="location.php"><input id="redirbtn" type="submit" name="value" value=' + data + '></form>';_x000D_
  document.getElementById('redirbtn').click();_x000D_
}
_x000D_
<button onclick="redir('dataToBeSent');">Next Page</button>_x000D_
<div id="redirect"></div>
_x000D_
_x000D_
_x000D_

You can use this method which creates a new hidden form whose "data" is sent by "post" to "location.php" when a button[Next Page] is clicked.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

I installed python2.7 to solve this issue. I wish can help you.

How to send a JSON object using html form data

The micro-library field-assist does exactly that: collectValues(formElement) will return a normalized json from the input fields (that means, also, checkboxes as booleans, selects as strings,etc).

Invalid length parameter passed to the LEFT or SUBSTRING function

CHARINDEX will return 0 if no spaces are in the string and then you look for a substring of -1 length.

You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.

SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.