Programs & Examples On #Pentaho

The Pentaho BI Suite is an open source Business Intelligence suite with integrated reporting, dashboard, data mining, workflow and ETL capabilities. It is primarily written in Java.

Pentaho Data Integration SQL connection

I just came across the same issue while trying to query a MySQL Database from Pentaho.

Error connecting to database [Local MySQL DB] : org.pentaho.di.core.exception.KettleDatabaseException: Error occured while trying to connect to the database

Exception while loading class org.gjt.mm.mysql.Driver

Expanding post by @user979331 the solution is:

  1. Download the MySQL Java Connector / Driver that is compatible with your kettle version
  2. Unzip the zip file (in my case it was mysql-connector-java-5.1.31.zip)
  3. copy the .jar file (mysql-connector-java-5.1.31-bin.jar) and paste it in your Lib folder:

    PC: C:\Program Files\pentaho\design-tools\data-integration\lib

    Mac: /Applications/data-integration/lib

Restart Pentaho (Data Integration) and re-test the MySQL Connection.

Additional interesting replies from others that could also help:

How to get last 7 days data from current datetime to last 7 days in sql server

Hope this will help,

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate >= cast(dateadd(day, -7, GETDATE()) as date)
and CreatedDate < cast(GETDATE()+1 as date) order by CreatedDate desc

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

Byte Array to Image object

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

Modifying Objects within stream in Java8 while iterating

This might be a little late. But here is one of the usage. This to get the count of the number of files.

Create a pointer to memory (a new obj in this case) and have the property of the object modified. Java 8 stream doesn't allow to modify the pointer itself and hence if you declare just count as a variable and try to increment within the stream it will never work and throw a compiler exception in the first place

Path path = Paths.get("/Users/XXXX/static/test.txt");



Count c = new Count();
            c.setCount(0);
            Files.lines(path).forEach(item -> {
                c.setCount(c.getCount()+1);
                System.out.println(item);});
            System.out.println("line count,"+c);

public static class Count{
        private int count;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "Count [count=" + count + "]";
        }



    }

What does bundle exec rake mean?

It means use rake that bundler is aware of and is part of your Gemfile over any rake that bundler is not aware of and run the db:migrate task.

How can I tail a log file in Python?

If you are on linux you implement a non-blocking implementation in python in the following way.

import subprocess
subprocess.call('xterm -title log -hold -e \"tail -f filename\"&', shell=True, executable='/bin/csh')
print "Done"

How to overload functions in javascript?

I am using a bit different overloading approach based on arguments number. However i believe John Fawcett's approach is also good. Here the example, code based on John Resig's (jQuery's Author) explanations.

// o = existing object, n = function name, f = function.
    function overload(o, n, f){
        var old = o[n];
        o[n] = function(){
            if(f.length == arguments.length){
                return f.apply(this, arguments);
            }
            else if(typeof o == 'function'){
                return old.apply(this, arguments);
            }
        };
    }

usability:

var obj = {};
overload(obj, 'function_name', function(){ /* what we will do if no args passed? */});
overload(obj, 'function_name', function(first){ /* what we will do if 1 arg passed? */});
overload(obj, 'function_name', function(first, second){ /* what we will do if 2 args passed? */});
overload(obj, 'function_name', function(first,second,third){ /* what we will do if 3 args passed? */});
//... etc :)

Test if object implements interface

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

How to add font-awesome to Angular 2 + CLI project

Many instructions above work, I suggest looking at those. However, something to note:

Using <i class="fas fa-coffee"></i> did not work in my project (new practice project only a week old) after installation and the sample icon here was also copied to the clipboard from Font Awesome within the past week.

This<i class="fa fa-coffee"></i> does work. If after installing Font Awesome on your project it isn't yet working, I suggest checking the class on your icon to remove the 's' to see if it works then.

HTML5 Video Autoplay not working correctly

Chrome does not allow autoplay if the video is not muted. Try using this:

<video width="440px" loop="true" autoplay="autoplay" controls muted>
  <source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>

Import regular CSS file in SCSS file?

It is now possible using:

@import 'CSS:directory/filename.css';

How can I find script's directory?

Here's what I ended up with. This works for me if I import my script in the interpreter, and also if I execute it as a script:

import os
import sys

# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
    path = os.path.realpath(sys.argv[0])
    if os.path.isdir(path):
        return path
    else:
        return os.path.dirname(path)

Can I call a function of a shell script from another shell script?

If you define

    #!/bin/bash
        fun1(){
          echo "Fun1 from file1 $1"
        }
fun1 Hello
. file2 
fun1 Hello
exit 0

in file1(chmod 750 file1) and file2

   fun1(){
      echo "Fun1 from file2 $1"
    }
    fun2(){
      echo "Fun1 from file1 $1"
    }

and run ./file2 you'll get Fun1 from file1 Hello Fun1 from file2 Hello Surprise!!! You overwrite fun1 in file1 with fun1 from file2... So as not to do so you must

declare -f pr_fun1=$fun1
. file2
unset -f fun1
fun1=$pr_fun1
unset -f pr_fun1
fun1 Hello

it's save your previous definition for fun1 and restore it with the previous name deleting not needed imported one. Every time you import functions from another file you may remember two aspects:

  1. you may overwrite existing ones with the same names(if that the thing you want you must preserve them as described above)
  2. import all content of import file(functions and global variables too) Be careful! It's dangerous procedure

How to make an Android Spinner with initial text "Select One"?

I found many good solutions for this. most is working by adding an item to the end of adapter, and don't display the last item in drop-down list. The big problem for me was the spinner drop-down list will start from the bottom of the list. So user see the last items instead of the first items (in case of have many items to show), after touch the spinner for the first time.

So I put the hint item to the beginning of the list. and hide the first item in drop-down list.

private void loadSpinner(){

    HintArrayAdapter hintAdapter = new HintArrayAdapter<String>(context, 0);

    hintAdapter.add("Hint to be displayed");
    hintAdapter.add("Item 1");
    hintAdapter.add("Item 2");
            .
            .
    hintAdapter.add("Item 30");

    spinner1.setAdapter(hintAdapter);

    //spinner1.setSelection(0); //display hint. Actually you can ignore it, because the default is already 0
    //spinner1.setSelection(0, false); //use this if don't want to onItemClick called for the hint

    spinner1.setOnItemSelectedListener(yourListener);
}

private class HintArrayAdapter<T> extends ArrayAdapter<T> {

    Context mContext;

    public HintArrayAdapter(Context context, int resource) {
        super(context, resource);
        this.mContext = context
    }

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
        TextView texview = (TextView) view.findViewById(android.R.id.text1);

        if(position == 0) {
            texview.setText("");
            texview.setHint(getItem(position).toString()); //"Hint to be displayed"
        } else {
            texview.setText(getItem(position).toString());
        }

        return view;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view;

        if(position == 0){
            view = inflater.inflate(R.layout.spinner_hint_list_item_layout, parent, false); // Hide first row
        } else {
            view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
            TextView texview = (TextView) view.findViewById(android.R.id.text1);
            texview.setText(getItem(position).toString());
        } 

        return view;
    }
}

set the below layout in @Override getDropDownView() when position is 0, to hide the first hint row.

R.layout.spinner_hint_list_item_layout:

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

</LinearLayout>

Iterate through the fields of a struct in Go

Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that

package main

import (
    "fmt"
    "reflect"
)

type person struct {
    firsName string
    lastName string
    iceCream []string
}

func main() {
    u := struct {
        myMap    map[int]int
        mySlice  []string
        myPerson person
    }{
        myMap:   map[int]int{1: 10, 2: 20},
        mySlice: []string{"red", "green"},
        myPerson: person{
            firsName: "Esmaeil",
            lastName: "Abedi",
            iceCream: []string{"Vanilla", "chocolate"},
        },
    }
    v := reflect.ValueOf(u)
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(v.Type().Field(i).Name)
        fmt.Println("\t", v.Field(i))
    }
}
and there is no *panic* for v.Field(i)

Simple search MySQL database using php

This is a better code that will help you through.
With your database, but rather, I have used mysql not mysqli
Enjoy it.

<body>

<form action="" method="post">

  <input name="search" type="search" autofocus><input type="submit" name="button">

</form>

<table>
  <tr><td><b>First Name</td><td></td><td><b>Last Name</td></tr>

<?php

$con=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('employee');


if(isset($_POST['button'])){    //trigger button click

  $search=$_POST['search'];

  $query=mysql_query("select * from employees where first_name like '%{$search}%' || last_name like '%{$search}%' ");

if (mysql_num_rows($query) > 0) {
  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}else{
    echo "No employee Found<br><br>";
  }

}else{                          //while not in use of search  returns all the values
  $query=mysql_query("select * from employees");

  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}

mysql_close();
?>

Get top 1 row of each group

I've done some timings over the various recommendations here, and the results really depend on the size of the table involved, but the most consistent solution is using the CROSS APPLY These tests were run against SQL Server 2008-R2, using a table with 6,500 records, and another (identical schema) with 137 million records. The columns being queried are part of the primary key on the table, and the table width is very small (about 30 bytes). The times are reported by SQL Server from the actual execution plan.

Query                                  Time for 6500 (ms)    Time for 137M(ms)

CROSS APPLY                                    17.9                17.9
SELECT WHERE col = (SELECT MAX(COL)…)           6.6               854.4
DENSE_RANK() OVER PARTITION                     6.6               907.1

I think the really amazing thing was how consistent the time was for the CROSS APPLY regardless of the number of rows involved.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

Have you created the DSN first in Control Panel>Administrative Tools>ODBC>System DSN. Name it same as "myDatabase" and if i is asking for locating the database/access file specify the path using browse option. Once ur DSN will be created successfully you will be easily able to access ur DB.

Copying files from one directory to another in Java

I provided an alternate solution without the need to use a third party, such as apache FileUtils. This can be done through the command line.

I tested this out on Windows and it works for me. A Linux solution follows.

Here I am utilizing Windows xcopy command to copy all files including subdirectories. The parameters that I pass are defined as per below.

  • /e - Copies all subdirectories, even if they are empty.
  • /i - If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes Destination specifies a directory name and creates a new directory. Then, xcopy copies all specified files into the new directory.
  • /h - Copies files with hidden and system file attributes. By default, xcopy does not copy hidden or system files

My example(s) utilizes the ProcessBuilder class to construct a process to execute the copy(xcopy & cp) commands.

Windows:

String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Linux:

String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Or a combo that can work on both Windows or Linux environments.

private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;

public static void main(String[] args) {
    if (OS.toLowerCase().contains("windows")) { // setup WINDOWS environment
        src = "C:\\srcDir";
        dest = "C:\\destDir";
        cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");

        System.out.println("on: " + OS);
    } else if (OS.toLowerCase().contains("linux")){ // setup LINUX environment
        src = "srcDir/";
        dest = "~/destDir/";
        cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);

        System.out.println("on: " + OS);
    }

    try {
        Process proc = new ProcessBuilder(cmd).start();
        BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        while ((line = inp.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Listen to port via a Java socket

You need to use a ServerSocket. You can find an explanation here.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Clear input fields on form submit

By this way, you hold a form by his ID and throw all his content. This technic is fastiest.

document.forms["id_form"].reset();

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

What's default HTML/CSS link color?

I am used to Chrome's color so the blue color in Chrome for link is #007bff

Remove warning messages in PHP

If you don't want to show warnings as well as errors use

// Turn off all error reporting
error_reporting(0);

Error Reporting - PHP Manual

Cannot start session without errors in phpMyAdmin

Problem I found in Windows server 2016 was that the permissions were wrong on the temp directory used by PHP. I added IUSR.

How to convert array to a string using methods other than JSON?

Use the implode() function:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

How can I check if a string is null or empty in PowerShell?

Another way to accomplish this in a pure PowerShell way would be to do something like this:

("" -eq ("{0}" -f $val).Trim())

This evaluates successfully for null, empty string, and whitespace. I'm formatting the passed value into an empty string to handle null (otherwise a null will cause an error when the Trim is called). Then just evaluate equality with an empty string. I think I still prefer the IsNullOrWhiteSpace, but if you're looking for another way to do it, this will work.

$val = null    
("" -eq ("{0}" -f $val).Trim())
>True
$val = "      "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False

In a fit of boredom, I played with this some and made it shorter (albeit more cryptic):

!!(("$val").Trim())

or

!(("$val").Trim())

depending on what you're trying to do.

C++ pass an array by reference

If you want to modify just the elements:

void foo(double *bar);

is enough.

If you want to modify the address to (e.g.: realloc), but it doesn't work for arrays:

void foo(double *&bar);

is the correct form.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Pageable has an option to specify sort as well. From the java doc

PageRequest(int page, int size, Sort.Direction direction, String... properties) 

Creates a new PageRequest with sort parameters applied.

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

Get full path of a file with FileUpload Control

Check this post under FileUpload Control

Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

Its an option under Internet security that can be enabled

Powershell Log Off Remote Session

This is oldschool and predates PowerShell, but I have used the qwinsta / rwinsta combo for YEARS to remotely log off stale RDP sessions. It's built in on at least Windows XP and forward (possibly earlier)

Determine the session ID:

qwinsta /SERVER:<NAME>

Remove the session in question:

rwinsta <SESSION_ID> /SERVER:<NAME>

How do I capture response of form.submit

 $(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            url : "<wiki:action path='/your struts action'/>",//path of url where u want to submit form
            type : "POST",
            data : $(this).serialize(),
            success : function(data) {
                var treeMenuFrame = parent.frames['wikiMenu'];
                if (treeMenuFrame) {
                    treeMenuFrame.location.href = treeMenuFrame.location.href;
                }
                var contentFrame = parent.frames['wikiContent'];
                contentFrame.document.open();
                contentFrame.document.write(data);
                contentFrame.document.close();
            }
        });
    });
});

First of all use $(document).ready(function()) inside this use ('formid').submit(function(event)) and then prevent default action after that call ajax form submission $.ajax({, , , , });

It will take parameter u can choose according your requirement then call a function

success:function(data) {
    // do whatever you want my example to put response html on div 
}

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to horizontally align ul to center of div?

You can check this solved your problem...

    #headermenu ul{ 
        text-align: center;
    }
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    }
    #headermenu ul li a{
        float: left;
    }

http://jsfiddle.net/thirtydot/VCZgW/

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

In Spring 5

@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {

    // import org.springframework.util.MultiValueMap;

    String datax = (String) body .getFirst("datax");
}

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

Regex to get string between curly braces

Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

Intellij idea subversion checkout error: `Cannot run program "svn"`

I solved this by uncheking the "Use command-line client" option from Subversion settings.

This works with version 1.6 and 1.7 only. See @Vic's answer for SVN version 1.8.

How to calculate the difference between two dates using PHP?

I found your article on the following page, which contains a number of references for PHP date time calculations.

Calculate the difference between two Dates (and time) using PHP. The following page provides a range of different methods (7 in total) for performing date / time calculations using PHP, to determine the difference in time (hours, munites), days, months or years between two dates.

See PHP Date Time – 7 Methods to Calculate the Difference between 2 dates.

What exactly is the meaning of an API?

1) What is an API?

API is a contract. A promise to perform described services when asked in specific ways.

2) How is it used?

According to the rules specified in the contract. The whole point of an API is to define how it's used.

3) When and where is it used?

It's used when 2 or more separate systems need to work together to achieve something they can't do alone.

How do I convert a number to a letter in Java?

This isn't exactly an answer, but some useful/related code I made. When you run it and enter any character in the command line it returns getNumericValue(char) ... which doesn't seem to be the same as the ASCII table so be aware. Anyways, not a direct answer to your question but hopefully helpful:

import java.lang.*;
import java.util.*;
/* charVal.java
         */

//infinite loops. whenever you type in a character gives you value of 
//getNumericValue(char)
//
//ctrl+c to exit



public class charVal {
   public static void main(String[] args) {
     Scanner inPut = new Scanner(System.in);
     for(;;){
       char c = inPut.next().charAt(0);
       System.out.printf("\n %s = %d \n", c, Character.getNumericValue(c));
     }
    }
}

How to access remote server with local phpMyAdmin client?

Method 1 ( for multiserver )

First , lets make a backup of original config.

sudo cp /etc/phpmyadmin/config.inc.php      ~/ 

Now in /usr/share/doc/phpmyadmin/examples/ you will see a file config.manyhosts.inc.php. Just copy in to /etc/phpmyadmin/ using command bellow:

sudo cp /usr/share/doc/phpmyadmin/examples/config.manyhosts.inc.php \
        /etc/phpmyadmin/config.inc.php

Edit the config.inc.php

sudo nano /etc/phpmyadmin/config.inc.php 

Search for :

$hosts = array (
    "foo.example.com",
    "bar.example.com",
    "baz.example.com",
    "quux.example.com",
);

And add your ip or hostname array save ( in nano CTRL+X press Y ) and exit . Done

Method 2 ( single server ) Edit the config.inc.php

sudo nano /etc/phpmyadmin/config.inc.php 

Search for :

/* Server parameters */
if (empty($dbserver)) $dbserver = 'localhost';
$cfg['Servers'][$i]['host'] = $dbserver;

if (!empty($dbport) || $dbserver != 'localhost') {
    $cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['port'] = $dbport;
}

And replace with:

$cfg['Servers'][$i]['host'] = '192.168.1.100';
$cfg['Servers'][$i]['port'] = '3306';

Remeber to replace 192.168.1.100 with your own mysql ip server.

Sorry for my bad English ( google translate have the blame :D )

Click event doesn't work on dynamically generated elements

The problem you have is that you're attempting to bind the "test" class to the event before there is anything with a "test" class in the DOM. Although it may seem like this is all dynamic, what is really happening is JQuery makes a pass over the DOM and wires up the click event when the ready() function fired, which happens before you created the "Click Me" in your button event.

By adding the "test" Click event to the "button" click handler it will wire it up after the correct element exists in the DOM.

<script type="text/javascript">
    $(document).ready(function(){                          
        $("button").click(function(){                                  
            $("h2").html("<p class='test'>click me</p>")                          
            $(".test").click(function(){                          
                alert()                          
            });       
        });                                     
    });
</script>

Using live() (as others have pointed out) is another way to do this but I felt it was also a good idea to point out the minor error in your JS code. What you wrote wasn't wrong, it just needed to be correctly scoped. Grasping how the DOM and JS works is one of the tricky things for many traditional developers to wrap their head around.

live() is a cleaner way to handle this and in most cases is the correct way to go. It essentially is watching the DOM and re-wiring things whenever the elements within it change.

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Under normal conditions, at least 3379 MB of disk space is needed. If you do not have that much space, to lower this requirement;

mongod.exe --smallfiles

This is not the only requirement. But this may be your problem.

Add st, nd, rd and th (ordinal) suffix to a number

Here is another option.

_x000D_
_x000D_
function getOrdinalSuffix(day) {_x000D_
        _x000D_
    if(/^[2-3]?1$/.test(day)){_x000D_
     return 'st';_x000D_
    } else if(/^[2-3]?2$/.test(day)){_x000D_
     return 'nd';_x000D_
    } else if(/^[2-3]?3$/.test(day)){_x000D_
     return 'rd';_x000D_
    } else {_x000D_
     return 'th';_x000D_
    }_x000D_
        _x000D_
}_x000D_
    _x000D_
console.log(getOrdinalSuffix('1'));_x000D_
console.log(getOrdinalSuffix('13'));_x000D_
console.log(getOrdinalSuffix('22'));_x000D_
console.log(getOrdinalSuffix('33'));
_x000D_
_x000D_
_x000D_

Notice the exception for the teens? Teens are so akward!

Edit: Forgot about 11th and 12th

How to draw a graph in LaTeX?

I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics to include those.

If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en

jQuery `.is(":visible")` not working in Chrome

If you read the jquery docs, there are numerous reasons for something to not be considered visible/hidden:

They have a CSS display value of none.

They are form elements with type="hidden".

Their width and height are explicitly set to 0.

An ancestor element is hidden, so the element is not shown on the page.

http://api.jquery.com/visible-selector/

Here's a small jsfiddle example with one visible and one hidden element:

http://jsfiddle.net/tNjLb/

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Angular 2 Scroll to bottom (Chat style)

If you want to be sure, that you are scrolling to the end after *ngFor is done, you can use this.

<div #myList>
 <div *ngFor="let item of items; let last = last">
  {{item.title}}
  {{last ? scrollToBottom() : ''}}
 </div>
</div>

scrollToBottom() {
 this.myList.nativeElement.scrollTop = this.myList.nativeElement.scrollHeight;
}

Important here, the "last" variable defines if you are currently at the last item, so you can trigger the "scrollToBottom" method

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

Classpath including JAR within a JAR

You need to build a custom class-loader to do this or a third-party library that supports this. Your best bet is to extract the jar from the runtime and add them to the classpath (or have them already added to the classpath).

Can someone explain how to append an element to an array in C programming?

For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.

But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:

#include <stdio.h>
#include <string.h>

int main(void)
{

int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};

// 5 is the number of the elements which are going to be appended
memcpy(a + 5, b, 5 * sizeof(int));

// loop through and print all the array
for (i = 0; i < 10; i++) {
    printf("%d\n", a[i]);
  }

}

Run/install/debug Android applications over Wi-Fi?

To complete the answer of @usethe4ce, if you have more than one device or emulators, the adb tcpip 5555 will give error: more than one device/emulator.

In this case you need to give the serial number of the desired device:

  1. adb devices

    List of devices attached

    33001229 device

    emulator-5554 device

  2. adb -s 33001229 tcpip 5555
  3. Find your device's IP in my case I can find it from the device's wifi connected settings.
  4. adb connect xxx.xxx.xxx.xxx:5555

write a shell script to ssh to a remote machine and execute commands

If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.

You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo is also supported.

Remove all values within one list from another list?

>>> a = range(1, 10)
>>> [x for x in a if x not in [2, 3, 7]]
[1, 4, 5, 6, 8, 9]

How to set default value for form field in Symfony2?

Just so I understand the problem.

You want to adjust the way the form is built based on data in your entity. If the entity is being created then use some default value. If the entity is existing use the database value.

Personally, I think @MolecularMans's solution is the way to go. I would actually set the default values in the constructor or in the property statement. But you don't seem to like that approach.

Instead you can follow this: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

You hang a listener on your form type and you can then examine your entity and adjust the builder->add statements accordingly based on havine a new or existing entity. You still need to specify your default values somewhere though you could just code them in your listener. Or pass them into the form type.

Seems like a lot of work though. Better to just pass the entity to the form with it's default values already set.

What is the best algorithm for overriding GetHashCode?

Here is my hashcode helper.
It's advantage is that it uses generic type arguments and therefore will not cause boxing:

public static class HashHelper
{
    public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
    {
         unchecked
         {
             return 31 * arg1.GetHashCode() + arg2.GetHashCode();
         }
    }

    public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            return 31 * hash + arg3.GetHashCode();
        }
    }

    public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, 
        T4 arg4)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            hash = 31 * hash + arg3.GetHashCode();
            return 31 * hash + arg4.GetHashCode();
        }
    }

    public static int GetHashCode<T>(T[] list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    public static int GetHashCode<T>(IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    /// <summary>
    /// Gets a hashcode for a collection for that the order of items 
    /// does not matter.
    /// So {1, 2, 3} and {3, 2, 1} will get same hash code.
    /// </summary>
    public static int GetHashCodeForOrderNoMatterCollection<T>(
        IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            int count = 0;
            foreach (var item in list)
            {
                hash += item.GetHashCode();
                count++;
            }
            return 31 * hash + count.GetHashCode();
        }
    }

    /// <summary>
    /// Alternative way to get a hashcode is to use a fluent 
    /// interface like this:<br />
    /// return 0.CombineHashCode(field1).CombineHashCode(field2).
    ///     CombineHashCode(field3);
    /// </summary>
    public static int CombineHashCode<T>(this int hashCode, T arg)
    {
        unchecked
        {
            return 31 * hashCode + arg.GetHashCode();   
        }
    }

Also it has extension method to provide a fluent interface, so you can use it like this:

public override int GetHashCode()
{
    return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);
}

or like this:

public override int GetHashCode()
{
    return 0.CombineHashCode(Manufacturer)
        .CombineHashCode(PartN)
        .CombineHashCode(Quantity);
}

How can I see what I am about to push with git?

  1. If you have write permissions on remote
git push --dry-run
  1. If you do not have write permissions on remote
git diff --stat HEAD remote/branch

class << self idiom in Ruby

In fact if you write any C extensions for your Ruby projects there is really only one way to define a Module method.

rb_define_singleton_method

I know this self business just opens up all kinds of other questions so you could do better by searching each part.

Objects first.

foo = Object.new

Can I make a method for foo?

Sure

def foo.hello
 'hello'
end

What do I do with it?

foo.hello
 ==>"hello"

Just another object.

foo.methods

You get all the Object methods plus your new one.

def foo.self
 self
end

foo.self

Just the foo Object.

Try to see what happens if you make foo from other Objects like Class and Module. The examples from all the answers are nice to play with but you have to work with different ideas or concepts to really understand what is going on with the way the code is written. So now you have lots of terms to go look at.

Singleton, Class, Module, self, Object, and Eigenclass was brought up but Ruby doesn't name Object Models that way. It's more like Metaclass. Richard or __why shows you the idea here. http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html And if the blows you away then try looking up Ruby Object Model in search. Two videos that I know of on YouTube are Dave Thomas and Peter Cooper. They try to explain that concept too. It took Dave a long time to get it so don't worry. I'm still working on it too. Why else would I be here? Thanks for your question. Also take a look at the standard library. It has a Singleton Module just as an FYI.

This is pretty good. https://www.youtube.com/watch?v=i4uiyWA8eFk

Filter by process/PID in Wireshark

Use Microsoft Message Analyzer v1.4

Navigate to ProcessId from the field chooser.

Etw
-> EtwProviderMsg
--> EventRecord
---> Header
----> ProcessId

Right click and Add as Column

Is it a good practice to place C++ definitions in header files?

Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers.

There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile times since all code has to be processed every time it is included by the compiler.

Finally, it is often annoying to have circular object relationships (sometimes desired) when all the code is the headers.

Bottom line, you were right, he is wrong.

EDIT: I have been thinking about your question. There is one case where what he says is true. templates. Many newer "modern" libraries such as boost make heavy use of templates and often are "header only." However, this should only be done when dealing with templates as it is the only way to do it when dealing with them.

EDIT: Some people would like a little more clarification, here's some thoughts on the downsides to writing "header only" code:

If you search around, you will see quite a lot of people trying to find a way to reduce compile times when dealing with boost. For example: How to reduce compilation times with Boost Asio, which is seeing a 14s compile of a single 1K file with boost included. 14s may not seem to be "exploding", but it is certainly a lot longer than typical and can add up quite quickly. When dealing with a large project. Header only libraries do affect compile times in a quite measurable way. We just tolerate it because boost is so useful.

Additionally, there are many things which cannot be done in headers only (even boost has libraries you need to link to for certain parts such as threads, filesystem, etc). A Primary example is that you cannot have simple global objects in header only libs (unless you resort to the abomination that is a singleton) as you will run into multiple definition errors. NOTE: C++17's inline variables will make this particular example doable in the future.

As a final point, when using boost as an example of header only code, a huge detail often gets missed.

Boost is library, not user level code. so it doesn't change that often. In user code, if you put everything in headers, every little change will cause you to have to recompile the entire project. That's a monumental waste of time (and is not the case for libraries that don't change from compile to compile). When you split things between header/source and better yet, use forward declarations to reduce includes, you can save hours of recompiling when added up across a day.

Giving a border to an HTML table row, <tr>

After fighting with this for a long time I have concluded that the spectacularly simple answer is to just fill the table with empty cells to pad out every row of the table to the same number of cells (taking colspan into account, obviously). With computer-generated HTML this is very simple to arrange, and avoids fighting with complex workarounds. Illustration follows:

<h3>Table borders belong to cells, and aren't present if there is no cell</h3>
<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>


<h3>Simple solution, artificially insert empty cells</h3>

<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only<td><td>
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only<td>
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>

How do you set a JavaScript onclick event to a class with css

It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:

$(document).ready(function(){
  $("a").click(function(){
    alert("hohoho");
  });
});

how to check redis instance version?

There are two commands, which you can use to check the version of redis

    redis-server -v

or

    redis-server --version

How to empty the message in a text area with jquery?

.html(''). was the only method that solved it for me.

How can I open Windows Explorer to a certain directory from within a WPF app?

Process.Start("explorer.exe" , @"C:\Users");

I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.

How can I install a previous version of Python 3 in macOS using homebrew?

I tried all the answers above to install Python 3.4.4. The installation of python worked, but PIP would not be installed and nothing I could do to make it work. I was using Mac OSX Mojave, which cause some issues with zlib, openssl.

What not to do:

  • Try to avoid using Homebrew for previous version given by the formula Python or Python3.
  • Do not try to compile Python

Solution:

  1. Download the macOS 64-bit installer or macOS 64-bit/32-bit installer: https://www.python.org/downloads/release/python-365/
  2. In previous step, it will download Python 3.6.5, if for example, you want to download Python 3.4.4, replace in the url above python-365 by python-344
  3. Download click on the file you downloaded a GUI installer will open
  4. If you downloaded python-365, after installation, to launch this version of python, you will type in your terminal python365, same thing for pip, it will be pip365

p.s: You don't have to uninstall your other version of Python on your system.


Edit:


I found a much much much better solution that work on MacOSX, Windows, Linux, etc.

  1. It doesn't matter if you have already python installed or not.
  2. Download Anaconda
  3. Once installed, in terminal type: conda init
  4. In terminal,create virtual environment with any python version, for example, I picked 3.4.4: conda create -n [NameOfYour VirtualEnvironment] python=3.4.4
  5. Then, in terminal, you can check all the virtual environment you ahave created with the command: conda info --envs
  6. Then, in terminal, activate the virtual environment of your choice with: conda activate [The name of your virtual environment that was shown with the command at step 5]

Unzipping files

I'm using zip.js and it seems to be quite useful. It's worth a look!

Check the Unzip demo, for example.

Difference between dict.clear() and assigning {} in Python

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

Resize iframe height according to content height in it

Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.

In terms of the height, you could also try height=100% on the iframe tag.

Fully custom validation error message with Rails

In the custom validation method use:

errors.add(:base, "Custom error message")

as add_to_base has been deprecated.

errors.add_to_base("Custom error message")

Javascript to Select Multiple options

A pure javascript solution

<select id="choice" multiple="multiple">
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<script type="text/javascript">

var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) != -1 )
  {
    o.selected = true;
  }
}

</script>

Although I agree this should be done server-side.

Errors in pom.xml with dependencies (Missing artifact...)

I know it is an old question. But I hope my answer will help somebody. I had the same issue and I think the problem is that it cannot find those .jar files in your local repository. So what I did is I added the following code to my pom.xml and it worked.

<repositories>
  <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/libs-milestone</url>
      <snapshots>
          <enabled>false</enabled>
      </snapshots>
  </repository>
</repositories>

Trying to detect browser close event

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


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

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script> 

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

Key hash for Android-Facebook app

  • download openSSL for windows in here you can find 64bit and 32bit here

  • extract the downloaded file

  • create folder name openSSL in C drive
  • copy all the extracted items in to openSSL folder (bin,include,lib,openssl.cnf)
  • get android debug keystore, default location will be

C:\Users\username\.android\debug.keystore

  • now get your command prompt and paste this code

keytool -exportcert -alias androiddebugkey -keystore C:\Users\username.android\debug.keystore | "C:\openSSL\bin\openssl" sha1 -binary | "C:\openSSL\bin\openssl" base64

  • hit enter and you will get the 28 digit keycode

Python - How to convert JSON File to Dataframe

import pandas as pd
print(pd.json_normalize(your_json))

This will Normalize semi-structured JSON data into a flat table

Output

  FirstName LastName MiddleName password    username
      John     Mark      Lewis     2910  johnlewis2

Windows Batch Files: if else

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

How to set textColor of UILabel in Swift

This code example that follows shows a basic UILabel configuration.

let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200))
lbl.text = "yourString"

// Enum type, two variations:
lbl.textAlignment = NSTextAlignment.Right
lbl.textAlignment = .Right

lbl.textColor = UIColor.red
lbl.shadowColor = UIColor.black
lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(lbl)

Uncaught TypeError: undefined is not a function while using jQuery UI

You may see if you are not loading jQuery twice somehow. Especially after your plugin JavaScript file loaded.

I has the same error and found that one of my external PHP files was loading jQuery again.

JAVA_HOME and PATH are set but java -version still shows the old one

In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java this jdk_home.sh file kept overriding the $PATH on boot-up.

how to force maven to update local repo

You can also use this command on the command line:

mvn dependency:purge-local-repository clean install

How do we check if a pointer is NULL pointer?

The actual representation of a null pointer is irrelevant here. An integer literal with value zero (including 0 and any valid definition of NULL) can be converted to any pointer type, giving a null pointer, whatever the actual representation. So p != NULL, p != 0 and p are all valid tests for a non-null pointer.

You might run into problems with non-zero representations of the null pointer if you wrote something twisted like p != reinterpret_cast<void*>(0), so don't do that.

Although I've just noticed that your question is tagged C as well as C++. My answer refers to C++, and other languages may be different. Which language are you using?

How to check if a DateTime field is not null or empty?

If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:

DateTime dat = new DateTime();

 if (dat==DateTime.MinValue)
 {
     //unassigned
 }

If the DateTime is nullable, well that's a different story:

 DateTime? dat = null;

 if (!dat.HasValue)
 {
     //unassigned
 }

Java random numbers using a seed

You shouldn't be creating a new Random in method scope. Make it a class member:

public class Foo {
   private Random random 

   public Foo() {
       this(System.currentTimeMillis());
   }

   public Foo(long seed) {
       this.random = new Random(seed);
   }

   public synchronized double getNext() {
        return generator.nextDouble();
   }
}

This is only an example. I don't think wrapping Random this way adds any value. Put it in a class of yours that is using it.

Create request with POST, which response codes 200 or 201 and content

The output is actually dependent on the content type being requested. However, at minimum you should put the resource that was created in Location. Just like the Post-Redirect-Get pattern.

In my case I leave it blank until requested otherwise. Since that is the behavior of JAX-RS when using Response.created().

However, just note that browsers and frameworks like Angular do not follow 201's automatically. I have noted the behaviour in http://www.trajano.net/2013/05/201-created-with-angular-resource/

How can I search (case-insensitive) in a column using LIKE wildcard?

I'm doing something like that.

Getting the values in lowercase and MySQL does the rest

    $string = $_GET['string'];
    mysqli_query($con,"SELECT *
                       FROM table_name
                       WHERE LOWER(column_name)
                       LIKE LOWER('%$string%')");

And For MySQL PDO Alternative:

        $string = $_GET['string'];
        $q = "SELECT *
              FROM table_name
              WHERE LOWER(column_name)
              LIKE LOWER(?);";
        $query = $dbConnection->prepare($q);
        $query->bindValue(1, "%$string%", PDO::PARAM_STR);
        $query->execute();

How to get current local date and time in Kotlin

Another solution is changing the api level of your project in build.gradle and this will work.

How to share my Docker-Image without using the Docker-Hub?

Based on this blog, one could share a docker image without a docker registry by executing:

docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0

Once this command has been completed, one could copy the image to a server and import it as follows:

docker load --input latestversion-1.0.0.tar

position fixed is not working

We'll never convince people to leave IE6 if we keep striving to deliver quality websites to those users.

Only IE7+ understood "position: fixed".

https://developer.mozilla.org/en-US/docs/Web/CSS/position

So you're out of luck for IE6. To get the footer semi-sticky try this:

.main {
  min-height: 100%;
  margin-bottom: -60px;
}
.footer {
  height: 60px;
}

You could also use an iFrame maybe.

This will keep the footer from 'lifting off' from the bottom of the page. If you have more than one page of content then it will push down out of site.

On a philosophical note, I'd rather point IE6 users to http://browsehappy.com/ and spend the time I save hacking for IE6 on something else.

What is the Windows version of cron?

There is NNCron for Windows. IT can schedule jobs to be run periodically.

chai test array equality doesn't work as expected

import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.

How do I move focus to next input with jQuery?

  function nextFormInput() {
      var focused = $(':focus');
      var inputs = $(focused).closest('form').find(':input');
      inputs.eq(inputs.index(focused) + 1).focus();
  }

Recursion or Iteration?

I'm going to answer your question by designing a Haskell data structure by "induction", which is a sort of "dual" to recursion. And then I will show how this duality leads to nice things.

We introduce a type for a simple tree:

data Tree a = Branch (Tree a) (Tree a)
            | Leaf a
            deriving (Eq)

We can read this definition as saying "A tree is a Branch (which contains two trees) or is a leaf (which contains a data value)". So the leaf is a sort of minimal case. If a tree isn't a leaf, then it must be a compound tree containing two trees. These are the only cases.

Let's make a tree:

example :: Tree Int
example = Branch (Leaf 1) 
                 (Branch (Leaf 2) 
                         (Leaf 3))

Now, let's suppose we want to add 1 to each value in the tree. We can do this by calling:

addOne :: Tree Int -> Tree Int
addOne (Branch a b) = Branch (addOne a) (addOne b)
addOne (Leaf a)     = Leaf (a + 1)

First, notice that this is in fact a recursive definition. It takes the data constructors Branch and Leaf as cases (and since Leaf is minimal and these are the only possible cases), we are sure that the function will terminate.

What would it take to write addOne in an iterative style? What will looping into an arbitrary number of branches look like?

Also, this kind of recursion can often be factored out, in terms of a "functor". We can make Trees into Functors by defining:

instance Functor Tree where fmap f (Leaf a)     = Leaf (f a)
                            fmap f (Branch a b) = Branch (fmap f a) (fmap f b)

and defining:

addOne' = fmap (+1)

We can factor out other recursion schemes, such as the catamorphism (or fold) for an algebraic data type. Using a catamorphism, we can write:

addOne'' = cata go where
           go (Leaf a) = Leaf (a + 1)
           go (Branch a b) = Branch a b

Abort a git cherry-pick?

You can do the following

git cherry-pick --abort

From the git cherry-pick docs

--abort  

Cancel the operation and return to the pre-sequence state.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

When should I use mmap for file access?

One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.

Jquery asp.net Button Click Event via ajax

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

How do I add a newline to command output in PowerShell?

Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file:

$OFS = "`r`n`r`n"
"$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall | 
    ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" | 
 out-file addrem.txt

Beware to use the ` and not the '. On my keyboard (US-English Qwerty layout) it's located left of the 1.
(Moved here from the comments - Thanks Koen Zomers)

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

Completely Remove MySQL Ubuntu 14.04 LTS

remove mysql :

sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

Restart instance :

sudo shutdown -r now

Django auto_now and auto_now_add

auto_now=True didn't work for me in Django 1.4.1, but the below code saved me. It's for timezone aware datetime.

from django.utils.timezone import get_current_timezone
from datetime import datetime

class EntryVote(models.Model):
    voted_on = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        self.voted_on = datetime.now().replace(tzinfo=get_current_timezone())
        super(EntryVote, self).save(*args, **kwargs)

XAMPP Start automatically on Windows 7 startup

You can put in this directory your Xampp control panel shortcut it will work fine (it will automatically start after windows startup) as @wajahat-hashmi answered above:

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

About aditional windows script or programs that we need to run automatically...

I needed to create some additional scripts to initialize some windows services. If someone has the same need you can put in that same directory, they will all run right after windows startup.

For me, Xampp auto start and other scripts and shortcuts worked fine in windows 8.1, I think it will work fine in any windows version.

I hope it works well for anyone who has the same need.

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

How to check if curl is enabled or disabled

Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -

function isExtensionLoaded($extension_name){
    return extension_loaded($extension_name);
}

Usage

echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');

How to get value of selected radio button?

Another (apparently older) option is to use the format: "document.nameOfTheForm.nameOfTheInput.value;" e.g. document.mainForm.rads.value;

_x000D_
_x000D_
document.mainForm.onclick = function(){_x000D_
    var radVal = document.mainForm.rads.value;_x000D_
    result.innerHTML = 'You selected: '+radVal;_x000D_
}
_x000D_
<form id="mainForm" name="mainForm">_x000D_
    <input type="radio" name="rads" value="1" />_x000D_
    <input type="radio" name="rads" value="2" />_x000D_
    <input type="radio" name="rads" value="3" />_x000D_
    <input type="radio" name="rads" value="4" />_x000D_
</form>_x000D_
<span id="result"></span>
_x000D_
_x000D_
_x000D_

You can refer to the element by its name within a form. Your original HTML does not contain a form element though.

Fiddle here (works in Chrome and Firefox): https://jsfiddle.net/Josh_Shields/23kg3tf4/1/

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

Just for another possibility to check, I came up with exactly the same problem with an incorrect port number specified in connect URL. I created a new oracle11g instance and forgot to kill the former one occupying the same port 1521, so the new instance automatically started on port 1522. Editing port number solved my problem.

Execute JavaScript using Selenium WebDriver in C#

public void javascriptclick(String element)
    { 
        WebElement webElement=driver.findElement(By.xpath(element));
        JavascriptExecutor js = (JavascriptExecutor) driver;

        js.executeScript("arguments[0].click();",webElement);   
        System.out.println("javascriptclick"+" "+ element);

    }

Passing struct to function

The line function implementation should be:

void addStudent(struct student person) {

}

person is not a type but a variable, you cannot use it as the type of a function parameter.

Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.

C++ - How to append a char to char*?

The specific problem is that you're declaring a new variable instead of assigning to an existing one:

char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this

and trying to compare string values by comparing pointers:

if (array!="")     // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string

although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.

The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string and it will manage all the memory allocation for you:

std::string appendCharToString(std::string const & s, char a) {
    return s + a;
}

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

In most housing services just add in the .htaccess on the target server folder this:

Header set Access-Control-Allow-Origin 'https://your.site.folder'

How to read from stdin line by line in Node

In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight, but that's just a random name.

#!/usr/bin/env node

function visible(a) {
    var R  =  ''
    for (var i = 0; i < a.length; i++) {
        if (a[i] == '\b') {  R -= 1; continue; }  
        if (a[i] == '\u001b') {
            while (a[i] != 'm' && i < a.length) i++
            if (a[i] == undefined) break
        }
        else R += a[i]
    }
    return  R
}

function empty(a) {
    a = visible(a)
    for (var i = 0; i < a.length; i++) {
        if (a[i] != ' ') return false
    }
    return  true
}

var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })

rl.on('line', function(line) {
    if (!empty(line)) console.log(line) 
})

Retrieving subfolders names in S3 bucket from boto3

The following works for me... S3 objects:

s3://bucket/
    form1/
       section11/
          file111
          file112
       section12/
          file121
    form2/
       section21/
          file211
          file112
       section22/
          file221
          file222
          ...
      ...
   ...

Using:

from boto3.session import Session
s3client = session.client('s3')
resp = s3client.list_objects(Bucket=bucket, Prefix='', Delimiter="/")
forms = [x['Prefix'] for x in resp['CommonPrefixes']] 

we get:

form1/
form2/
...

With:

resp = s3client.list_objects(Bucket=bucket, Prefix='form1/', Delimiter="/")
sections = [x['Prefix'] for x in resp['CommonPrefixes']] 

we get:

form1/section11/
form1/section12/

show/hide a div on hover and hover out

Why not just use .show()/.hide() instead?

$("#menu").hover(function(){
    $('.flyout').show();
},function(){
    $('.flyout').hide();
});

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

Creating a Facebook share button with customized url, title and image

This is the code as 2017:

<i class="fa fa-facebook-square"></i>
<a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</a>

Facebook now takes all data from OG metatags.

NOTE: This code assumes you have OG metatags on in site's code.

Source

How to generate unique IDs for form labels in React?

This solutions works fine for me.

utils/newid.js:

let lastId = 0;

export default function(prefix='id') {
    lastId++;
    return `${prefix}${lastId}`;
}

And I can use it like this:

import newId from '../utils/newid';

React.createClass({
    componentWillMount() {
        this.id = newId();
    },
    render() {
        return (
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
        );
    }
});

But it won’t work in isomorphic apps.

Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

Updated 28.01.2016. It’s better to generate ID in componentWillMount.

JSON.parse vs. eval()

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

WPF Datagrid Get Selected Cell Value

I was to dumb to find the Solution...

For me (VB):

 Dim string= Datagrid.SelectedCells(0).Item(0).ToString

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

How to set 'X-Frame-Options' on iframe?

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

For More Information: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

I have an alternate solution for this problem, which I am going to demonstrate by using PHP:

iframe.php:

<iframe src="target_url.php" width="925" height="2400" frameborder="0" ></iframe>

target_url.php:

<?php 
  echo file_get_contents("http://www.example.com");
?>

How to get the onclick calling object?

I think the best way is to use currentTarget property instead of target property.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.


For example:

<a href="#"><span class="icon"></span> blah blah</a>

Javascript:

a.addEventListener('click', e => {
    e.currentTarget; // always returns "a" element
    e.target; // may return "a" or "span"
})

How to update/upgrade a package using pip?

To upgrade pip for Python3.4+, you must use pip3 as follows:

sudo pip3 install pip --upgrade

This will upgrade pip located at: /usr/local/lib/python3.X/dist-packages

Otherwise, to upgrade pip for Python2.7, you would use pip as follows:

sudo pip install pip --upgrade

This will upgrade pip located at: /usr/local/lib/python2.7/dist-packages

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

NSRange to Range<String.Index>

This answer by Martin R seems to be correct because it accounts for Unicode.

However at the time of the post (Swift 1) his code doesn't compile in Swift 2.0 (Xcode 7), because they removed advance() function. Updated version is below:

Swift 2

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
        let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

Swift 3

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        if let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

Swift 4

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        return Range(nsRange, in: self)
    }
}

How to run iPhone emulator WITHOUT starting Xcode?

You can get it to launch via spotlight if you create an Automator launcher for it:

  1. Open Automator.app
  2. Choose type of Application
  3. Select Actions > Library > Utilities > Launch Application
  4. Open the dropdown of applications that can be launched and choose Other
  5. You can't directly select the Simulator app because it's inside the Xcode.app package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
    • /Applications/Xcode.app/Contents/Developer/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
  6. Finally, save this Automator app in your applications folder as iOS Simulator.app

Create Automator app

To get a nice icon for the Automator app you just made, you can do the following:

  1. Right click iOS Simulator.app and choose Get Info
  2. Click the icon in the upper left corner and do Cmd-C to copy it
  3. Right click your Automator app and choose Get Info
  4. Click the icon in the upper left corner and do Cmd-V to paste

Copy icon

Python - How do you run a .py file?

On windows platform, you have 2 choices:

  1. In a command line terminal, type

    c:\python23\python xxxx.py

  2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.

For your posted code, the error is at this line:

def main(url, out_folder="C:\asdf\"):

It should be:

def main(url, out_folder="C:\\asdf\\"):

Filter LogCat to get only the messages from My Application in Android?

ADT v15 for Eclipse let you specify an application name (which is actually the package value in your androidmanifest.xml).

I love being able to filter by app, but the new logcat has a bug with the autoscroll. When you scroll up a little to look at previous logs, it automatically scrolls back to the bottom in a couple seconds. It seems scrolling 1/2 way up the log does keep it from jumping back to the bottom, but that's often useless.

EDIT: I tried specifying an app filter from the command-line -- but no luck. If someone figures this out OR how to stop the autoscroll, please let me know.

Make Bootstrap 3 Tabs Responsive

I have created a directive in agularJS supported with ng-bootStrap components

https://angular-ui.github.io/bootstrap/#!#tabs

here I share the code that I implemented

[https://jsfiddle.net/k1r02/u6gpv4dc/][1]

  [1]: https://jsfiddle.net/k1r02/u6gpv4dc/

PostgreSQL: export resulting data from SQL query to Excel/CSV

Several GUI tools like Squirrel, SQL Workbench/J, AnySQL, ExecuteQuery can export to Excel files.

Most of those tools are listed in the PostgreSQL wiki:

http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

How does data binding work in AngularJS?

This is my basic understanding. It may well be wrong!

  1. Items are watched by passing a function (returning the thing to be watched) to the $watch method.
  2. Changes to watched items must be made within a block of code wrapped by the $apply method.
  3. At the end of the $apply the $digest method is invoked which goes through each of the watches and checks to see if they changed since last time the $digest ran.
  4. If any changes are found then the digest is invoked again until all changes stabilize.

In normal development, data-binding syntax in the HTML tells the AngularJS compiler to create the watches for you and controller methods are run inside $apply already. So to the application developer it is all transparent.

How to convert a char to a String?

Use the Character.toString() method like so:

char mChar = 'l';
String s = Character.toString(mChar);

Is it possible to deserialize XML into List<T>?

Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.

[Serializable]
public class A
{
    [XmlArray]
    public List<string> strings;
}

This works with both Serialize() and Deserialize().

How to check if the user can go back in browser history or not

You can't directly check whether the back button is usable. You can look at history.length>0, but that will hold true if there are pages ahead of the current page as well. You can only be sure that the back button is unusable when history.length===0.

If that's not good enough, about all you can do is call history.back() and, if your page is still loaded afterwards, the back button is unavailable! Of course that means if the back button is available, you've just navigated away from the page. You aren't allowed to cancel the navigation in onunload, so about all you can do to stop the back actually happening is to return something from onbeforeunload, which will result in a big annoying prompt appearing. It's not worth it.

In fact it's normally a Really Bad Idea to be doing anything with the history. History navigation is for browser chrome, not web pages. Adding “go back” links typically causes more user confusion than it's worth.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Simple steps (using git + hub => GitHub):

  1. Install Hub (GitHub).

    • OS X: brew install hub
    • having Go: go get github.com/github/hub
    • otherwise (having Go as well):

      git clone https://github.com/github/hub.git && cd hub && ./script/build
      
  2. Go to your repo or create empty one: mkdir foo && cd foo && git init.

  3. Run: hub create, it'll ask you about GitHub credentials for the first time.

    Usage: hub create [-p] [-d DESCRIPTION] [-h HOMEPAGE] [NAME]

    Example: hub create -d Description -h example.com org_name/foo_repo

    Hub will prompt for GitHub username & password the first time it needs to access the API and exchange it for an OAuth token, which it saves in ~/.config/hub.

    To explicitly name the new repository, pass in NAME, optionally in ORGANIZATION/NAME form to create under an organization you're a member of.

    With -p, create a private repository, and with -d and -h set the repository's description and homepage URL, respectively.

    To avoid being prompted, use GITHUB_USER and GITHUB_PASSWORD environment variables.

  4. Then commit and push as usual or check hub commit/hub push.

For more help, run: hub help.

See also: Importing a Git repository using the command line at GitHub.

Can I use a binary literal in C or C++?

A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:

#define B_0000    0
#define B_0001    1
#define B_0010    2
#define B_0011    3
#define B_0100    4
#define B_0101    5
#define B_0110    6
#define B_0111    7
#define B_1000    8
#define B_1001    9
#define B_1010    a
#define B_1011    b
#define B_1100    c
#define B_1101    d
#define B_1110    e
#define B_1111    f

#define _B2H(bits)    B_##bits
#define B2H(bits)    _B2H(bits)
#define _HEX(n)        0x##n
#define HEX(n)        _HEX(n)
#define _CCAT(a,b)    a##b
#define CCAT(a,b)   _CCAT(a,b)

#define BYTE(a,b)        HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d)    HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h)    HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )

// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;

Disadvantages (it's not such a big ones):

  • The binary numbers have to be grouped 4 by 4;
  • The binary literals have to be only unsigned integer numbers;

Advantages:

  • Total preprocessor driven, not spending processor time in pointless operations (like "?.. :..", "<<", "+") to the executable program (it may be performed hundred of times in the final application);
  • It works "mainly in C" compilers and C++ as well (template+enum solution works only in C++ compilers);
  • It has only the limitation of "longness" for expressing "literal constant" values. There would have been earlyish longness limitation (usually 8 bits: 0-255) if one had expressed constant values by parsing resolve of "enum solution" (usually 255 = reach enum definition limit), differently, "literal constant" limitations, in the compiler allows greater numbers;
  • Some other solutions demand exaggerated number of constant definitions (too many defines in my opinion) including long or several header files (in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()");
  • Simplicity of the solution: easily readable, understandable and adjustable for other cases (could be extended for grouping 8 by 8 too);

How to center text vertically with a large font-awesome icon?

This worked well for me.

i.fa {
  line-height: 100%;
}

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

The C# summarized descendant.

More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx

public sealed class ObservableCollectionEx<T> : ObservableCollection<T>
{
    #region Ctor

    public ObservableCollectionEx()
    {
    }

    public ObservableCollectionEx(List<T> list) : base(list)
    {
    }

    public ObservableCollectionEx(IEnumerable<T> collection) : base(collection)
    {
    }

    #endregion

    /// <summary> 
    /// Adds the elements of the specified collection to the end of the ObservableCollection(Of T). 
    /// </summary> 
    public void AddRange(
        IEnumerable<T> itemsToAdd,
        ECollectionChangeNotificationMode notificationMode = ECollectionChangeNotificationMode.Add)
    {
        if (itemsToAdd == null)
        {
            throw new ArgumentNullException("itemsToAdd");
        }
        CheckReentrancy();

        if (notificationMode == ECollectionChangeNotificationMode.Reset)
        {
            foreach (var i in itemsToAdd)
            {
                Items.Add(i);
            }

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            return;
        }

        int startIndex = Count;
        var changedItems = itemsToAdd is List<T> ? (List<T>) itemsToAdd : new List<T>(itemsToAdd);
        foreach (var i in changedItems)
        {
            Items.Add(i);
        }

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
    }

    public enum ECollectionChangeNotificationMode
    {
        /// <summary>
        /// Notifies that only a portion of data was changed and supplies the changed items (not supported by some elements,
        /// like CollectionView class).
        /// </summary>
        Add,

        /// <summary>
        /// Notifies that the entire collection was changed, does not supply the changed items (may be inneficient with large
        /// collections as requires the full update even if a small portion of items was added).
        /// </summary>
        Reset
    }
}

summing two columns in a pandas dataframe

You could also use the .add() function:

 df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])

Use -notlike to filter out multiple strings in PowerShell

V2 at least contains the -username parameter that takes a string[], and supports globbing.

V1 you want to expand your test like so:

Get-EventLog Security | ?{$_.UserName -notlike "user1" -and $_.UserName -notlike "*user2"}

Or you could use "-notcontains" on the inline array but this would only work if you can do exact matching on the usernames.

... | ?{@("user1","user2") -notcontains $_.username}

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

Alphabet range in Python

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

If you really need a list:

>>> list(string.ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

And to do it with range

>>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1)))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Other helpful string module features:

>>> help(string) # on Python 3
....
DATA
    ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
    ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'
    hexdigits = '0123456789abcdefABCDEF'
    octdigits = '01234567'
    printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
    punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
    whitespace = ' \t\n\r\x0b\x0c'

How can I change the image displayed in a UIImageView programmatically?

Note that the NIB file doesn't wire up all the IBOutlets until the view has been added to the scene. If you're wiring things up manually (which you might be doing if things are in separate NIBs) this is important to keep in mind.

So if my test view controller has an "imageView" wired by a nib, this probably won't work:

  testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];
  [self.view addSubview:testCardViewController.view];

But this will:

  [self.view addSubview:testCardViewController.view];
  testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];

How to display (print) vector in Matlab?

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

z-index not working with position absolute

I faced this issue a lot when using position: absolute;, I faced this issue by using position: relative in the child element. don't need to change position: absolute to relative, just need to add in the child element look into the beneath two examples:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

This's how it can be fixed using position relative:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

Sandbox here

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.

How to do this in Laravel, subquery where in

You can use Eloquent in different queries and make things easier to understand and mantain:

$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
                   ->select('product_id'); //don't need ->get() or ->first()

and then we put all together:

Products::whereIn('id', $productCategory)
          ->where('active', 1)
          ->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
          ->get();//runs all queries at once

This will generate the same query that you wrote in your question.

Picking a random element from a set

The easiest with Java 8 is:

outbound.stream().skip(n % outbound.size()).findFirst().get()

where n is a random integer. Of course it is of less performance than that with the for(elem: Col)

Can I replace groups in Java regex?

You can use matcher.start() and matcher.end() methods to get the group positions. So using this positions you can easily replace any text.

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Auto highlight text in a textbox control

Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.

public class AutoSelectAll
{
    public static bool GetIsEnabled(DependencyObject obj) 
    { 
        return (bool)obj.GetValue(IsEnabledProperty); 
    } 
    public static void SetIsEnabled(DependencyObject obj, bool value) 
    { 
        obj.SetValue(IsEnabledProperty, value);
    }

    static void ue_Loaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        ue.GotFocus += ue_GotFocus;
        ue.GotMouseCapture += ue_GotMouseCapture;
    }

    private static void ue_Unloaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        //ue.Unloaded -= ue_Unloaded;
        ue.GotFocus -= ue_GotFocus;
        ue.GotMouseCapture -= ue_GotMouseCapture;
    }

    static void ue_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    static void ue_GotMouseCapture(object sender, MouseEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
        typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));

    static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ue = d as FrameworkElement;
        if (ue == null)
            return;
        if ((bool)e.NewValue)
        {
            ue.Unloaded += ue_Unloaded;
            ue.Loaded += ue_Loaded;
        }
    }
} 

The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.

You can use this by including the following tag in your xaml.

<TextBox  
    Text="{Binding Property}"
    Library:AutoSelectAll.IsEnabled="True" />

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Using #!/usr/bin/env NAME makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

Update Eclipse with Android development tools v. 23

is what they are saying about this:

OK, guys, sorry about all this trouble, and we apologize for the messed up releases. Here's the summary:

Starting with ADT bundle 23.0.2, you should be able to update to future versions of ADT.

Source: https://code.google.com/p/android/issues/detail?id=72912

Wget output document and headers to STDOUT

This worked for me for printing response with header:

wget --server-response http://www.example.com/

Convert a SQL Server datetime to a shorter date format

Just add date keyword. E.g. select date(orderdate),count(1) from orders where orderdate > '2014-10-01' group by date(orderdate);

orderdate is in date time. This query will show the orders for that date rather than datetime.

Date keyword applied on a datetime column will change it to short date.

How to generate unique id in MySQL?

 <?php
    $hostname_conn = "localhost";
    $database_conn = "user_id";
    $username_conn = "root";
    $password_conn = "";
     $conn = mysql_pconnect($hostname_conn, $username_conn,   $password_conn) or trigger_error(mysql_error(),E_USER_ERROR); 
   mysql_select_db($database_conn,$conn);
   // run an endless loop      
    while(1) {       
    $randomNumber = rand(1, 999999);// generate unique random number               
    $query = "SELECT * FROM tbl_rand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'";  // check if it exists in database   
    $res =mysql_query($query,$conn);       
    $rowCount = mysql_num_rows($res);
     // if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
    if($rowCount < 1) {
    $con = mysql_connect ("localhost","root");      
    mysql_select_db("user_id", $con);       
    $sql = "insert into tbl_rand(the_number) values('".$randomNumber."')";      
    mysql_query ($sql,$con);        
    mysql_close ($con);
    break;
    }   
}
  echo "inserted unique number into Data_base. use it as ID";
   ?>

How to add New Column with Value to the Existing DataTable?

Add the column and update all rows in the DataTable, for example:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

val() doesn't trigger change() in jQuery

From https://api.jquery.com/change/:

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

How to handle the `onKeyPress` event in ReactJS?

render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

How to restart Activity in Android

I wonder why no one mentioned Intent.makeRestartActivityTask() which cleanly makes this exact purpose.

Make an Intent that can be used to re-launch an application's task * in its base state.

startActivity(Intent.makeRestartActivityTask(getActivity().getIntent().getComponent()));

This method sets Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK as default flags.

Position absolute and overflow hidden

Make outer <div> to position: relative and inner <div> to position: absolute. It should work for you.

Casting interfaces for deserialization in JSON.NET

For what it's worth, I ended up having to handle this myself for the most part. Each object has a Deserialize(string jsonStream) method. A few snippets of it:

JObject parsedJson = this.ParseJson(jsonStream);
object thingyObjectJson = (object)parsedJson["thing"];
this.Thing = new Thingy(Convert.ToString(thingyObjectJson));

In this case, new Thingy(string) is a constructor that will call the Deserialize(string jsonStream) method of the appropriate concrete type. This scheme will continue to go downward and downward until you get to the base points that json.NET can just handle.

this.Name = (string)parsedJson["name"];
this.CreatedTime = DateTime.Parse((string)parsedJson["created_time"]);

So on and so forth. This setup allowed me to give json.NET setups it can handle without having to refactor a large part of the library itself or using unwieldy try/parse models that would have bogged down our entire library due to the number of objects involved. It also means that I can effectively handle any json changes on a specific object, and I do not need to worry about everything that object touches. It's by no means the ideal solution, but it works quite well from our unit and integration testing.

Iterating over all the keys of a map

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

What is the list of valid @SuppressWarnings warning names in Java?

I just want to add that there is a master list of IntelliJ suppress parameters at: https://gist.github.com/vegaasen/157fbc6dce8545b7f12c

It looks fairly comprehensive. Partial:

Warning Description - Warning Name

"Magic character" MagicCharacter 
"Magic number" MagicNumber 
'Comparator.compare()' method does not use parameter ComparatorMethodParameterNotUsed 
'Connection.prepare*()' call with non-constant string JDBCPrepareStatementWithNonConstantString 
'Iterator.hasNext()' which calls 'next()' IteratorHasNextCallsIteratorNext 
'Iterator.next()' which can't throw 'NoSuchElementException' IteratorNextCanNotThrowNoSuchElementException 
'Statement.execute()' call with non-constant string JDBCExecuteWithNonConstantString 
'String.equals("")' StringEqualsEmptyString 
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) StringBufferMayBeStringBuilder 
'StringBuffer.toString()' in concatenation StringBufferToStringInConcatenation 
'assert' statement AssertStatement 
'assertEquals()' between objects of inconvertible types AssertEqualsBetweenInconvertibleTypes 
'await()' not in loop AwaitNotInLoop 
'await()' without corresponding 'signal()' AwaitWithoutCorrespondingSignal 
'break' statement BreakStatement 
'break' statement with label BreakStatementWithLabel 
'catch' generic class CatchGenericClass 
'clone()' does not call 'super.clone()' CloneDoesntCallSuperClone

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.

Using HTTPS with REST in Java

Something to keep in mind is that this error isn't only due to self signed certs. The new Entrust CA certs fail with the same error, and the right thing to do is to update the server with the appropriate root certs, not to disable this important security feature.

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Can't import database through phpmyadmin file size too large

to import big database into phpmyadmin there are two ways 1 increase file execution size from php.ini 2 use command line to import big database.

How can I add a vertical scrollbar to my div automatically?

You need to assign some height to make the overflow: auto; property work.
For testing purpose, add height: 100px; and check.
and also it will be better if you give overflow-y:auto; instead of overflow: auto;, because this makes the element to scroll only vertical but not horizontal.

float:left;
width:1000px;
overflow-y: auto;
height: 100px;

If you don't know the height of the container and you want to show vertical scrollbar when the container reaches a fixed height say 100px, use max-height instead of height property.

For more information, read this MDN article.

The application may be doing too much work on its main thread

I too had the same problem.
Mine was a case where i was using a background image which was in drawables.That particular image was of approx 130kB and was used during splash screen and home page in my android app.

Solution - I just shifted that particular image to drawables-xxx folder from drawables and was able free a lot of memory occupied in background and the skipping frames were no longer skipping.

Update Use 'nodp' drawable resource folder for storing background drawables files.
Will a density qualified drawable folder or drawable-nodpi take precedence?

Is there a limit on number of tcp/ip connections between machines on linux?

Is your server single-threaded? If so, what polling / multiplexing function are you using?

Using select() does not work beyond the hard-coded maximum file descriptor limit set at compile-time, which is hopeless (normally 256, or a few more).

poll() is better but you will end up with the scalability problem with a large number of FDs repopulating the set each time around the loop.

epoll() should work well up to some other limit which you hit.

10k connections should be easy enough to achieve. Use a recent(ish) 2.6 kernel.

How many client machines did you use? Are you sure you didn't hit a client-side limit?

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Instead of below code:

$(this).attr("src").replace(urlRelative, urlAbsolute);

Use this:

$(this).attr("src",urlAbsolute);

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

What are 'get' and 'set' in Swift?

variable declares and call like this in a class

class X {
    var x: Int = 3

}
var y = X()
print("value of x is: ", y.x)

//value of x is:  3

now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.

class X {
    var _x: Int = 3
    var x: Int {
        get {
            return _x
        }
        set(newVal) {  //set always take 1 argument
            if newVal >= 3 {
             _x = newVal //updating _x with the input value by the user
            print("new value is: ", _x)
            }
            else {
                print("error must be greater than 3")
            }
        }
    }
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8

if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

How to make PDF file downloadable in HTML link?

Try this:

<a href="pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/">Download my eBook</a>

The code inside pdf_server_with_path.php is:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
$path = $_GET["path"];
$fullfile = $path.$file;

header("Content-Disposition: attachment; filename=" . Urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . Filesize($fullfile));
flush(); // this doesn't really matter.
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp);

Setting the focus to a text field

If you create your GUI with Netbeans, you can also insert some self written code. Just select an element (maybe the button, panel or the window) and use the "Code"-tab in the "Properties"-dialog.

There you can insert Pre- and Post- code for various parts of the creation process.

I think the "After-All-Set-Code" field of the window is a good place for your code, or you could bind it to the event ("Properties"-dialog -> "Events") "componentShown" of the text field / panel.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The main problem for causing your table unable to migrate, is that you have running query on your "AppServiceProvider.php" try to check your serviceprovider and disable code for the meantime, and run php artisan migrate

List of all unique characters in a string?

The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

As far as performance goes, worrying about it at this stage sounds like premature optimization.

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Error: Cannot find module 'gulp-sass'

Did you check this question?

May be possible solution is:

rm -rf node_modules/
npm install

How to use string.substr() function?

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2);

?

How to post data in PHP using file_get_contents?

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>