Programs & Examples On #Trafficshaping

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

PHP send mail to multiple email addresses

In mail function you can as many reciepient as you want in $emailto paramater seperated by comma.

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

What is a lambda (function)?

Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.

In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.

For instance (in C#3):

LinqToSqlContext.Where( 
    row => row.FieldName > 15 );

LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.

The statement above becomes:

select ... from [tablename] 
where [FieldName] > 15      --this line was 'read' from the lambda function

This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.

Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:

LinqToSqlContext.Where( 
    row => SomeComplexCheck( row.FieldName ) );

Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through SomeComplexCheck.

Lambda functions should not be confused with anonymous methods. For instance:

LinqToSqlContext.Where( 
    delegate ( DataRow row ) { 
        return row.FieldName > 15; 
    } );

This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.

Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.

Terminal Commands: For loop with echo

By using jot:

jot -w "http://example.com/%d.jpg" 1000 1

Code for download video from Youtube on Java, Android

Ref : Youtube Video Download (Android/Java)

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

Assembly - JG/JNLE/JL/JNGE after CMP

Addition and subtraction in two's complement is the same for signed and unsigned numbers

The key observation is that CMP is basically subtraction, and:

In two's complement (integer representation used by x86), signed and unsigned addition are exactly the same operation

This allows for example hardware developers to implement it more efficiently with just one circuit.

So when you give input bytes to the x86 ADD instruction for example, it does not care if they are signed or not.

However, ADD does set a few flags depending on what happened during the operation:

  • carry: unsigned addition or subtraction result does not fit in bit size, e.g.: 0xFF + 0x01 or 0x00 - 0x01

    For addition, we would need to carry 1 to the next level.

  • sign: result has top bit set. I.e.: is negative if interpreted as signed.

  • overflow: input top bits are both 0 and 0 or 1 and 1 and output inverted is the opposite.

    I.e. signed operation changed sigedness in an impossible way (e.g. positive + positive or negative

We can then interpret those flags in a way that makes comparison match our expectations for signed or unsigned numbers.

This interpretation is exactly what JA vs JG and JB vs JL do for us!

Code example

Here is GNU GAS a code snippet to make this more concrete:

/* 0x0 ==
 *
 * * 0 in 2's complement signed
 * * 0 in 2's complement unsigned
 */
mov $0, %al

/* 0xFF ==
 *
 * *  -1 in 2's complement signed
 * * 255 in 2's complement unsigned
 */
mov $0xFF, %bl

/* Do the operation "Is al < bl?" */
cmp %bl, %al

Note that AT&T syntax is "backwards": mov src, dst. So you have to mentally reverse the operands for the condition codes to make sense with cmp. In Intel syntax, this would be cmp al, bl

After this point, the following jumps would be taken:

  • JB, because 0 < 255
  • JNA, because !(0 > 255)
  • JNL, because !(0 < -1)
  • JG, because 0 > -1

Note how in this particular example the signedness mattered, e.g. JB is taken but not JL.

Runnable example with assertions.

Equals / Negated versions like JLE / JNG are just aliases

By looking at the Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2 section "Jcc - Jump if Condition Is Met" we see that the encodings are identical, for example:

Opcode  Instruction  Description
7E cb   JLE rel8     Jump short if less or equal (ZF=1 or SF ? OF).
7E cb   JNG rel8     Jump short if not greater (ZF=1 or SF ? OF).

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

Rails: update_attribute vs update_attributes

Recently I ran into update_attribute vs. update_attributes and validation issue, so similar names, so different behavior, so confusing.

In order to pass hash to update_attribute and bypass validation you can do:

object = Object.new
object.attributes = {
  field1: 'value',
  field2: 'value2',
  field3: 'value3'
}
object.save!(validate: false)

Android Use Done button on Keyboard to click button

Kotlin and Numeric keyboard

If you are using the numeric keyboard you have to dismiss the keyboard, it will be like:

editText.setOnEditorActionListener { v, actionId, event ->
  if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
      //hide the keyboard
      val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      imm.hideSoftInputFromWindow(windowToken, 0)
      //Take action
      editValue.clearFocus()
      return true
  } else {
      return false
  }
}

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

How to get the first line of a file in a bash script?

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

Populate XDocument from String

How about this...?

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);

This was taken from the MSDN docs for XDocument.Load, found here...

http://msdn.microsoft.com/en-us/library/bb299692.aspx

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

import java.util.Timer;
import java.util.TimerTask;

class Clock {
    private Timer mTimer = new Timer();

    private int mSecondsPassed = 0;
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            mSecondsPassed++;
            System.out.println("Seconds passed: " + mSecondsPassed);
        }
    };

    private void start() {
        mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
    }

    public static void main(String[] args) {
        Clock c = new Clock();
        c.start();
    }
}

How to replace master branch in Git, entirely, from another branch?

You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:

git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks

The result should be your master is now essentially seotweaks.

(-s ours is short for --strategy=ours)

From the docs about the 'ours' strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

When to use reinterpret_cast?

Read the FAQ! Holding C++ data in C can be risky.

In C++, a pointer to an object can be converted to void * without any casts. But it's not true the other way round. You'd need a static_cast to get the original pointer back.

Adding sheets to end of workbook in Excel (normal method not working?)

Be sure to fully qualify your sheets with which workbook they are referencing!

 mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

how to remove css property using javascript?

To change all classes for an element:

document.getElementById("ElementID").className = "CssClass";

To add an additional class to an element:

document.getElementById("ElementID").className += " CssClass";

To check if a class is already applied to an element:

if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )

Sorting a list with stream.sorted() in Java

This might help for people ending up here searching how to sort list alphabetically.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortService {
    public static void main(String[] args) {
        List<TestData> test = new ArrayList<>();
        test.add(prepareTestData("Asmin",1));
        test.add(prepareTestData("saurav",4));
        test.add(prepareTestData("asmin",2));
        test.add(prepareTestData("Saurav",3));

        test.forEach(data-> System.out.println(data));
        /** Output
         *  TestData(name=Asmin, id=1)
         *  TestData(name=saurav, id=4)
         *  TestData(name=asmin, id=2)
         *  TestData(name=Saurav, id=3)
         */

        test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
        test.forEach(data-> System.out.println(data));
        /**Sorted Output
         * TestData(name=Asmin, id=1)
         * TestData(name=asmin, id=2)
         * TestData(name=saurav, id=4)
         * TestData(name=Saurav, id=3)
         */
    }
    private static TestData prepareTestData(String name, int id){
        TestData testData= new TestData();
        testData.setId(id);
        testData.setName(name);
        return testData;
    }
}

@Getter
@Setter
@ToString
class TestData{
    private String name;
    private int id;
}

Setting up Eclipse with JRE Path

Java version used : 1.8 IDE : Eclipse Neon

Adding like the below didn't work for me

-vm [relative java home]/jdk1.8.0_21/bin/javaw.exe

and then when i removed

javaw.exe

it worked, so it will be like

-vm [relative java home]/jdk1.8.0_21/bin/

How to add two strings as if they were numbers?

If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.

const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"

Why are the Level.FINE logging messages not showing?

I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

How to automatically generate unique id in SQL like UID12345678?

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

XAMPP on Windows - Apache not starting

I know this is somewhat of an old topic, but in case anyone reads this in the future...

I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.

Adding a new SQL column with a default value

Try This :)

ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT NOT NULL DEFAULT 0;

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

How to convert uint8 Array to base64 Encoded String?

Here is a JS Function to this:

This function is needed because Chrome doesn't accept a base64 encoded string as value for applicationServerKey in pushManager.subscribe yet https://bugs.chromium.org/p/chromium/issues/detail?id=802280

function urlBase64ToUint8Array(base64String) {
  var padding = '='.repeat((4 - base64String.length % 4) % 4);
  var base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  var rawData = window.atob(base64);
  var outputArray = new Uint8Array(rawData.length);

  for (var i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

How to output (to a log) a multi-level array in a format that is human-readable?

This will help you

echo '<pre>';

$output = print_r($array,1);

echo '</pre>';

EDIT

using echo '<pre>'; is useless, but var_export($var); will do the thing which you are expecting.

Add a new item to a dictionary in Python

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

>>> class Dict(dict):
...     def __add__(self, other):
...         copy = self.copy()
...         copy.update(other)
...         return copy
...     def __radd__(self, other):
...         copy = other.copy()
...         copy.update(self)
...         return copy
... 
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}

Note that this is more overhead then using dict[key] = value or dict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.

xcopy file, rename, suppress "Does xxx specify a file name..." message

Place an asterisk(*) at the end of the destination path to skip the dispute of D and F.

Example:

xcopy "compressedOutput.xml" "../../Execute Scripts/APIAutomation/Libraries/rerunlastfailedbuild.xml*"

Parse an URL in JavaScript

Something like this should work for you. Even if there are multiple query string values then this function should return the value of your desired key.

function getQSValue(url) 
{
    key = 'img_id';
    query_string = url.split('?');
    string_values = query_string[1].split('&');
    for(i=0;  i < string_values.length; i++)
    {
        if( string_values[i].match(key))
            req_value = string_values[i].split('=');    
    }
    return req_value[1];
}

Body set to overflow-y:hidden but page is still scrollable in Chrome

Find out the element which is larger than the body (element which is causing the page to scroll) and just set it's position to fixed. NOTE: I'm not talking to change the position of draggable elements. Draggable elements can be dragged out of body only when there's an element larger than body (mostly in width).

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

How do I get the domain originating the request in express.js?

In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:

// Host: "example.com:3000"
req.hostname
// => "example.com"

See: http://expressjs.com/en/4x/api.html#req.hostname

Function to Calculate Median in SQL Server

Frequently, we may need to calculate Median not just for the whole table, but for aggregates with respect to some ID. In other words, calculate median for each ID in our table, where each ID has many records. (based on the solution edited by @gdoron: good performance and works in many SQL)

SELECT our_id, AVG(1.0 * our_val) as Median
FROM
( SELECT our_id, our_val, 
  COUNT(*) OVER (PARTITION BY our_id) AS cnt,
  ROW_NUMBER() OVER (PARTITION BY our_id ORDER BY our_val) AS rnk
  FROM our_table
) AS x
WHERE rnk IN ((cnt + 1)/2, (cnt + 2)/2) GROUP BY our_id;

Hope it helps.

REST / SOAP endpoints for a WCF service

This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Inside service model

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

EndPoint Behaviour

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>

How do I uniquely identify computers visiting my web site?

Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.

I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.

Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).

A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.

Hope that helps.

What is the difference between Swing and AWT?

The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.

Make anchor link go some pixels above where it's linked to

Put this in style :

.hash_link_tag{margin-top: -50px; position: absolute;}

and use this class in separate div tag before the links, example:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

or use this php code for echo link tag:

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

Pass a PHP string to a JavaScript variable (and escape newlines)

  1. Don’t. Use Ajax, put it in data-* attributes in your HTML, or something else meaningful. Using inline scripts makes your pages bigger, and could be insecure or still allow users to ruin layout, unless…

  2. … you make a safer function:

    function inline_json_encode($obj) {
        return str_replace('<!--', '<\!--', json_encode($obj));
    }
    

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

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

MySQL Great Circle Distance (Haversine formula)

calculate distance in Mysql

 SELECT (6371 * acos(cos(radians(lat2)) * cos(radians(lat1) ) * cos(radians(long1) -radians(long2)) + sin(radians(lat2)) * sin(radians(lat1)))) AS distance

thus distance value will be calculated and anyone can apply as required.

How can I submit form on button click when using preventDefault()?

You need to use

$(this).parents('form').submit()

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

get dictionary value by key

That is not how the TryGetValue works. It returns true or false based on whether the key is found or not, and sets its out parameter to the corresponding value if the key is there.

If you want to check if the key is there or not and do something when it's missing, you need something like this:

bool hasValue = Data_Array.TryGetValue("XML_File", out value);
if (hasValue) {
    xmlfile = value;
} else {
    // do something when the value is not there
}

Get selected option text with JavaScript

Try options

_x000D_
_x000D_
function myNewFunction(sel) {_x000D_
  alert(sel.options[sel.selectedIndex].text);_x000D_
}
_x000D_
<select id="box1" onChange="myNewFunction(this);">_x000D_
  <option value="98">dog</option>_x000D_
  <option value="7122">cat</option>_x000D_
  <option value="142">bird</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

Check if AJAX response data is empty/blank/null/undefined/0

$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        // do console.log(data);
        console.log(data);
        // you'll find that what exactly inside data 
        // I do not prefer alter(data); now because, it does not 
        // completes requirement all the time 
        // After that you can easily put if condition that you do not want like
        // if(data != '')
        // if(data == null)
        // or whatever you want 
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});

How to determine the IP address of a Solaris system

hostname and uname will give you the name of the host. Then use nslookup to translate that to an IP address.

Extract source code from .jar file

Use JD GUI. Open the application, drag and drop your JAR file into it.

MySQL WHERE IN ()

You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).

I assume your table looks somewhat like this

TABLE
================================
| group_id | user_ids | name   |
--------------------------------
| 1        | 1,4,6    | group1 |
--------------------------------
| 2        | 4,5,1    | group2 |    

so in your table of user groups, each row represents one group and in user_ids column you have set of user ids assigned to that group.

Normalized version of this table would look like this

GROUP
=====================
| id       | name   |
---------------------
| 1        | group1 |
---------------------
| 2        | group2 |    

GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1        | 1       |
----------------------
| 1        | 4       |
----------------------
| 1        | 6       |
----------------------
| 2        | 4       |
----------------------
| ...      

Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:

/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);

/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);

/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;

/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;

/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;

/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;

This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment, when you want to remove assignment you just delete row in group_user_assignment.

In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.

Here is sqlFiddle to play with.

Angular 2.0 router not working on reloading the browser

Angular by default uses HTML5 pushstate (PathLocationStrategy in Angular slang).
You either need a server that processes all requests like it were requesting index.html or you switch to HashLocationStrategy (with # in the URL for routes) https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class.html

See also https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/

To switch to HashLocationStrategy use

update for >= RC.5 and 2.0.0 final

import {HashLocationStrategy, LocationStrategy} from '@angular/common';

@NgModule({
  declarations: [AppCmp], 
  bootstrap: [AppCmp],
  imports: [BrowserModule, routes],
  providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
]);

or shorter with useHash

imports: [RouterModule.forRoot(ROUTER_CONFIG, {useHash: true}), ...

ensure you have all required imports

For the new (RC.3) router

<base href="."> 

can cause 404 as well.

It requires instead

<base href="/">

update for >= RC.x

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
  // or since RC.2
  {provide: LocationStrategy, useClass: HashLocationStrategy} 
]);

import {provide} from '@angular/core';
import {  
  PlatformLocation,  
  Location,  
  LocationStrategy,  
  HashLocationStrategy,  
  PathLocationStrategy,  
  APP_BASE_HREF}  
from '@angular/common';  

update for >= beta.16 Imports have changed

import {BrowserPlatformLocation} from '@angular/platform-browser';

import {provide} from 'angular2/core';
import {
  // PlatformLocation,
  // Location,
  LocationStrategy,
  HashLocationStrategy,
  // PathLocationStrategy,
  APP_BASE_HREF}
from 'angular2/router';
import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location';

< beta.16

import {provide} from 'angular2/core';
import {
  HashLocationStrategy
  LocationStrategy,
  ROUTER_PROVIDERS,
} from 'angular2/router';

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26 breaking-changes

How to change theme for AlertDialog

Arve Waltin's solution looks good, although I haven't tested it yet. There is another solution in case you have trouble getting that to work.... Extend AlertDialog.Builder and override all the methods (eg. setText, setTitle, setView, etc) to not set the actual Dialog's text/title/view, but to create a new view within the Dialog's View do everything in there. Then you are free to style everything as you please.

To clarify, as far as the parent class is concerned, the View is set, and nothing else.

As far as your custom extended class is concerned, everything is done within that view.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

How can I convert an image into Base64 string using JavaScript?

uploadProfile(e) {

    let file = e.target.files[0];
    let reader = new FileReader();

    reader.onloadend = function() {
        console.log('RESULT', reader.result)
    }
    reader.readAsDataURL(file);
}

Copy file or directories recursively in Python

To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)

import os, shutil

root_src_dir = r'C:\MyMusic'    #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp'  #Path to the destination folder

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.

Multi-line string with extra space (preserved indentation)

Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat

cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

The string after << indicates where to stop.

To send these lines to a file, use:

cat > $FILE <<- EOM
Line 1.
Line 2.
EOM

You could also store these lines to a variable:

read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM

This stores the lines to the variable named VAR.

When printing, remember the quotes around the variable otherwise you won't see the newline characters.

echo "$VAR"

Even better, you can use indentation to make it stand out more in your code. This time just add a - after << to stop the tabs from appearing.

read -r -d '' VAR <<- EOM
    This is line 1.
    This is line 2.
    Line 3.
EOM

But then you must use tabs, not spaces, for indentation in your code.

I/O error(socket error): [Errno 111] Connection refused

Its seems that server is not running properly so ensure that with terminal by

telnet ip port

example

telnet localhost 8069

It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection

Get year, month or day from numpy datetime64

Use dates.tolist() to convert to native datetime objects, then simply access year. Example:

>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]

This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.

Tested with python 3.6 / numpy 1.18.

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

Add an element to an array in Swift

Example: students = ["Ben" , "Ivy" , "Jordell"]

1) To add single elements to the end of an array, use the append(_:)

students.append(\ "Maxime" )

2) Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method

students.append(contentsOf: ["Shakia" , "William"])

3) To add new elements in the middle of an array by using the insert(_:at:) method for single elements

students.insert("Liam" , at:2 )

4) Using insert(contentsOf:at:) to insert multiple elements from another collection or array literal

students.insert(['Tim','TIM' at: 2 )

using href links inside <option> tag

(I don't have enough reputation to comment on toscho's answer.)

I have no experience with screen readers and I'm sure your points are valid.

However as far as using a keyboard to manipulate selects, it is trivial to select any option by using the keyboard:

TAB to the control

SPACE to open the select list

UP or DOWN arrows to scroll to the desired list item

ENTER to select the desired item

Only on ENTER does the onchange or (JQuery .change()) event fire.

While I personally would not use a form control for simple menus, there are many web applications that use form controls to change the presentation of the page (eg., sort order.) These can be implemented either by AJAX to load new content into the page, or, in older implementations, by triggering new page loads, which is essentially a page link.

IMHO these are valid uses of a form control.

Changing the sign of a number in PHP?

function positive_number($number)
{
    if ($number < 0) {
        $number *= -1;
    }

   return $number;
}

RecyclerView vs. ListView

In addition to above differences following are few more:

  1. RV separates view creation and binding of data to view. In LV, you need to check if convertView is null or not for creating view, before binding data to it. So, in case of RV, view will be created only when it is needed but in case of LV, one can miss the check for convertview and will create view everytime.

  2. Switching between Grid and List is more easy now with LayoutManager.

  3. No need to notify and update all items, even if only single item is changed.

  4. One had to implement view caching in case of LV. It is provided in RV by default. (There is difference between view caching n recycling.)

  5. Very easy item animations in case of RV.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

I was looking for a listing of macOS but found nothing, maybe this helps someone.

Output on macOS Catalina (10.15.7) using net5.0

# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER

# SpecialFolders (All)
SpecialFolder.AdminTools: 
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonTemplates: 
SpecialFolder.CommonVideos: 
SpecialFolder.Cookies: 
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History: 
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources: 
SpecialFolder.MyComputer: 
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86: 
SpecialFolder.Programs: 
SpecialFolder.Recent: 
SpecialFolder.Resources: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.Startup: 
SpecialFolder.System: /System
SpecialFolder.SystemX86: 
SpecialFolder.Templates: 
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows: 

I have replaced my username with $USER.

Code Snippet from pogosama.

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.

How to force a script reload and re-execute?

Use this function to find all script elements containing some word and refresh them.

_x000D_
_x000D_
function forceReloadJS(srcUrlContains) {_x000D_
  $.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {_x000D_
    var oldSrc = $(el).attr('src');_x000D_
    var t = +new Date();_x000D_
    var newSrc = oldSrc + '?' + t;_x000D_
_x000D_
    console.log(oldSrc, ' to ', newSrc);_x000D_
_x000D_
    $(el).remove();_x000D_
    $('<script/>').attr('src', newSrc).appendTo('head');_x000D_
  });_x000D_
}_x000D_
_x000D_
forceReloadJS('/libs/');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

Clear a terminal screen for real

None of the answers I read worked in PuTTY, so I found a comment on this article:

In the settings for your connection, under "Window->Behavior" you'll find a setting "System Menu Appears on ALT alone". Then CTRL + L, ALT, l (that's a lower case L) will scroll the screen and then clear the scrollback buffer.

(relevant to the OP because I am connecting to an Ubuntu server, but also apparently relevant no matter what your server is running.)

Switch statement equivalent in Windows batch file

Try by this way. To perform some list of operations like

  1. Switch case has been used.
  2. Checking the conditional statements.
  3. Invoking the function with more than two arguments.

 @echo off
 :Start2 
    cls
    goto Start
    :Start
    echo --------------------------------------
    echo     Welcome to the Shortcut tool     
    echo --------------------------------------            
    echo Choose from the list given below:
    echo [1] 2017
    echo [2] 2018
    echo [3] Task

    set /a one=1
    set /a two=2
    set /a three=3
    set /a four=4
    set input=
    set /p input= Enter your choice:
    if %input% equ %one% goto Z if NOT goto Start2
    if %input% equ %two% goto X if NOT goto Start2
    if %input% equ %three% goto C if NOT goto Start2
    if %input% geq %four% goto N

    :Z
    cls
    echo You have selected year : 2017
    set year=2017
    echo %year%
    call:branches year

    pause
    exit

    :X
    cls
    echo You have selected year : 2018
    set year=2018
    echo %year%
    call:branches year
    pause
    exit

    :C  
    cls
    echo You have selected Task
    call:Task
    pause
    exit

    :N
    cls
    echo Invalid Selection! Try again
    pause
    goto :start2




    :branches
    cls
    echo Choose from the list of Branches given below:
    echo [1] January
    echo [2] Feburary
    echo [3] March
    SETLOCAL
    set /a "Number1=%~1"
    set input=
    set /p input= Enter your choice:
    set /a b=0
    set /a bd=3
    set /a bdd=4
    if %input% equ %b% goto N
    if %input% leq %bd% call:Z1 Number1,input if NOT goto Start2
    if %input% geq %bdd% goto N



    :Z1
    cls
    SETLOCAL
    set /a "Number1=%~1"
    echo year = %Number1%
    set /a "Number2=%~2"
    echo branch = %Number2%
    call:operation Number1,Number2
    pause
    GOTO :EOF


    :operation
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set /a "year=%~1"
    echo Your have selected year = %year%
    set /a "month=%~2"
    echo You have selected Branch = %month%
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2






    :Task
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2

PostgreSQL function for last inserted ID

SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))

You need to supply the table name and column name of course.

This will be for the current session / connection http://www.postgresql.org/docs/8.3/static/functions-sequence.html

WiX tricks and tips

Fix the ProgressDlg so that it displays properly.

I've increased the font size for my installer from 8 to 10, to make the font a more human, usable scale on high-res monitors. I do this with this XML magic:

<UI Id="MyCustomUI">
  <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="10" />
  <TextStyle Id="WixUI_Font_Big"    FaceName="Tahoma" Size="12" />
  <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="14" />
  <TextStyle Id="WixUI_Font_Title"  FaceName="Tahoma" Size="12" Bold="yes" />

  <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
</UI>

But this means the ProgressDlg doesn't display properly any longer. This is the one that displays the progress of the install, right at the very end. The ActionText gets clipped, so descenders on letters like g and j do not display. Fix this by adjusting the size and position of the various controls on the Progressdialog, in a post-processing Javascript. Run this script after generating the MSI:

var msiOpenDatabaseModeTransact = 1;
var filespec = WScript.Arguments(0);
var installer = new ActiveXObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);

// The text on the exit dialog is too close to the title.  This 
// step moves the text down from Y=70 to Y=90, about one line. 
sql = "UPDATE `Control` SET `Control`.`Y` = '90' " +
    "WHERE `Control`.`Dialog_`='ExitDialog' AND `Control`.`Control`='Description'";
view = database.OpenView(sql);
view.Execute();
view.Close();

// The progressbar is too close to the status text on the Progress dialog. 
// This step moves the progressbar down from Y=115 to Y=118, about 1/3 line. 
sql = "UPDATE `Control` SET `Control`.`Y` = '118' " +
    "WHERE `Control`.`Dialog_`='ProgressDlg' AND `Control`.`Control`='ProgressBar'";
view = database.OpenView(sql);
view.Execute();
view.Close();

// The StatusLabel and ActionText controls are too short on the Progress dialog,
// which means the bottom of the text is cut off.  This step
// increases the height from 10 to 16.
sql = "UPDATE `Control` SET `Control`.`Height` = '16' " +
    "WHERE `Control`.`Dialog_`='ProgressDlg' AND `Control`.`Control`='StatusLabel'";
view = database.OpenView(sql);
view.Execute();
view.Close();
sql = "UPDATE `Control` SET `Control`.`Height` = '16' " +
    "WHERE `Control`.`Dialog_`='ProgressDlg' AND `Control`.`Control`='ActionText'";
view = database.OpenView(sql);
view.Execute();
view.Close();

database.Commit();

OR condition in Regex

A classic "or" would be |. For example, ab|de would match either side of the expression.

However, for something like your case you might want to use the ? quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:

\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+

This pattern will match:

  • \d+: One or more numbers.
  • \s+: One or more whitespaces.
  • [A-Z\s]+: One or more uppercase characters or space characters
  • \s+: One or more whitespaces.
  • [A-Z][A-Za-z\s]+: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.

If you'd like a more static check, e.g. indeed only match ABC and A ABC, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):

\d (?:ABC|A ABC) Street

Or another alternative using a quantifier:

\d (?:A )?ABC Street

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

How do I run a program with a different working directory from current, from Linux shell?

from the current directory provide the full path to the script directory to execute the command

/root/server/user/home/bin/script.sh

Gradle error: could not execute build using gradle distribution

I had the same Gradle build problems in Eclipse and by doing the following steps, the problems were solved:

  • set up project to use correct java version of java project properties-> java build path -> jre system (edit the current one, and add the correct java jdk or jre there)

  • window->Preferences ->Gradle->Arguments-> Workspace JRE (set to the correct one)

Hope this will help those who have the same problems.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

expected assignment or function call: no-unused-expressions ReactJS

In my case the error happened because the new line after the return statement.

Error : Expected an assignment or function call and instead saw an expression

return
(
    <ul>
        {
            props.numbers.map(number => <li key={number.toString()}>number</li>)
        }
    </ul>
);

Working OK. No Error

return (
    <ul>
        {
            props.numbers.map(number => <li key={number.toString()}>number</li>)
        }
    </ul>
);

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

You can try like below

DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @ID INT
DECLARE @Name NVARCHAR(100)
SET @ID = 4
SET @sqlCommand = 'SELECT @Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = @ID'
EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT',
@ID = @ID, @Name = @Name OUTPUT
SELECT @Name ReturnedName

Source : blog.sqlauthority.com

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

The warning message MAY BE due to an XMLHttpRequest request within the main thread with the async flag set to false.

https://xhr.spec.whatwg.org/#synchronous-flag:

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.

The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.

How to set $_GET variable

I know this is an old thread, but I wanted to post my 2 cents...

Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..

<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>

<button type='button' onClick='ButtonPressed()'>Click me!</button>

<?PHP
 if(isset($_GET['next']))
    {
          echo "This will display after pressing the 'Click Me' button!";
    }
 ?>

How do I convert a pandas Series or index to a Numpy array?

A more recent way to do this is to use the .to_numpy() function.

If I have a dataframe with a column 'price', I can convert it as follows:

priceArray = df['price'].to_numpy()

You can also pass the data type, such as float or object, as an argument of the function

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

If you are ubuntu 14.04 and using php 5.6 You are missing out on mbstring and mysql module

Please install mbstring and mysql by

sudo apt-get install php5.6-mbstring
sudo apt-get install php5.6-mysql

and restart apache

sudo service apache2 restart

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

Regular expression to detect semi-colon terminated C++ for & while loops

Greg is absolutely correct. This kind of parsing cannot be done with regular expressions. I suppose it is possible to build some horrendous monstrosity that would work for many cases, but then you'll just run across something that does.

You really need to use more traditional parsing techniques. For example, its pretty simple to write a recursive decent parser to do what you need.

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

How to enable Logger.debug() in Log4j

This is happening due to the fact that the logging level of your logger is set to 'error' - therefore you will only see error messages or above this level in terms of severity so this is why you also see the 'fatal' message.

If you set the logging level to 'debug' on your logger in your log4j.xml you should see all messages.

Have a look at the log4j introduction for explaination.

How to increase the execution timeout in php?

As an addition to above answers, you may use set_time_limit() function:

http://php.net/manual/en/function.set-time-limit.php

passing 0 as an argument will make your script run with no time limit.

Retrieving the output of subprocess.call()

If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string).

Simple example (linux version, see note):

import subprocess

print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

Note that the ping command is using linux notation (-c for count). If you try this on Windows remember to change it to -n for same result.

As commented below you can find a more detailed explanation in this other answer.

how to compare two string dates in javascript?

Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.

// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2

function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}

P.S. would have commented directly to vitran's post but I don't have the rep to do that.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected (I just changed the type from double to String):

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Can a variable number of arguments be passed to a function?

Another way to go about it, besides the nice answers already mentioned, depends upon the fact that you can pass optional named arguments by position. For example,

def f(x,y=None):
    print(x)
    if y is not None:
        print(y)

Yields

In [11]: f(1,2)
1
2

In [12]: f(1)
1

Access elements in json object like an array

The your seems a multi-array, not a JSON object.

If you want access the object like an array, you have to use some sort of key/value, such as:

var JSONObject = {
  "city": ["Blankaholm, "Gamleby"],
  "date": ["2012-10-23", "2012-10-22"],
  "description": ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  "lat": ["57.586174","16.521841"], 
  "long": ["57.893162","16.406090"]
}

and access it with:

JSONObject.city[0] // => Blankaholm
JSONObject.date[1] // => 2012-10-22

and so on...

or

JSONObject['city'][0] // => Blankaholm
JSONObject['date'][1] // => 2012-10-22

and so on...

or, in last resort, if you don't want change your structure, you can do something like that:

var JSONObject = {
  "data": [
    ["Blankaholm, "Gamleby"],
    ["2012-10-23", "2012-10-22"],
    ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
    ["57.586174","16.521841"], 
    ["57.893162","16.406090"]
  ]
}

JSONObject.data[0][1] // => Gambleby

"could not find stored procedure"

You may need to check who the actual owner of the stored procedure is. If it is a specific different user then that could be why you can't access it.

Changing capitalization of filenames in Git

Considering larsks' answer, you can get it working with a single command with "--force":

 git mv --force myfile MyFile

Applying a single font to an entire website with CSS

Please place this in the head of your Page(s) if the "body" needs the use of 1 and the same font:

<style type="text/css">
body {font-family:FONT-NAME ;
     }
</style>

Everything between the tags <body> and </body>will have the same font

.war vs .ear file

From GeekInterview:

In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality

JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension

WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension

EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

Illegal mix of collations error in MySql

Here's how to check which columns are the wrong collation:

SELECT table_schema, table_name, column_name, character_set_name, collation_name

FROM information_schema.columns

WHERE collation_name = 'latin1_general_ci'

ORDER BY table_schema, table_name,ordinal_position; 

And here's the query to fix it:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin1 COLLATE 'latin1_swedish_ci';

Link

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

If someone else have got a similar error message, you probably built the app with optimisations(production) flag on and that's why the error message is not that communicative. Another possibility that you have got the error under development (from i386 I know you were using simulator). If that is the case, change the build environment to development and try to reproduce the situation to get a more specific error message.

How do I run Python code from Sublime Text 2?

I had the same problem. You probably haven't saved the file yet. Make sure to save your code with .py extension and it should work.

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

npm install doesn't create node_modules directory

NPM has created a node_modules directory at '/home/jasonshark/' path.

From your question it looks like you wanted node_modules to be created in the current directory.

For that,

  1. Create project directory: mkdir <project-name>
  2. Switch to: cd <project-name>
  3. Do: npm init This will create package.json file at current path
  4. Open package.json & fill it something like below

    {
        "name": "project-name",
        "version": "project-version",
        "dependencies": {
            "mongodb": "*"
        }
    }
    
  5. Now do : npm install OR npm update

Now it will create node_modules directory under folder 'project-name' you created.

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

SyntaxError: missing ) after argument list

You had a unescaped " in the onclick handler, escape it with \"

$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "'  onclick=\"(canLaunch('" + v.LibraryItemId + " '))\">View &raquo;</a></div></div>")

How to display Base64 images in HTML?

You need to specify correct Content-type, Content-encoding and charset like

 data:image/jpeg;charset=utf-8;base64, 

according to the syntax of the data URI scheme:

 data:[<media type>][;charset=<character set>][;base64],<data>

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

Filter data.frame rows by a logical condition

No one seems to have included the which function. It can also prove useful for filtering.

expr[which(expr$cell == 'hesc'),]

This will also handle NAs and drop them from the resulting dataframe.

Running this on a 9840 by 24 dataframe 50000 times, it seems like the which method has a 60% faster run time than the %in% method.

The infamous java.sql.SQLException: No suitable driver found

url="jdbc:postgresql//localhost:5432/mmas"

That URL looks wrong, do you need the following?

url="jdbc:postgresql://localhost:5432/mmas"

Absolute vs relative URLs

I would heartily recommend relative URLs for pointing bits of the same site to other bits of the same site.

Don't forget that a change to HTTPS - even if in the same site - is going to need an absolute URL.

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.

C++ auto keyword. Why is it magic?

For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).

Syntax

auto variable initializer   (1) (since C++11)

auto function -> return type    (2) (since C++11)

auto function   (3) (since C++14)

decltype(auto) variable initializer (4) (since C++14)

decltype(auto) function (5) (since C++14)

auto :: (6) (concepts TS)

cv(optional) auto ref(optional) parameter   (7) (since C++14)

Explanation

1) When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier. Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u) if the function call f(expr) was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop. If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0; is ill-formed, while the declaration auto i = 0, *p = &i; is well-formed and the auto is deduced as int.

2) In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.

3) In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.

4) If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.

5) If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.

6) A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.

7) A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)

Notes Until C++11, auto had the semantic of a storage duration specifier. Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0; is not allowed.

For more info : http://en.cppreference.com/w/cpp/language/auto

jQuery: Return data after ajax call success

Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:

If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.

Generally, instead of:

function testAjax() {
  $.ajax({
    url: "getvalue.php",  
    success: function(data) {
      return data; 
    }
  });
}

you can write your testAjax function like this:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

Then you can get your promise like this:

var promise = testAjax();

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:

promise.success(function (data) {
  alert(data);
});

(See updates below for simplified syntax.)

If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.

The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.

See this DEMO.

UPDATE (2015)

Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.

However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.

What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.

But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.

In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.

For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.

How to return a real promise

The function from my example above:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

returns a jqXHR object, which is a jQuery Deferred Object.

To make it return a real promise, you can change it to - using the method from the Q wiki:

function testAjax() {
  return Q($.ajax({
      url: "getvalue.php"
  }));
}

or, using the method from the HTML5 Rocks article:

function testAjax() {
  return Promise.resolve($.ajax({
      url: "getvalue.php"
  }));
}

This Promise.resolve($.ajax(...)) is also what is explained in the promise module documentation and it should work with ES6 Promise.resolve().

To use the ES6 Promises today you can use es6-promise module's polyfill() by Jake Archibald.

To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.

For more info see:

Future of jQuery

Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.

Interesting talks

UPDATE (2016)

There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.

Using the jQuery API, instead of:

promise.success(function (data) {
  alert(data);
});

you can write:

promise.success(data => alert(data));

or using the Promises/A+ API:

promise.then(data => alert(data));

Remember to always use rejection handlers either with:

promise.then(data => alert(data), error => alert(error));

or with:

promise.then(data => alert(data)).catch(error => alert(error));

See this answer to see why you should always use rejection handlers with promises:

Of course in this example you could use just promise.then(alert) because you're just calling alert with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:

promise.then(data => alert("x is " + data.x));

Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).

For the support of arrow functions, see:

UPDATE (2017)

There is an even newer syntax right now called async functions with a new await keyword that instead of this code:

functionReturningPromise()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

lets you write:

try {
    let data = await functionReturningPromise();
    console.log('Data:', data);
} catch (error) {
    console.log('Error:', error);
}

You can only use it inside of a function created with the async keyword. For more info, see:

For support in browsers, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

More info

Some other questions about promises for more details:

How to extend an existing JavaScript array with another array, without creating a new array

If you want to use jQuery, there is $.merge()

Example:

a = [1, 2];
b = [3, 4, 5];
$.merge(a,b);

Result: a = [1, 2, 3, 4, 5]

Call method when home button pressed

use onPause() method to do what you want to do on home button.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You have configured the auth.php and used members table for authentication but there is no user_email field in the members table so, Laravel says

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))

Because, it tries to match the user_email in the members table and it's not there. According to your auth configuration, laravel is using members table for authentication not users table.

how to specify local modules as npm package dependencies

npm install now supports this

npm install --save ../path/to/mymodule

For this to work mymodule must be configured as a module with its own package.json. See Creating NodeJS modules.

As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.

This feature was implemented in the version 2.0.0 of npm. For example:

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

Any of the following paths are also valid:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

syncing updates

Since npm install copies mymodule into node_modules, changes in mymodule's source will not automatically be seen by the dependent project.

There are two ways to update the dependent project with

  • Update the version of mymodule and then use npm update: As you can see above, the package.json "dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update just tries to make sure the latest version is installed, as determined by mymodule's package.json. See chriskelly's answer to this specific problem.

  • Reinstall using npm install. This will install whatever is at mymodule's source path, even if it is older, or has an alternate branch checked out, whatever.

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Excel date to Unix timestamp

To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:

=IF(
  AND(
    A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
    A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
  );
  (A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
  (A2-DATE(1970;1;1))*24*60*60*1000
)

Quick explanation:

If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

C# string replace

Use:

line.Replace(@""",""", ";");

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

NullPointerException in Java with no StackTrace

Here is an explanation : Hotspot caused exceptions to lose their stack traces in production – and the fix

I've tested it on Mac OS X

  • java version "1.6.0_26"
  • Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
  • Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)

    Object string = "abcd";
    int i = 0;
    while (i < 12289) {
        i++;
        try {
            Integer a = (Integer) string;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

For this specific fragment of code, 12288 iterations (+frequency?) seems to be the limit where JVM has decided to use preallocated exception...

Declare an empty two-dimensional array in Javascript?

// for 3 x 5 array

new Array(3).fill(new Array(5).fill(0))

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

To fetch only one distinct record from duplicate column of two rows you can use "rowid" column which is maintained by oracle itself as Primary key,so first try

"select rowid,RequestID,CreatedDate,HistoryStatus  from temptable;"

and then you can fetch second row only by it's value of 'rowid' column by using in SELECT statement.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

I ran into the same error. My web app was pointed towards report viewer version 10.0 however if 11.0 is installed it adds a redirect in the 10.0 .dll to 11.0. This became an issue when 11.0 was uninstalled as this does not correct the redirect in the 10.0 .dll. The fix in my case was to simply uninstall and reinstall 10.0.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

It took a few hours to understand all the details of this problem and figure out the best implementation. It turns out as of April 2016 only iOS Chrome has this problem. I tried on Android Chrome and iOS Safari-- both were fine without this fix. So the fix for iOS Chrome I'm using is:

$(document).ready(function() {
   var screenHeight = $(window).height();
   $('div-with-background-image').css('height', screenHeight + 'px');
});

JavaScript: Check if mouse button down?

        var mousedown = 0;
        $(function(){
            document.onmousedown = function(e){
                mousedown = mousedown | getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.onmouseup = function(e){
                mousedown = mousedown ^ getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.oncontextmenu = function(e){
                // to suppress oncontextmenu because it blocks
                // a mouseup when two buttons are pressed and 
                // the right-mouse button is released before
                // the other button.
                return false;
            }
        });

        function getWindowStyleButton(e){
            var button = 0;
                if (e) {
                    if (e.button === 0) button = 1;
                    else if (e.button === 1) button = 4;
                    else if (e.button === 2) button = 2;  
                }else if (window.event){
                    button = window.event.button;
                }
            return button;
        }

this cross-browser version works fine for me.

How do you use the Immediate Window in Visual Studio?

One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.

For example, if you had a static method that returns the sum of two numbers such as:

private static int GetSum(int a, int b)
{
    return a + b;
}

Then in the Immediate Window you can type the following:

? GetSum(2, 4)
6

As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.

For example, let’s say this is what your class looks like:

private class Foo
{
    public string GetMessage()
    {
        return "hello";
    }
}

If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):

? foo.GetMessage(); // object ‘foo’ already exists
"hello"

In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:

? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"

You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:

? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"

Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:

? new Foo().GetMessage()
"hello" 

A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.

Along with inspecting methods, you can do simple math equations:

? 5 * 6
30

or compare values:

? 5==6
false
? 6==6
true

The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.

Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.

Unfortunately, another drawback of the Immediate Window is that it does not support loops.

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

  var elem = document.getElementById(id); 

  return elem.dispatchEvent(event);
}

How do I pass command-line arguments to a WinForms application?

This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

Add a reference to Microsoft.VisualBasic

Create a class called WindowsFormsApplication

public class WindowsFormsApplication : WindowsFormsApplicationBase
{

    /// <summary>
    /// Runs the specified mainForm in this application context.
    /// </summary>
    /// <param name="mainForm">Form that is run.</param>
    public virtual void Run(Form mainForm)
    {
        // set up the main form.
        this.MainForm = mainForm;

        // Example code
        ((Form1)mainForm).FileName = this.CommandLineArgs[0];

        // then, run the the main form.
        this.Run(this.CommandLineArgs);
    }

    /// <summary>
    /// Runs this.MainForm in this application context. Converts the command
    /// line arguments correctly for the base this.Run method.
    /// </summary>
    /// <param name="commandLineArgs">Command line collection.</param>
    private void Run(ReadOnlyCollection<string> commandLineArgs)
    {
        // convert the Collection<string> to string[], so that it can be used
        // in the Run method.
        ArrayList list = new ArrayList(commandLineArgs);
        string[] commandLine = (string[])list.ToArray(typeof(string));
        this.Run(commandLine);
    }

}

Modify your Main() routine to look like this

static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;

PHPExcel - set cell type before writing a value in it

Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:

$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getDefaultStyle()
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

And it works flawlessly. Thank you, Mark Baker.

Auto detect mobile browser (via user-agent?)

Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.

@media screen and (max-width:1025px) {
   #content {
     width: 100%;
   }
}

You can set the width to whatever you want, but 1025 will catch the iPad landscape view.

You'll also want to add the following meta tag to your head:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check out this article over at HTML5 Rocks for some good examples

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case was a misspelling "Custom Class" name. Make sure that you check your storyboard for the custom classes that you defined.

How to match a substring in a string, ignoring case

You can use in operator in conjunction with lower method of strings.

if "mandy" in line.lower():

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

SQL Server FOR EACH Loop

declare @counter as int
set @counter = 0
declare @date as varchar(50)
set @date = cast(1+@counter as varchar)+'/01/2013'
while(@counter < 12)
begin 
select  cast(1+@counter as varchar)+'/01/2013' as date
set @counter = @counter + 1
end

How do I add indices to MySQL tables?

Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.

Explanation

Primary key as index

Consider you have a tbl_student table and you want student_id as primary key:

ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)

Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.

Specify index name

ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)

Above statement will create an ordinary index with student_index name.

Create unique index

ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)

Here, student_unique_index is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).

Fulltext option

ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)

Above statement will create the Fulltext index name with student_fulltext_index, for which you need MyISAM Mysql Engine.

How to remove indexes ?

DROP INDEX `student_index` ON `tbl_student`

How to check available indexes?

SHOW INDEX FROM `tbl_student`

Android - implementing startForeground for a service?

This is my code to set the service to foreground:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

To remove the notification, just call the stopForeground(true);

It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java

What is the correct way to declare a boolean variable in Java?

As stated by Levon, this is not mandatory as stated in the docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

This is probably either an habit from other languages that don't guarantee primitive data types default values.

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

Make sure you commit .pfx files to repository.

I just found *.pfx in my default .gitignore. Comment it (by #) and commit changes. Then pull repository and rebuild.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Download latest version of postman from https://www.postman.com/downloads/ then after tar.gz file gets downloaded follow below commands

$ tar -xvzf Postman-linux-x64-7.27.1.tar.gz
$ cd Postman
$ ./Postman

Random number in range [min - max] using PHP

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

Validating email addresses using jQuery and regex

you can use this function

 var validateEmail = function (email) {

        var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;


        if (pattern.test(email)) {
            return true;
        }
        else {
            return false;
        }
    };

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

We have following script for create new table:

CREATE TABLE new_table
(
id                     NUMBER(32) PRIMARY KEY,
referenced_table_id    NUMBER(32)    NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
    FOREIGN KEY (referenced_table_id)
        REFERENCES referenced_table (id)
);

and we were getting this error on execute:

[42000][2270] ORA-02270: no matching unique or primary key for this column-list

The issue was due to disabled primary key of referenced table in our case. We have enabled it by

ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;

after that we created new table using first script without any issues

How to add jQuery in JS file

You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.

_x000D_
_x000D_
// Anonymous "self-invoking" function_x000D_
(function() {_x000D_
    var startingTime = new Date().getTime();_x000D_
    // Load the script_x000D_
    var script = document.createElement("SCRIPT");_x000D_
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';_x000D_
    script.type = 'text/javascript';_x000D_
    document.getElementsByTagName("head")[0].appendChild(script);_x000D_
_x000D_
    // Poll for jQuery to come into existance_x000D_
    var checkReady = function(callback) {_x000D_
        if (window.jQuery) {_x000D_
            callback(jQuery);_x000D_
        }_x000D_
        else {_x000D_
            window.setTimeout(function() { checkReady(callback); }, 20);_x000D_
        }_x000D_
    };_x000D_
_x000D_
    // Start polling..._x000D_
    checkReady(function($) {_x000D_
        $(function() {_x000D_
            var endingTime = new Date().getTime();_x000D_
            var tookTime = endingTime - startingTime;_x000D_
            window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");_x000D_
        });_x000D_
    });_x000D_
})();
_x000D_
_x000D_
_x000D_

Other Option : - You can also try Require.JS which is a JS module loader.

Use .htaccess to redirect HTTP to HTTPs

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^digitalsoftwaremarket.com [NC]
    RewriteRule ^(.*)$ http://www.digitalsoftwaremarket.com/$1 [L,R=301]
</IfModule>

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You may need to set up a root account for your MySQL database:

In the terminal type:

mysqladmin -u root password 'root password goes here'

And then to invoke the MySQL client:

mysql -h localhost -u root -p

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

enter image description here

I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement

update [Contacts] set contactNo=(case 
when contactNo=8018070777 then 8018070999
else
contactNo
end)

enter image description here

How to write a basic swap function in Java

You can swap variables with or without using a temporary variable.

Here is an article that provides multiple methods to swap numbers without temp variable :

http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/

Numeric for loop in Django templates

For those who are looking to simple answer, just needing to display an amount of values, let say 3 from 100 posts for example just add {% for post in posts|slice:"3" %} and loop it normally and only 3 posts will be added.

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in

ngOnInt(){

    userForm = new FormGroup({
        name: new FormControl(),
        email: new FormControl(),
        adresse: new FormGroup({
            rue: new FormControl(),
            ville: new FormControl(),
            cp: new FormControl(),
        })
     });
)

Cannot assign requested address - possible causes?

this is just a shot in the dark : when you call connect without a bind first, the system allocates your local port, and if you have multiple threads connecting and disconnecting it could possibly try to allocate a port already in use. the kernel source file inet_connection_sock.c hints at this condition. just as an experiment try doing a bind to a local port first, making sure each bind/connect uses a different local port number.

How can I increment a date by one day in Java?

you can use Simple java.util lib

Calendar cal = Calendar.getInstance(); 
cal.setTime(yourDate); 
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();

Android soft keyboard covers EditText field

Why not try to add a ScrollView to wrap whatever it is you want to scroll. Here is how I have done it, where I actually leave a header on top which does not scroll, while the dialog widgets (in particular the EditTexts) scroll when you open soft keypad.

<LinearLayout android:id="@+id/HeaderLayout" >
  <!-- Here add a header or whatever will not be scrolled. -->
</LinearLayout>
<ScrollView android:id="@+id/MainForm" >
  <!-- Here add your edittexts or whatever will scroll. -->
</ScrollView>

I would typically have a LinearLayout inside the ScrollView, but that is up to you. Also, setting Scrollbar style to outsideInset helps, at least on my devices.

Max parallel http connections in a browser?

Looking at about:config on Firefox 33 on GNU/Linux (Ubuntu), and searching connections I found:

network.http.max-connections: 256

That is likely to answer the part is there any limit to the number of active connections per browser, across all domain

network.http.max-persistent-connections-per-proxy: 32

network.http.max-persistent-connections-per-server: 6

skipped two properties...

network.websocket.max-connections: 200

(interesting, seems like they are not limited per server but have a default value lower than global http connections)

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

How to remove focus around buttons on click

If the above doesn't work for you, try this:

.btn:focus {outline: none;box-shadow: none;border:2px solid transparent;}

As user1933897 pointed out, this might be specific to MacOS with Chrome.

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

Animate background image change with jQuery

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>?

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});?

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}?

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

Running JAR file on Windows

First set path on cmd(command prompt):

set path="C:\Program Files\Java\jre6\bin"

then type

java -jar yourProgramname.jar 

What is a None value?

The book you refer to is clearly trying to greatly simplify the meaning of None. Python variables don't have an initial, empty state – Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.

>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
NameError: global name 'x' is not defined

but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None:

>>> def test(x=None):
...   if x is None:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

The fact that this value is the special None value is not terribly important in this case. I could've used any default value:

>>> def test(x=-1):
...   if x == -1:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

…but having None around gives us two benefits:

  1. We don't have to pick a special value like -1 whose meaning is unclear, and
  2. Our function may actually need to handle -1 as a normal input.
>>> test(-1)
no x here

oops!

So the book is a little misleading mostly in its use of the word reset – assigning None to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reset a value to its original, undefined state you must use the del keyword:

>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Correct way to find max in an Array in Swift

Update: This should probably be the accepted answer since maxElement appeared in Swift.


Use the almighty reduce:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })

Similarly:

let numMin = nums.reduce(Int.max, { min($0, $1) })

reduce takes a first value that is the initial value for an internal accumulator variable, then applies the passed function (here, it's anonymous) to the accumulator and each element of the array successively, and stores the new value in the accumulator. The last accumulator value is then returned.

Input type=password, don't let browser remember the password

I tried the following and it seems that works to any browser:

<input id="passfld" type="text" autocomplete="off" />

<script type="text/javascript">
    $(function(){  
        var passElem = $("input#passfld");
        passElem.focus(function() { 
            passElem.prop("type", "password");                                             
        });
    });
</script>

This way is much more safer than using timeout techniques, because it guaranties that the input field will yield to password when the user focuses it.

How do you append an int to a string in C++?

Well, if you use cout you can just write the integer directly to it, as in

std::cout << text << i;

The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.

#include <sstream>

std::ostringstream oss;
oss << text << i;
std::cout << oss.str();

Alternatively, you can just convert the integer and append it to the string.

oss << i;
text += oss.str();

Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.

data.map is not a function

There is an error on $.map() invocation, try this:

    function getData(data) {
        this.productID = data.product_id;
        this.productData = data.product_data;
        this.imageID = data.product_data.image_id;
        this.text = data.product_data.text;
        this.link = data.product_data.link;
        this.imageUrl = data.product_data.image_url;
    }

    $.getJSON("json.json?sdfsdfg").done(function (data) {

        var allPosts = $.map(data,function (item) {

            for (var i = 0; i < item.length; i++) {
                new getData(item[i]);
            };

        });

    }); 

The error in your code was that you made return in your AJAX call, so it executed only one time.

Ruby replace string with captured regex pattern

If you need to use a regex to filter some results, and THEN use only the capture group, you can do the following:

str = "Leesburg, Virginia  20176"
state_regex = Regexp.new(/,\s*([A-Za-z]{2,})\s*\d{5,}/)
# looks for the comma, possible whitespace, captures alpha,
# looks for possible whitespace, looks for zip

> str[state_regex]
=> ", Virginia  20176"

> str[state_regex, 1] # use the capture group
=> "Virginia"

Hash table in JavaScript

If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

And then access them using JavaScript's associative array syntax:

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

If you're instantiating an android.support.v4.app.Fragment class, the you have to call getActivity().getSupportFragmentManager() to get rid of the cannot-resolve problem. However the official Android docs on Fragment by Google tends to over look this simple problem and they still document it without the getActivity() prefix.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

PL/SQL: numeric or value error: character string buffer too small

is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.

for example:

myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26

will fire such an error

how to get the cookies from a php curl into a variable

libcurl also provides CURLOPT_COOKIELIST which extracts all known cookies. All you need is to make sure the PHP/CURL binding can use it.

Copy an entire worksheet to a new worksheet in Excel 2010

' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

There only two things that MapReduce does NATIVELY: Sort and (implemented by sort) scalable GroupBy.

Most of applications and Design Patterns over MapReduce are built over these two operations, which are provided by shuffle and sort.

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

Echo newline in Bash prints literal \n

One more entry here for those that didn't make it work with any of these solutions, and need to get a return value from their function:

function foo()
{
    local v="Dimi";
    local s="";
    .....
    s+="Some message here $v $1\n"
    .....
    echo $s
}

r=$(foo "my message");
echo -e $r;

Only this trick worked in a linux I was working on with this bash:

GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)

Hope it helps someone with similar problem.

No line-break after a hyphen

You could also wrap the relevant text with

<span style="white-space: nowrap;"></span>

Reset select value to default

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});

This is a simple way for your question. only one line answer.