Programs & Examples On #Speech

Speech is the vocalized form of human communication.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Remove quotes from String in Python

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

ImportError: No module named request

You can do that using Python 2.

  1. Remove request
  2. Make that line: from urllib2 import urlopen

You cannot have request in Python 2, you need to have Python 3 or above.

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.

Using Google Text-To-Speech in Javascript

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

_x000D_
_x000D_
const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
_x000D_
_x000D_

How should I escape commas and speech marks in CSV files so they work in Excel?

According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).

FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
    C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional

    v_aux VARCHAR2(32000);
    v_has_double_quotes BOOLEAN;
    v_has_comma BOOLEAN;
    v_has_newline BOOLEAN;
BEGIN
    v_has_double_quotes := instr(str, '"') > 0;
    v_has_comma := instr(str,',') > 0;
    v_has_newline := instr(str, C_NEWLINE) > 0;

    IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
        IF v_has_double_quotes THEN
            v_aux := replace(str,'"','""');
        ELSE
            v_aux := str;
        END IF;
        return '"'||v_aux||'"';
    ELSE
        return str;
    END IF;
END;

Google Text-To-Speech API

You can download the Voice using Wget:D

wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello"

Save the output into a mp3 file:

wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello" -O hello.mp3

Enjoy !!

Android java.lang.NoClassDefFoundError

Edit the build path in this order, this worked for me.

Make sure the /gen is before /src

enter image description here

Retrieving an element from array list in Android?

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // add elements to the array list

        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // retrieve elements from array

        String data = al.get(pass the index here);
        System.out.println("Data is "+ data);

This is another way of getting element

        Iterator<String> it = al.iterator();
        while (it.hasNext()) {
            System.out.println("Data is "+ it.next());
        }
    }

Using Chrome's Element Inspector in Print Preview Mode?

Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.

Chrome v52+:

  • Open the Developer Tools (Windows: F12 or Ctrl+Shift+I, Mac: Cmd+Opt+I)
  • Click the Customize and control DevTools hamburger menu button and choose More tools > Rendering settings (or Rendering in newer versions).
  • Check the Emulate print media checkbox at the Rendering tab and select the Print media type.

Chrome v52+

Chrome v48+ (Thanks Alex for noticing):

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (CTRLSHIFTM).
  • Make sure the console is shown by clicking Show console in menu at (1) (ESC key toggles the console if Developer Toolbar has focus).
  • Check Emulate print media at the rendering tab which can be opened by selecting Rendering in menu at (2).

Chrome v48+

Chrome v46+:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the console is shown by clicking the menu button (2) > Show console (3) or pressing the ESC key to toggle the console (only works when Developer Toolbar has the focus).
  • Open the Emulation (4) > Media (5) tabs, check CSS media and select print (3).

Chrome v46+ support

Chrome v43+:

  • The drawer icon at step 2 has changed.

Emulate print media query on Chrome v43

Chrome v42:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the drawer is shown by clicking the Show drawer button (2) or pressing the ESC key to toggle the drawer.
  • Under Emulation > Media check CSS media and select print (3).

Emulate print media query on Chrome v42

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

In my case I used Tortoise SVN and made the mistake to also use the Visual Studio GIT functions at the same time. That made Visual Studio lock the HEAD file inside the .git folder so neither VS or Tortoise could access the repo and i got the "fatal: Not a git repo..." error from both applications.

Solution:

  1. Go inside the .git folder and rename "HEAD.lock" to just "HEAD"
  2. Decide for one GIT admin application and don't touch the other one

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

jQuery on window resize

Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.

$(document).ready(function()
{   
   var resizeDelay = 200;
   var doResize = true;
   var resizer = function () {
      if (doResize) {

        //your code that needs to be executed goes here

        doResize = false;
      }
    };
    var resizerInterval = setInterval(resizer, resizeDelay);
    resizer();

    $(window).resize(function() {
      doResize = true;
    });
});

Git remote branch deleted, but still it appears in 'branch -a'

Don't forget the awesome

git fetch -p

which fetches and prunes all origins.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrap your formula with IFERROR.

=IFERROR(yourformula)

How to loop through elements of forms with JavaScript?

You need to get a reference of your form, and after that you can iterate the elements collection. So, assuming for instance:

<form method="POST" action="submit.php" id="my-form">
  ..etc..
</form>

You will have something like:

var elements = document.getElementById("my-form").elements;

for (var i = 0, element; element = elements[i++];) {
    if (element.type === "text" && element.value === "")
        console.log("it's an empty textfield")
}

Notice that in browser that would support querySelectorAll you can also do something like:

var elements = document.querySelectorAll("#my-form input[type=text][value='']")

And you will have in elements just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:

var elements = document.querySelectorAll("#my-form input[type=text]")

for (var i = 0, element; element = elements[i++];) {
    if (element.value === "")
        console.log("it's an empty textfield")
}

You will basically save one check.

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

Problems with entering Git commit message with Vim

Have you tried just going: git commit -m "Message here"

So in your case:

git commit -m "Form validation added"

After you've added your files of course.

Specifying an Index (Non-Unique Key) Using JPA

As far as I know, there isn't a cross-JPA-Provider way to specify indexes. However, you can always create them by hand directly in the database, most databases will pick them up automatically during query planning.

How can I remove space (margin) above HTML header?

I solved the space issue by adding a border and removing is by setting a negative margin. Do not know what the underlying problem is though.

header {
  border-top: 1px solid gold !important;
  margin-top: -1px !important;
}

Calculate days between two Dates in Java 8

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate dateBefore =  LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
    
long daysBetween =  ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
    
System.out.println(daysBetween);

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

Check if you have the linebreak-style rule configure as below either in your .eslintrc or in source code:

/*eslint linebreak-style: ["error", "unix"]*/

Since you're working on Windows, you may want to use this rule instead:

/*eslint linebreak-style: ["error", "windows"]*/

Refer to the documentation of linebreak-style:

When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).

The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF) whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n" (for LF) and "\r\n" for (CRLF).

This is a rule that is automatically fixable. The --fix option on the command line automatically fixes problems reported by this rule.

But if you wish to retain CRLF line-endings in your code (as you're working on Windows) do not use the fix option.

How to get multiline input from user

no_of_lines = 5
lines = ""
for i in xrange(5):
    lines+=input()+"\n"
    a=raw_input("if u want to continue (Y/n)")
    ""
    if(a=='y'):
        continue
    else:
        break
    print lines

How to get numbers after decimal point?

Another option would be to use the re module with re.findall or re.search:

import re


def get_decimcal(n: float) -> float:
    return float(re.search(r'\.\d+', str(n)).group(0))


def get_decimcal_2(n: float) -> float:
    return float(re.findall(r'\.\d+', str(n))[0])


def get_int(n: float) -> int:
    return int(n)


print(get_decimcal(5.55))
print(get_decimcal_2(5.55))
print(get_int(5.55))

Output

0.55
0.55
5

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Source

How to get rid of additional floating numbers in python subtraction?

How can I set the aspect ratio in matplotlib?

After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at

https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl

With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:

ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)

The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.

Thanks for all great answers received - especially @Yann's which will remain the winner.

Adding a parameter to the URL with JavaScript

Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:

window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));


// background functions below:

// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
  key = encodeURI(key);

  var params = getSearchParameters();

  if (Object.keys(params).length === 0) {
    if (value !== false)
      return '?' + key + '=' + encodeURI(value);
    else
      return '';
  }

  if (value !== false)
    params[key] = encodeURI(value);
  else
    delete params[key];

  if (Object.keys(params).length === 0)
    return '';

  return '?' + $.map(params, function (value, key) {
    return key + '=' + value;
  }).join('&');
}

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

Currently running queries in SQL Server

The tool is called the SQL Server Profiler, it's still part of the standard toolset.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK build tools are used to debug, build, run and test an Android application.

Android Build Tools can be used to develop and work from command line or IDE (i.e Eclipse or Android Studio).

Also used to connect Android devices and root them.(fastboot, adb and more..)

Always use the latest.(Recommended)

More Info on Android Build tools and commands

Is __init__.py not required for packages in Python 3.3+

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an __init__.py file.

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely, and affected ... .

The old way with __init__.py files still works as in Python 2.

How do I hide anchor text without hiding the anchor?

text-indent :-9999px 

Works flawlessly.

How to prevent XSS with HTML/PHP?

You are also able to set some XSS related HTTP response headers via header(...)

X-XSS-Protection "1; mode=block"

to be sure, the browser XSS protection mode is enabled.

Content-Security-Policy "default-src 'self'; ..."

to enable browser-side content security. See this one for Content Security Policy (CSP) details: http://content-security-policy.com/ Especially setting up CSP to block inline-scripts and external script sources is helpful against XSS.

for a general bunch of useful HTTP response headers concerning the security of you webapp, look at OWASP: https://www.owasp.org/index.php/List_of_useful_HTTP_headers

PHP Echo a large block of text

You can achieve that by printing your string like:

<?php $string ='here is your string.'; print_r($string); ?>

How to clear form after submit in Angular 2?

To angular version 4, you can use this:

this.heroForm.reset();

But, you could need a initial value like:

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

It is important to resolve null problem in your object reference.

reference link, Search for "reset the form flags".

RecyclerView - Get view at particular position

If you want the View, make sure to access the itemView property of the ViewHolder like so: myRecyclerView.findViewHolderForAdapterPosition(pos).itemView;

Syntax behind sorted(key=lambda: ...)

I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function, like the one sblom provided an example of. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its applications for such roles are broad. Its syntax is purely by convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

Lambda syntax is as follows:

lambda input_variable(s): tasty one liner

e.g.

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. The idea behind the key argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should used to sort by. When it says key=, what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list.

Check it out:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)

Base example:

sorted(mylist)

[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.

Example 1:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)

[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if (e) was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]

Now we're getting somewhere. What do you get when you sort the transformed list?

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

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:

[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]

Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.

This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

Global constants file in Swift

Constant.swift

import Foundation

let kBaseURL = NSURL(string: "http://www.example.com/")

ViewController.swift

var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)

How to add elements of a string array to a string array list?

Use asList() method. From java Doc asList

List<String> species = Arrays.asList(speciesArr);

Array inside a JavaScript Object?

var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

How to validate phone number in laravel 5.2?

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

Array or List in Java. Which is faster?

I suggest that you use a profiler to test which is faster.

My personal opinion is that you should use Lists.

I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.

Simple way to measure cell execution time in ipython notebook

Use cell magic and this project on github by Phillip Cloud:

Load it by putting this at the top of your notebook or put it in your config file if you always want to load it by default:

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime

If loaded, every output of subsequent cell execution will include the time in min and sec it took to execute it.

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

How to convert seconds to time format?

just one small additional example

requested time in miliseconds

    // ms2time( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array
    function ms2time($ms){
        $return = array();
        // ms
        $return['ms'] = (int) number_format( ($ms - (int) $ms), 2, '', '');
        $seconds = (int) $ms;
        unset($ms);

        if ($seconds%60 > 0){
            $return['s'] = $seconds%60;
        } else {
            $return['s'] = 0;
        }

        if ( ($minutes = intval($seconds/60))){
            $return['m'] = $minutes;
        }

        if (isset($return['m'])){
            $return['h'] = intval($return['m'] / 60);
            $return['m']  = $return['m'] % 60; 
        }


        if (isset($return['h'])){
            $return['d'] = intval($return['h'] / 24);
            $return['h']  = $return['h'] % 24; 
        }

        if (isset($return['d']))
            $return['mo'] = intval($return['d'] / 30);

        foreach($return as $k=>$v){
            if ($v == 0)
                unset($return[$k]);
        }

        return $return;
    }

    // ms2time2string( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array     
    function ms2time2string($ms){
        $array = array(
            'ms' => 'ms',
            's'  => 'seconds',
            'm'  => 'minutes',
            'h'  => 'hours',
            'd'  => 'days',
            'mo' => 'month',
        );


        if ( ( $return = ms2time($ms) )  && count($ms) > 0){

            foreach($return as $key=>$data){
                $return[$key] = $data .' '.$array[$key];
            }

        }
        return implode(" ", array_reverse($return));
    }

Append a single character to a string or char array in java?

new StringBuilder().append(str.charAt(0))
                   .append(str.charAt(10))
                   .append(str.charAt(20))
                   .append(str.charAt(30))
                   .toString();

This way you can get the new string with whatever characters you want.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

In many linux release, you can find complier.h in /usr/linux/ , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because

if ( likely( ... ) ) {
     doSomething();
}

it can be optimized as well in many compiler.

And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:

gcc -c test.c objdump -d test.o > obj.s

Then, open obj.s, you can find the answer.

pandas convert some columns into rows

pd.wide_to_long

You can add a prefix to your year columns and then feed directly to pd.wide_to_long. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt, e.g. when your columns already have an appropriate prefix.

df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))

res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
        .sort_values(['location', 'name'])

print(res)

   name        Date location  Value
0  test    Jan-2010        A     12
2  test    Feb-2010        A     20
4  test  March-2010        A     30
1   foo    Jan-2010        B     18
3   foo    Feb-2010        B     20
5   foo  March-2010        B     25

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

iOS how to set app icon and launch images

The correct sizes are as following:

1)58x58

2)80x80

3)120x120

4)180x180

Android: Getting a file URI from a content URI?

Well I am bit late to answer,but my code is tested

check scheme from uri:

 byte[] videoBytes;

if (uri.getScheme().equals("content")){
        InputStream iStream =   context.getContentResolver().openInputStream(uri);
            videoBytes = getBytes(iStream);
        }else{
            File file = new File(uri.getPath());
            FileInputStream fileInputStream = new FileInputStream(file);     
            videoBytes = getBytes(fileInputStream);
        }

In the above answer I converted the video uri to bytes array , but that's not related to question, I just copied my full code to show the usage of FileInputStream and InputStream as both are working same in my code.

I used the variable context which is getActivity() in my Fragment and in Activity it simply be ActivityName.this

context=getActivity(); //in Fragment

context=ActivityName.this;// in activity

Adding values to a C# array

int[] terms = new int[10]; //create 10 empty index in array terms

//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case 
for (int run = 0; run < terms.Length; run++) 
{
    terms[run] = 400;
}

//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}

Console.ReadLine();

/*Output:

Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Here is the way I fixed this issue on ASP.NET

  • First, you should add the nuget package Microsoft.AspNet.WebApi.Cors

  • Then modify the file App_Start\WebApiConfig.cs

    public static class WebApiConfig    
    {
       public static void Register(HttpConfiguration config)
       {
          config.EnableCors();
    
          ...
       }    
    }
    
  • Add this attribute on your controller class

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class MyController : ApiController
    {  
        [AcceptVerbs("POST")]
        public IHttpActionResult Post([FromBody]YourDataType data)
        {
             ...
             return Ok(result);
        }
    }
    
  • I was able to send json to the action by this way

    $http({
            method: 'POST',
            data: JSON.stringify(data),
            url: 'actionurl',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(...)
    

Reference : Enabling Cross-Origin Requests in ASP.NET Web API 2

Select data from "show tables" MySQL query

You may be closer than you think — SHOW TABLES already behaves a lot like SELECT:

$pdo = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
foreach ($pdo->query("SHOW TABLES") as $row) {
    print "Table $row[Tables_in_$dbname]\n";
}

In a Bash script, how can I exit the entire script if a certain condition occurs?

I often include a function called run() to handle errors. Every call I want to make is passed to this function so the entire script exits when a failure is hit. The advantage of this over the set -e solution is that the script doesn't exit silently when a line fails, and can tell you what the problem is. In the following example, the 3rd line is not executed because the script exits at the call to false.

function run() {
  cmd_output=$(eval $1)
  return_value=$?
  if [ $return_value != 0 ]; then
    echo "Command $1 failed"
    exit -1
  else
    echo "output: $cmd_output"
    echo "Command succeeded."
  fi
  return $return_value
}
run "date"
run "false"
run "date"

iOS 7 - Status bar overlaps the view

For Navigation Bar :

Writing this code :

self.navigationController.navigationBar.translucent = NO;

just did the trick for me.

How to run html file using node js

This is a simple html file "demo.htm" stored in the same folder as the node.js file.

<!DOCTYPE html>
<html>
  <body>
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </body>
</html>

Below is the node.js file to call this html file.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.
  console.log("Request for demo file received.");
  fs.readFile("Documents/nodejs/demo.html",function(error, data){
    if (error) {
      resp.writeHead(404);
      resp.write('Contents you are looking for-not found');
      resp.end();
    }  else {
      resp.writeHead(200, {
        'Content-Type': 'text/html'
      });
      resp.write(data.toString());
      resp.end();
    }
  });
});

server.listen(8081, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8081/');

Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".

MongoDB running but can't connect using shell

I had a similar problem, well actually the same (mongo process is running but can't connect to it). What I did was went to my database path and removed mongod.lock, and then gave it another try (restarted mongo). After that it worked.

Hope it works for you too. mongodb repair on ubuntu

Google Chromecast sender error if Chromecast extension is not installed or using incognito

i know it is not the best solution, but the only one supposed solution that i have read for all the web is to install chrome cast extension, so, i've decide, not to put the iframe into the website, i just insert the thumnail of my video from youtube like in this post explain.

and here we have two options:
1) Target the video to the channel and play it there
2) Call the video via ajax, like explain here (i've decided for this one) in a colorbox or any another plugin.

and like this, i prevent the google cast sender error make my site slow

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

ERROR 1064 (42000) in MySQL

Error 1064 often occurs when missing DELIMITER around statement like : create function, create trigger.. Make sure to add DELIMITER $$ before each statement and end it with $$ DELIMITER like this:

DELIMITER $$
CREATE TRIGGER `agents_before_ins_tr` BEFORE INSERT ON `agents`
  FOR EACH ROW
BEGIN

END $$
DELIMITER ; 

How do you get assembler output from C/C++ source in gcc?

As everyone has pointed out, use the -S option to GCC. I would also like to add that the results may vary (wildly!) depending on whether or not you add optimization options (-O0 for none, -O2 for agressive optimization).

On RISC architectures in particular, the compiler will often transform the code almost beyond recognition in doing optimization. It's impressive and fascinating to look at the results!

jQuery $.ajax request of dataType json will not retrieve data from PHP script

Try this...  
  <script type="text/javascript">

    $(document).ready(function(){

    $("#find").click(function(){
        var username  = $("#username").val();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'includes/find.php',
            data: 'username='+username,
            success: function( data ) {
            //in data you result will be available...
            response = jQuery.parseJSON(data);
//further code..
            },

    error: function(xhr, status, error) {
        alert(status);
        },
    dataType: 'text'

    });
        });

    });



    </script>

    <form name="Find User" id="userform" class="invoform" method="post" />

    <div id ="userdiv">
      <p>Name (Lastname, firstname):</p>
      </label>
      <input type="text" name="username" id="username" class="inputfield" />
      <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
    </div>
    </form>
    <div id="userinfo"><b>info will be listed here.</b></div>

Updating to latest version of CocoaPods?

Non of the above solved my problem, you can check pod version using two commands

  1. pod --version
  2. gem which cocoapods

In my case pod --version always showed "1.5.0" while gem which cocopods shows Library/Ruby/Gems/2.3.0/gems/cocoapods-1.9.0/lib/cocoapods.rb. I tried every thing but unable to update version showed from pod --version. sudo gem install cocopods result in installing latest version but pod --version always showing previous version. Finally I tried these commands

  1. sudo gem update
  2. sudo gem uninstall cocoapods
  3. sudo gem install cocopods
  4. pod setup``pod install

catch for me was sudo gem update. Hopefully it will help any body else.

How to remove a directory from git repository?

A combination of the 2 answers worked for me

git rm -r one-of-the-directories
git commit . -m "Remove duplicated directory"
git push

if it still shows some warning, remove the files manually

git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD
git push

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How do I run a docker instance from a DockerFile?

You cannot start a container from a Dockerfile.

The process goes like this:

Dockerfile =[docker build]=> Docker image =[docker run]=> Docker container

To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].

[1]: you can also docker import an image from a tarball or again docker load.

How can I switch to another branch in git?

Check remote branch list:

git branch -a

Switch to another Branch:

git checkout -b <local branch name> <Remote branch name>
Example: git checkout -b Dev_8.4 remotes/gerrit/Dev_8.4

Check local Branch list:

git branch

Update everything:

git pull

C++ Convert string (or char*) to wstring (or wchar_t*)

Based upon my own testing (On windows 8, vs2010) mbstowcs can actually damage original string, it works only with ANSI code page. If MultiByteToWideChar/WideCharToMultiByte can also cause string corruption - but they tends to replace characters which they don't know with '?' question marks, but mbstowcs tends to stop when it encounters unknown character and cut string at that very point. (I have tested Vietnamese characters on finnish windows).

So prefer Multi*-windows api function over analogue ansi C functions.

Also what I've noticed shortest way to encode string from one codepage to another is not use MultiByteToWideChar/WideCharToMultiByte api function calls but their analogue ATL macros: W2A / A2W.

So analogue function as mentioned above would sounds like:

wstring utf8toUtf16(const string & str)
{
   USES_CONVERSION;
   _acp = CP_UTF8;
   return A2W( str.c_str() );
}

_acp is declared in USES_CONVERSION macro.

Or also function which I often miss when performing old data conversion to new one:

string ansi2utf8( const string& s )
{
   USES_CONVERSION;
   _acp = CP_ACP;
   wchar_t* pw = A2W( s.c_str() );

   _acp = CP_UTF8;
   return W2A( pw );
}

But please notice that those macro's use heavily stack - don't use for loops or recursive loops for same function - after using W2A or A2W macro - better to return ASAP, so stack will be freed from temporary conversion.

Run react-native on android emulator

It happened to me that I had an instance of the packager running with an old project (I ran react-native start as usual). I was using Ubuntu 14.04. So what I did was to stop that instance and go to my project folder and in two different console tabs I ran these two commands separately:

npm start #here I used to run react-native start
react-native run-android

npm start is defined in my package.json as:

"start": "node_modules/react-native/packager/packager.sh"

I don't know if there is a sort of confusing stuff for react-native but that did the trick.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Here is Kotlin version.
Thanks you :)

         fun unSafeOkHttpClient() :OkHttpClient.Builder {
            val okHttpClient = OkHttpClient.Builder()
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts:  Array<TrustManager> = arrayOf(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                    override fun getAcceptedIssuers(): Array<X509Certificate>  = arrayOf()
                })

                // Install the all-trusting trust manager
                val  sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                if (trustAllCerts.isNotEmpty() &&  trustAllCerts.first() is X509TrustManager) {
                    okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
                    okHttpClient.hostnameVerifier { _, _ -> true }
                }

                return okHttpClient
            } catch (e: Exception) {
                return okHttpClient
            }
        }

Query to search all packages for table and/or column

you can use the views *_DEPENDENCIES, for example:

SELECT owner, NAME
  FROM dba_dependencies
 WHERE referenced_owner = :table_owner
   AND referenced_name = :table_name
   AND TYPE IN ('PACKAGE', 'PACKAGE BODY')

Clearing NSUserDefaults

In Swift:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryRepresentation().keys.forEach { defaults.removeObjectForKey($0) }

When should I use "this" in a class?

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

Java Swing - how to show a panel on top of another panel?

JOptionPane.showInternalInputDialog probably does what you want. If not, it would be helpful to understand what it is missing.

Normal arguments vs. keyword arguments

I was looking for an example that had default kwargs using type annotation:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

example:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

Convert a python dict to a string and back

If you care about the speed use ujson (UltraJSON), which has the same API as json:

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

Launch a shell command with in a python script, wait for the termination and return to the script

use spawn

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

laravel 5.3 new Auth::routes()

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.

Here are the routes

// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');

What does it mean when Statement.executeUpdate() returns -1?

For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:

For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:

A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.

0, if no rows are affected by the operation.

-1, if the operation is a mass delete on a segmented table space.

For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.

Populate unique values into a VBA array from Excel

one more way ...

Sub get_unique()
Dim unique_string As String
    lr = Sheets("data").Cells(Sheets("data").Rows.Count, 1).End(xlUp).Row
    Set range1 = Sheets("data").Range("A2:A" & lr)
    For Each cel In range1
       If Not InStr(output, cel.Value) > 0 Then
           unique_string = unique_string & cel.Value & ","
       End If
    Next
End Sub

Uploading an Excel sheet and importing the data into SQL Server database

 protected void btnUpload_Click(object sender, EventArgs e)
    {
          if (Page.IsValid)
            {
                bool logval = true;
                if (logval == true)
                {
                    String img_1 = fuUploadExcelName.PostedFile.FileName;
                    String img_2 = System.IO.Path.GetFileName(img_1);
                    string extn = System.IO.Path.GetExtension(img_1);

                    string frstfilenamepart = "";
                    frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
                    UploadExcelName.Value = frstfilenamepart + extn;
                    fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
                    string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
                    GetExcelSheetForEmp(PathName, UploadExcelName.Value);

                }
            }


    }

    private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
    {
        string excelFile = "EmpExcel/" + PathName;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        try
        {

            DataSet dss = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
            objConn = new OleDbConnection(connString);
            objConn.Open();
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return;
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (i == 0)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dss, "TABLE");

                }
                i++;
            }
            grdByExcel.DataSource = dss.Tables[0].DefaultView;
            grdByExcel.DataBind();


        }

        catch (Exception ex)
        {
            ViewState["Fuletypeidlist"] = "0";
            grdByExcel.DataSource = null;
            grdByExcel.DataBind();
        }
        finally
        {
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }

    }

How to find first element of array matching a boolean condition in JavaScript?

foundElement = myArray[myArray.findIndex(element => //condition here)];

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

Static image src in Vue.js template

declare new variable that the value contain the path of image

const imgLink = require('../../assets/your-image.png')

then call the variable

export default {
    name: 'onepage',
    data(){
        return{
            img: imgLink,
        }
    }
}

bind that on html, this the example:

<a href="#"><img v-bind:src="img" alt="" class="logo"></a>

hope it will help

How to remove gaps between subplots in matplotlib?

You can use gridspec to control the spacing between axes. There's more information here.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure(figsize = (4,4))
gs1 = gridspec.GridSpec(4, 4)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. 

for i in range(16):
   # i = i + 1 # grid spec indexes from 0
    ax1 = plt.subplot(gs1[i])
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')

plt.show()

axes very close together

variable or field declared void

The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like

initializeJSP(Experiment);

how to create dynamic two dimensional array in java?

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

How do I apply a diff patch on Windows?

Do you have two monitors? I was having the same issue with TortoiseMerge and I realized that when I disabled one of the monitors the little window with the file list showed up. Hope this helps you.

How to pipe list of files returned by find command to cat to view all the files

Here's my way to find file names that contain some content that I'm interested in, just a single bash line that nicely handles spaces in filenames too:

find . -name \*.xml | while read i; do grep '<?xml' "$i" >/dev/null; [ $? == 0 ] && echo $i; done

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Make sure you are loading from a URL such as:

https://www.youtube.com/embed/HIbAz29L-FA?modestbranding=1&playsinline=0&showinfo=0&enablejsapi=1&origin=https%3A%2F%2Fintercoin.org&widgetid=1

Note the "origin" component, as well as "enablejsapi=1". The origin must match what your domain is, and then it will be whitelisted and work.

Where is debug.keystore in Android Studio

It helped me.

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"

exapmle

USER_NAME_PC - Your PC username

How to align input forms in HTML

The accepted answer (setting an explicit width in pixels) makes it hard to make changes, and breaks when your users use a different font size. Using CSS tables, on the other hand, works great:

_x000D_
_x000D_
form  { display: table;      }_x000D_
p     { display: table-row;  }_x000D_
label { display: table-cell; }_x000D_
input { display: table-cell; }
_x000D_
<form>_x000D_
  <p>_x000D_
    <label for="a">Short label:</label>_x000D_
    <input id="a" type="text">_x000D_
  </p>_x000D_
  <p>_x000D_
    <label for="b">Very very very long label:</label>_x000D_
    <input id="b" type="text">_x000D_
  </p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Here's a JSFiddle: http://jsfiddle.net/DaS39/1/

And if you need the labels right-aligned, just add text-align: right to the labels: http://jsfiddle.net/DaS39/


EDIT: One more quick note: CSS tables also let you play with columns: for example, if you want to make the input fields take as much space as possible, you can add the following in your form

<div style="display: table-column;"></div>
<div style="display: table-column; width:100%;"></div>

you may want to add white-space: nowrap to the labels in that case.

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Filtering a list based on a list of booleans

Like so:

filtered_list = [i for (i, v) in zip(list_a, filter) if v]

Using zip is the pythonic way to iterate over multiple sequences in parallel, without needing any indexing. This assumes both sequences have the same length (zip stops after the shortest runs out). Using itertools for such a simple case is a bit overkill ...

One thing you do in your example you should really stop doing is comparing things to True, this is usually not necessary. Instead of if filter[idx]==True: ..., you can simply write if filter[idx]: ....

How to convert C# nullable int to int

You can use the Value property for assignment.

v2 = v1.Value;

Turning Sonar off for certain code

This is a FAQ. You can put //NOSONAR on the line triggering the warning. I prefer using the FindBugs mechanism though, which consists in adding the @SuppressFBWarnings annotation:

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value = "NAME_OF_THE_FINDBUGS_RULE_TO_IGNORE",
    justification = "Why you choose to ignore it")

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

MySQL - UPDATE query with LIMIT

You should highly consider using an ORDER BY if you intend to LIMIT your UPDATE, because otherwise it will update in the ordering of the table, which might not be correct.

But as Will A said, it only allows limit on row_count, not offset.

Apache - MySQL Service detected with wrong path. / Ports already in use

about this specific issue:

12:35:23  [mysql]   Found Path: "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" MySQL
12:35:23  [mysql]   Expected Path: c:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysql

notice that .exe is missing from 1st row at the end of mysqld.

To fix this, start regedit.exe and change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\mysql ImagePath by adding the .exe extension.

Restart xampp control panel and this error should not show up.

Disable browser's back button

I came up with a little hack that disables the back button using JavaScript. I checked it on chrome 10, firefox 3.6 and IE9:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
     window.location.href += "#";
     setTimeout("changeHashAgain()", "50"); 
}

function changeHashAgain() {
  window.location.href += "1";
}

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
         window.location.hash = storedHash;
    }
}, 50);


</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>

What is it doing?

From Comments:

This script leverages the fact that browsers consider whatever comes after the "#" sign in the URL as part of the browsing history. What it does is this: When the page loads, "#1" is added to the URL. After 50ms the "1" is removed. When the user clicks "back", the browser changes the URL back to what it was before the "1" was removed, BUT - it's the same web page, so the browser doesn't need to reload the page. – Yossi Shasho

How do I see which checkbox is checked?

I love short hands so:

$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

Get a list of distinct values in List

Distinct the Note class by Author

var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());

foreach(var item in DistinctItems)
{
    //Add to other List
}

How to change the colors of a PNG image easily?

If you are going to be programming an application to do all of this, the process will be something like this:

  1. Convert image from RGB to HSV
  2. adjust H value
  3. Convert image back to RGB
  4. Save image

How to pass values between Fragments

This simple implementation helps to pass data between fragments in a simple way. Think you want to pass data from 'Frgment1' to 'Fragment2'

In Fragment1(Set data to send)

 Bundle bundle = new Bundle();
 bundle.putString("key","Jhon Doe"); // set your parameteres

 Fragment2 nextFragment = new Fragment2();
 nextFragment.setArguments(bundle);

 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit();

In Fragment2 onCreateView method (Get parameteres)

String value = this.getArguments().getString("key");//get your parameters
Toast.makeText(getActivity(), value+" ", Toast.LENGTH_LONG).show();//show data in tost

How to redirect to a different domain using NGINX?

Temporary redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;

Permanent redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;

In nginx configuration file for specific site:

server {    
    server_name www.example.com;
    rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;

}

Fit Image in ImageButton in Android

Try to use android:scaleType="fitXY" in i-Imagebutton xml

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

In my case, it's related to the Toggle Vrapper Icon in the Eclipse.

If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity.

enter image description here

Creating a div element in jQuery

Technically $('<div></div>') will 'create' a div element (or more specifically a DIV DOM element) but won't add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append() method or such like).

The manipulation documentation gives you all the various options on how to add new elements.

How to set a single, main title above all the subplots with Pyplot?

A few points I find useful when applying this to my own plots:

  • I prefer the consistency of using fig.suptitle(title) rather than plt.suptitle(title)
  • When using fig.tight_layout() the title must be shifted with fig.subplots_adjust(top=0.88)
  • See answer below about fontsizes

Example code taken from subplots demo in matplotlib docs and adjusted with a master title.

A nice 4x4 plot

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

Need to ZIP an entire directory using Node.js

I ended up wrapping archiver to emulate JSZip, as refactoring through my project woult take too much effort. I understand Archiver might not be the best choice, but here you go.

// USAGE:
const zip=JSZipStream.to(myFileLocation)
    .onDone(()=>{})
    .onError(()=>{});

zip.file('something.txt','My content');
zip.folder('myfolder').file('something-inFolder.txt','My content');
zip.finalize();

// NodeJS file content:
    var fs = require('fs');
    var path = require('path');
    var archiver = require('archiver');

  function zipper(archive, settings) {
    return {
        output: null,
        streamToFile(dir) {
            const output = fs.createWriteStream(dir);
            this.output = output;
            archive.pipe(output);

            return this;
        },
        file(location, content) {
            if (settings.location) {
                location = path.join(settings.location, location);
            }
            archive.append(content, { name: location });
            return this;
        },
        folder(location) {
            if (settings.location) {
                location = path.join(settings.location, location);
            }
            return zipper(archive, { location: location });
        },
        finalize() {
            archive.finalize();
            return this;
        },
        onDone(method) {
            this.output.on('close', method);
            return this;
        },
        onError(method) {
            this.output.on('error', method);
            return this;
        }
    };
}

exports.JSzipStream = {
    to(destination) {
        console.log('stream to',destination)
        const archive = archiver('zip', {
            zlib: { level: 9 } // Sets the compression level.
        });
        return zipper(archive, {}).streamToFile(destination);
    }
};

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

How to input a regex in string.replace?

str.replace() does fixed replacements. Use re.sub() instead.

How to add spacing between columns?

This will be useful..

_x000D_
_x000D_
.list-item{_x000D_
  margin-right:-10px;_x000D_
   margin-top:10px;_x000D_
    margin-bottom: 10px;_x000D_
    border: 1px solid #eee;_x000D_
    padding: 0px;_x000D_
  }
_x000D_
<div class="col-md-4">_x000D_
  <div class="list-item">_x000D_
      <h2>Your name</h2> _x000D_
  </div>_x000D_
</div>_x000D_
<div class="col-md-4">_x000D_
   <div class="list-item"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If use want to increase or decrease further margin in right side of the box then simply edit margin-right property of list-item.

sample output

enter image description here

Laravel Eloquent limit and offset

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

Access Controller method from another controller in Laravel 5

This approach also works with same hierarchy of Controller files:

$printReport = new PrintReportController;

$prinReport->getPrintReport();

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

C# switch statement limitations - why?

It's important not to confuse the C# switch statement with the CIL switch instruction.

The CIL switch is a jump table, that requires an index into a set of jump addresses.

This is only useful if the C# switch's cases are adjacent:

case 3: blah; break;
case 4: blah; break;
case 5: blah; break;

But of little use if they aren't:

case 10: blah; break;
case 200: blah; break;
case 3000: blah; break;

(You'd need a table ~3000 entries in size, with only 3 slots used)

With non-adjacent expressions, the compiler may start to perform linear if-else-if-else checks.

With larger non- adjacent expression sets, the compiler may start with a binary tree search, and finally if-else-if-else the last few items.

With expression sets containing clumps of adjacent items, the compiler may binary tree search, and finally a CIL switch.

This is full of "mays" & "mights", and it is dependent on the compiler (may differ with Mono or Rotor).

I replicated your results on my machine using adjacent cases:

total time to execute a 10 way switch, 10000 iterations (ms) : 25.1383
approximate time per 10 way switch (ms) : 0.00251383

total time to execute a 50 way switch, 10000 iterations (ms) : 26.593
approximate time per 50 way switch (ms) : 0.0026593

total time to execute a 5000 way switch, 10000 iterations (ms) : 23.7094
approximate time per 5000 way switch (ms) : 0.00237094

total time to execute a 50000 way switch, 10000 iterations (ms) : 20.0933
approximate time per 50000 way switch (ms) : 0.00200933

Then I also did using non-adjacent case expressions:

total time to execute a 10 way switch, 10000 iterations (ms) : 19.6189
approximate time per 10 way switch (ms) : 0.00196189

total time to execute a 500 way switch, 10000 iterations (ms) : 19.1664
approximate time per 500 way switch (ms) : 0.00191664

total time to execute a 5000 way switch, 10000 iterations (ms) : 19.5871
approximate time per 5000 way switch (ms) : 0.00195871

A non-adjacent 50,000 case switch statement would not compile.
"An expression is too long or complex to compile near 'ConsoleApplication1.Program.Main(string[])'

What's funny here, is that the binary tree search appears a little (probably not statistically) quicker than the CIL switch instruction.

Brian, you've used the word "constant", which has a very definite meaning from a computational complexity theory perspective. While the simplistic adjacent integer example may produce CIL that is considered O(1) (constant), a sparse example is O(log n) (logarithmic), clustered examples lie somewhere in between, and small examples are O(n) (linear).

This doesn't even address the String situation, in which a static Generic.Dictionary<string,int32> may be created, and will suffer definite overhead on first use. Performance here will be dependent on the performance of Generic.Dictionary.

If you check the C# Language Specification (not the CIL spec) you'll find "15.7.2 The switch statement" makes no mention of "constant time" or that the underlying implementation even uses the CIL switch instruction (be very careful of assuming such things).

At the end of the day, a C# switch against an integer expression on a modern system is a sub-microsecond operation, and not normally worth worrying about.


Of course these times will depend on machines and conditions. I wouldn’t pay attention to these timing tests, the microsecond durations we’re talking about are dwarfed by any “real” code being run (and you must include some “real code” otherwise the compiler will optimise the branch away), or jitter in the system. My answers are based on using IL DASM to examine the CIL created by the C# compiler. Of course, this isn’t final, as the actual instructions the CPU runs are then created by the JIT.

I have checked the final CPU instructions actually executed on my x86 machine, and can confirm a simple adjacent set switch doing something like:

  jmp     ds:300025F0[eax*4]

Where a binary tree search is full of:

  cmp     ebx, 79Eh
  jg      3000352B
  cmp     ebx, 654h
  jg      300032BB
  …
  cmp     ebx, 0F82h
  jz      30005EEE

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

remote rejected master -> master (pre-receive hook declined)

In my case I had forgotten to use postgres in my production environment. I moved the sqlite3 gem into my development and test groups in my Gemfile. Everything worked after that.

Simple way to change the position of UIView?

The solution in the selected answer does not work in case of using Autolayout. If you are using Autolayout for views take a look at this answer.

what is .subscribe in angular?

In Angular (currently on Angular-6) .subscribe() is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.

The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.

An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.

Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-

Subscribe takes 3 methods as parameters each are functions:

  • next: For each item being emitted by the observable perform this function
  • error: If somewhere in the stream an error is found, do this method
  • complete: Once all items are complete from the stream, do this method

Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.

In the simple example above:

.subscribe(hero => this.hero = hero); basically says on this observable take the hero being emitted and set it to this.hero.

Adding this answer to give more context to Observables based off the documentation and my understanding.

Difference between static and shared libraries?

A static library is like a bookstore, and a shared library is like... a library. With the former, you get your own copy of the book/function to take home; with the latter you and everyone else go to the library to use the same book/function. So anyone who wants to use the (shared) library needs to know where it is, because you have to "go get" the book/function. With a static library, the book/function is yours to own, and you keep it within your home/program, and once you have it you don't care where or when you got it.

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

Substring in excel

In Excel, the substring function is called MID function, and indexOf is called FIND for case-sensitive location and SEARCH function for non-case-sensitive location. For the first portion of your text parsing the LEFT function may also be useful.

See all the text functions here: Text Functions (reference).

Full worksheet function reference lists available at:

    Excel functions (by category)
    Excel functions (alphabetical)

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

How to get current moment in ISO 8601 format with date, hour, and minute?

For systems where the default Time Zone is not UTC:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.

EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

How to search a specific value in all tables (PostgreSQL)?

If you're using IntelliJ add your DB to Database view then right click on databases and select full text search, it will list all tables and all fields for your specific text.

Batchfile to create backup and rename with timestamp

See if this is what you want to do:

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%

set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%

copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think I had the same requirement as Tim, but none of the answers provide for a 'viewport edge-to-edge columns with normal internal gutters' solution. Or another way to put it: how can I get my first and last columns to break into the container padding and flow to the edge of the viewport, while still maintaining normal gutters between the columns.

full width rows

From what I can tell, there is no neat and clean solution. This is what works for me, but it is well outside anything that would be supported by Bootstrap. But it works for now (Bootstrap 3.3.5 & 4.0-alpha).

http://www.bootply.com/ioWBaljBAd

Sample HTML:

<div class="container">
  <div class="row full-width-row">
    <div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
    </div>
  </div>
</div>

CSS:

.full-width-row {
  overflow-x: hidden;
}

.full-width-row > div {
  margin-left: -15px;
  margin-right: -15px;
}

The trick is to nest a div in between the row and the columns to generate the extra -15px margin to push into the container padding. The extra negative margin creates horizontal scroll (into whitespace) on small viewports. Adding overflow-x: hidden to the .row is required to suppress it.

This works the same for .container-fluid as .container.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Assume n=2. Then we have 2-1 = 1 on the left side and 2*1/2 = 1 on the right side.

Denote f(n) = (n-1)+(n-2)+(n-3)+...+1

Now assume we have tested up to n=k. Then we have to test for n=k+1.

on the left side we have k+(k-1)+(k-2)+...+1, so it's f(k)+k

On the right side we then have (k+1)*k/2 = (k^2+k)/2 = (k^2 +2k - k)/2 = k+(k-1)k/2 = kf(k)

So this have to hold for every k, and this concludes the proof.

Run a task every x-minutes with Windows Task Scheduler

The task must be configured in two steps.

First you create a simple task that start at 0:00, every day. Then, you go in Advanced... (or similar depending on the operating system you are on) and select the Repeat every X minutes option for 24 hours.

The key here is to find the advanced properties. If you are using the XP wizard, it will only offer you to launch the advanced dialog once you created the task.

On more recent versions of Windows (7+ I think?):

  1. Double click the task and a property window will show up.
  2. Click the Triggers tab.
  3. Double click the trigger details and the Edit Trigger window will show up.
  4. Under Advanced settings panel, tick Repeat task every xxx minutes, and set Indefinitely if you need.
  5. Finally, click ok.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

How to get row data by clicking a button in a row in an ASP.NET gridview

<ItemTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="MyButtonClick" />
</ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e)
{
     //Get the button that raised the event
Button btn = (Button)sender;

    //Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

What are named pipes?

Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine. What named pipes give you is a way to send your data without having the performance penalty of involving the network stack.

Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests. In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request. Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe).

By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners.

The advantage of named pipes is that it is usually much faster, and frees up network stack resources.

-- BTW, in the Windows world, you can also have named pipes to remote machines -- but in that case, the named pipe is transported over TCP/IP, so you will lose performance. Use named pipes for local machine communication.

How exactly to use Notification.Builder

In case it helps anyone... I was having a lot of trouble with setting up notifications using the support package when testing against newer an older API's. I was able to get them to work on the newer device but would get an error testing on the old device. What finally got it working for me was to delete all the imports related to the notification functions. In particular the NotificationCompat and the TaskStackBuilder. It seems that while setting up my code in the beginning the imports where added from the newer build and not from the support package. Then when I wanted to implement these items later in eclipse, I wasn't prompted to import them again. Hope that makes sense, and that it helps someone else out :)

Comparing two strings in C?

To compare two C strings (char *), use strcmp(). The function returns 0 when the strings are equal, so you would need to use this in your code:

if (strcmp(namet2, nameIt2) != 0)

If you (wrongly) use

if (namet2 != nameIt2)

you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).

Simple dictionary in C++

While using a std::map is fine or using a 256-sized char table would be fine, you could save yourself an enormous amount of space agony by simply using an enum. If you have C++11 features, you can use enum class for strong-typing:

// First, we define base-pairs. Because regular enums
// Pollute the global namespace, I'm using "enum class". 
enum class BasePair {
    A,
    T,
    C,
    G
};

// Let's cut out the nonsense and make this easy:
// A is 0, T is 1, C is 2, G is 3.
// These are indices into our table
// Now, everything can be so much easier
BasePair Complimentary[4] = {
    T, // Compliment of A
    A, // Compliment of T
    G, // Compliment of C
    C, // Compliment of G
};

Usage becomes simple:

int main (int argc, char* argv[] ) {
    BasePair bp = BasePair::A;
    BasePair complimentbp = Complimentary[(int)bp];
}

If this is too much for you, you can define some helpers to get human-readable ASCII characters and also to get the base pair compliment so you're not doing (int) casts all the time:

BasePair Compliment ( BasePair bp ) {
    return Complimentary[(int)bp]; // Move the pain here
}

// Define a conversion table somewhere in your program
char BasePairToChar[4] = { 'A', 'T', 'C', 'G' };
char ToCharacter ( BasePair bp ) {
    return BasePairToChar[ (int)bp ];
}

It's clean, it's simple, and its efficient.

Now, suddenly, you don't have a 256 byte table. You're also not storing characters (1 byte each), and thus if you're writing this to a file, you can write 2 bits per Base pair instead of 1 byte (8 bits) per base pair. I had to work with Bioinformatics Files that stored data as 1 character each. The benefit is it was human-readable. The con is that what should have been a 250 MB file ended up taking 1 GB of space. Movement and storage and usage was a nightmare. Of coursse, 250 MB is being generous when accounting for even Worm DNA. No human is going to read through 1 GB worth of base pairs anyhow.

Docker: adding a file from a parent directory

Adding some code snippets to support the accepted answer.

Directory structure :

setup/
 |__docker/DockerFile
 |__target/scripts/<myscripts.sh>
src/
 |__<my source files>

Docker file entry:

RUN mkdir -p /home/vagrant/dockerws/chatServerInstaller/scripts/
RUN mkdir -p /home/vagrant/dockerws/chatServerInstaller/src/
WORKDIR /home/vagrant/dockerws/chatServerInstaller

#Copy all the required files from host's file system to the container file system.
COPY setup/target/scripts/install_x.sh scripts/
COPY setup/target/scripts/install_y.sh scripts/
COPY src/ src/

Command used to build the docker image

docker build -t test:latest -f setup/docker/Dockerfile .

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

How do I make a relative reference to another workbook in Excel?

easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")

however indirect() has performance drawbacks if lot of links in workbook

I miss construct like: ['../Data.ods']#Sheet1.A1 in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

How can I get npm start at a different directory?

This one-liner should work too:

(cd /path/to/your/app && npm start)

Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:

(cd /path/to/your/app && npm start && cd -)

I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I solved it by myself.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>

How to check if a column is empty or null using SQL query select statement?

select isnull(nullif(CAR_OWNER_TEL, ''), 'NULLLLL')  PHONE from TABLE

will replace CAR_OWNER_TEL if empty by NULLLLL (MS SQL)

WebView and HTML5 <video>

Actually, it seems sufficient to merely attach a stock WebChromeClient to the client view, ala

mWebView.setWebChromeClient(new WebChromeClient());

and you need to have hardware acceleration turned on!

At least, if you don't need to play a full-screen video, there's no need to pull the VideoView out of the WebView and push it into the Activity's view. It will play in the video element's allotted rect.

Any ideas how to intercept the expand video button?

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

Font size relative to the user's screen resolution?

@media screen and (max-width : 320px)
{
  body or yourdiv element
  {
    font:<size>px/em/rm;
  }
}
@media screen and (max-width : 1204px)
{
  body or yourdiv element
  {
    font:<size>px/em/rm;
  }
}

You can give it manually according to screen size of screen.Just have a look of different screen size and add manually the font size.

Unable to set default python version to python3 in ubuntu

At First Install python3 and pip3

sudo apt-get install python3 python3-pip

then in your terminal run

alias python=python3

Check the version of python in your machine.

python --version

Java 256-bit AES Password-Based Encryption

Share the password (a char[]) and salt (a byte[]—8 bytes selected by a SecureRandom makes a good salt—which doesn't need to be kept secret) with the recipient out-of-band. Then to derive a good key from this information:

/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

The magic numbers (which could be defined as constants somewhere) 65536 and 256 are the key derivation iteration count and the key size, respectively.

The key derivation function is iterated to require significant computational effort, and that prevents attackers from quickly trying many different passwords. The iteration count can be changed depending on the computing resources available.

The key size can be reduced to 128 bits, which is still considered "strong" encryption, but it doesn't give much of a safety margin if attacks are discovered that weaken AES.

Used with a proper block-chaining mode, the same derived key can be used to encrypt many messages. In Cipher Block Chaining (CBC), a random initialization vector (IV) is generated for each message, yielding different cipher text even if the plain text is identical. CBC may not be the most secure mode available to you (see AEAD below); there are many other modes with different security properties, but they all use a similar random input. In any case, the outputs of each encryption operation are the cipher text and the initialization vector:

/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes(StandardCharsets.UTF_8));

Store the ciphertext and the iv. On decryption, the SecretKey is regenerated in exactly the same way, using using the password with the same salt and iteration parameters. Initialize the cipher with this key and the initialization vector stored with the message:

/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
System.out.println(plaintext);

Java 7 included API support for AEAD cipher modes, and the "SunJCE" provider included with OpenJDK and Oracle distributions implements these beginning with Java 8. One of these modes is strongly recommended in place of CBC; it will protect the integrity of the data as well as their privacy.


A java.security.InvalidKeyException with the message "Illegal key size or default parameters" means that the cryptography strength is limited; the unlimited strength jurisdiction policy files are not in the correct location. In a JDK, they should be placed under ${jdk}/jre/lib/security

Based on the problem description, it sounds like the policy files are not correctly installed. Systems can easily have multiple Java runtimes; double-check to make sure that the correct location is being used.

Iterating through populated rows

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next

Spring,Request method 'POST' not supported

For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"

I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.

How can I use interface as a C# generic type constraint?

If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.

  • I let my interfaces, which came into question, inherit an empty interface IInterface.
  • I constrained the generic T parameter to be of IInterface

In source, it looks like this:

  • Any interface you want to be passed as the generic parameter:

    public interface IWhatever : IInterface
    {
        // IWhatever specific declarations
    }
    
  • IInterface:

    public interface IInterface
    {
        // Nothing in here, keep moving
    }
    
  • The class on which you want to put the type constraint:

    public class WorldPeaceGenerator<T> where T : IInterface
    {
        // Actual world peace generating code
    }
    

Regular expression for excluding special characters

Use This one

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

JavaScript - Getting HTML form values

<form id='form'>
    <input type='text' name='title'>
    <input type='text' name='text'>
    <input type='email' name='email'>
</form>
const element = document.getElementByID('#form')
const data = new FormData(element)
const form = Array.from(data.entries())
/*
form = [
    ["title", "a"]
    ["text", "b"]
    ["email", "c"]
]
*/
for (const [name, value] of form) {
    console.log({ name, value })
    /*
    {name: "title", value: "a"}
    {name: "text", value: "b"}
    {name: "email", value: "c"}
    */
}

How to change or add theme to Android Studio?

I am using android studio 2.2.3 and I am able to change theme by following steps

  1. go to File > Setting it open an window like attach image
  2. then Editor > Colors & Fonts
  3. Select theme from Scheme dropdownlist
  4. now select Ok

enter image description here

How to get primary key of table?

I use SHOW INDEX FROM table ; it gives me alot of informations ; if the key is unique, its sequenece in the index, the collation, sub part, if null, its type and comment if exists, see screenshot herehere

Collections.emptyList() returns a List<Object>?

The issue you're encountering is that even though the method emptyList() returns List<T>, you haven't provided it with the type, so it defaults to returning List<Object>. You can supply the type parameter, and have your code behave as expected, like this:

public Person(String name) {
  this(name,Collections.<String>emptyList());
}

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

public Person(String name) {
  List<String> emptyList = Collections.emptyList();
  this(name, emptyList);
}

then the emptyList() call would correctly return a List<String>.

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Regarding [Console]::WriteLine() - you should use it if you are going to use pipelines in CMD (not in powershell). Say you want your ps1 to stream a lot of data to stdout, and some other utility to consume/transform it. If you use Write-Host in the script it will be much slower.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

In my case, I had to do this

 // Initialization in the dom
 // Consider the muted attribute
 <audio id="notification" src="path/to/sound.mp3" muted></audio>


 // in the js code unmute the audio once the event happened
 document.getElementById('notification').muted = false;
 document.getElementById('notification').play();

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

How to let an ASMX file output JSON

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Firefox does allow you to store data in the clipboard, but due to security implications it is disabled by default. See how to enable it in "Granting JavaScript access to the clipboard" in the Mozilla Firefox knowledge base.

The solution offered by amdfan is the best if you are having a lot of users and configuring their browser isn't an option. Though you could test if the clipboard is available and provide a link for changing the settings, if the users are tech savvy. The JavaScript editor TinyMCE follows this approach.

how to release localhost from Error: listen EADDRINUSE

simply kill the node as pkill -9 node in terminal of ubantu than start node

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

What are the uses of "using" in C#?

You can make use of the alias namespace by way of the following example:

using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to e.g.

LegacyEntities.Account

instead of

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

or simply

Account   // It is not obvious this is a legacy entity

Appending an id to a list if not already present in a string

I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

input = '350882 348521 350166\r\n'
list.append([int(x) for x in input.split()])

Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

list = ['350882 348521 350166\r\n']
id = 348521
if id not in [int(y) for x in list for y in x.split()]:
    list.append(id)
print list

How can I find and run the keytool

Keytool is part of the Java SDK. You should be able to find it in your Java SDK directory e.g. C:\Program Files\Java\jdk1.6.0_14\bin

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

In case you have trouble building boost or prefer not to do that, an alternative is to download the lib files from SourceForge. The link will take you to a folder of zipped lib and dll files for version 1.51. But, you should be able to edit the link to specify the version of choice. Apparently the installer from BoostPro has some issues.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

Force decimal point instead of comma in HTML5 number input (client-side)

one option is javascript parseFloat()... never do parse a "text chain" --> 12.3456 with point to a int... 123456 (int remove the point) parse a text chain to a FLOAT...

to send this coords to a server do this sending a text chain. HTTP only sends TEXT

in the client keep out of parsing the input coords with "int", work with text strings

if you print the cords in the html with php or similar... float to text and print in html

error: pathspec 'test-branch' did not match any file(s) known to git

The modern Git should able to detect remote branches and create a local one on checkout.

However if you did a shallow clone (e.g. with --depth 1), try the following commands to correct it:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch --all

and try to checkout out the branch again.

Alternatively try to unshallow your clone, e.g. git fetch --unshallow and try again.

See also: How to fetch all remote branches?

Rename all files in a folder with a prefix in a single command

With rnm (you will need to install it):

rnm -ns 'Unix_/fn/' *

Or

rnm -rs '/^/Unix_/' *

P.S : I am the author of this tool.

How can I use Bash syntax in Makefile targets?

There is a way to do this without explicitly setting your SHELL variable to point to bash. This can be useful if you have many makefiles since SHELL isn't inherited by subsequent makefiles or taken from the environment. You also need to be sure that anyone who compiles your code configures their system this way.

If you run sudo dpkg-reconfigure dash and answer 'no' to the prompt, your system will not use dash as the default shell. It will then point to bash (at least in Ubuntu). Note that using dash as your system shell is a bit more efficient though.

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Closing JFrame with button click

It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

C++ deprecated conversion from string constant to 'char*'

Maybe you can try this:

void foo(const char* str) 
{
    // Do something
}

foo("Hello")

It works for me

SELECT with a Replace()

if you want any hope of ever using an index, store the data in a consistent manner (with the spaces removed). Either just remove the spaces or add a persisted computed column, Then you can just select from that column and not have to add all the space removing overhead every time you run your query.

add a PERSISTED computed column:

ALTER TABLE Contacts ADD PostcodeSpaceFree AS Replace(Postcode, ' ', '') PERSISTED 
go
CREATE NONCLUSTERED INDEX IX_Contacts_PostcodeSpaceFree 
ON Contacts (PostcodeSpaceFree) --INCLUDE (covered columns here!!)
go

to just fix the column by removing the spaces use:

UPDATE Contacts
    SET Postcode=Replace(Postcode, ' ', '')

now you can search like this, either select can use an index:

--search the PERSISTED computed column
SELECT 
    PostcodeSpaceFree 
    FROM Contacts
    WHERE PostcodeSpaceFree  LIKE 'NW101%'

or

--search the fixed (spaces removed column)
SELECT 
    Postcode
    FROM Contacts
    WHERE PostcodeLIKE 'NW101%'

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

TL;DR

  1. npm uninstall node-sass
  2. npm install [email protected]

Or, if using yarn (default in newer CRA versions)

  1. yarn remove node-sass
  2. yarn add [email protected]

Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.


Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.


Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).

Uninstall node-sass

npm uninstall node-sass

Then install the latest version (before 5.0)

npm install [email protected]


Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass instead, which is a node distribution of dart-sass compiled to pure JavaScript. Be warned though:

Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation

Regex to replace multiple spaces with a single space

We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.

Add the text into some file say test

manjeet-laptop:Desktop manjeet$ cat test
"The dog      has a long   tail, and it     is RED!"

We can use the following regex to replace all white spaces with single space

manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"

Hope this serves the purpose

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You could create your own class of type Quiz and then deserialize with strong type:

Example:

quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
                 new JsonSerializerSettings
                 {
                     Error = delegate(object sender1, ErrorEventArgs args1)
                     {
                         errors.Add(args1.ErrorContext.Error.Message);
                         args1.ErrorContext.Handled = true;
                     }
                 });

And you could also apply a schema validation.

http://james.newtonking.com/projects/json/help/index.html

Service will not start: error 1067: the process terminated unexpectedly

I resolved the problem.This is for EAServer Windows Service

Resolution is --> Open Regedit in Run prompt

Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer

In parameters, give SERVERNAME entry as EAServer.

[It is sometime overwritten with Envirnoment variable : Path value]

How does ApplicationContextAware work in Spring?

Spring source code to explain how ApplicationContextAware work
when you use ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
In AbstractApplicationContext class,the refresh() method have the following code:

// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);

enter this method,beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); will add ApplicationContextAwareProcessor to AbstractrBeanFactory.

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Tell the internal bean factory to use the context's class loader etc.
        beanFactory.setBeanClassLoader(getClassLoader());
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
        // Configure the bean factory with context callbacks.
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........

When spring initialize bean in AbstractAutowireCapableBeanFactory, in method initializeBean,call applyBeanPostProcessorsBeforeInitialization to implement the bean post process. the process include inject the applicationContext.

@Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }

when BeanPostProcessor implement Objectto execute the postProcessBeforeInitialization method,for example ApplicationContextAwareProcessor that added before.

private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof EnvironmentAware) {
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            }
            if (bean instanceof EmbeddedValueResolverAware) {
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
                        new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
            }
            if (bean instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            }
            if (bean instanceof ApplicationEventPublisherAware) {
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            }
            if (bean instanceof MessageSourceAware) {
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            }
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

Disable browser 'Save Password' functionality

IMHO,
The best way is to randomize the name of the input field that has type=password. Use a prefix of "pwd" and then a random number. Create the field dynamically and present the form to the user.

Your log-in form will look like...

<form>
   <input type=password id=pwd67584 ...>
   <input type=text id=username ...>
   <input type=submit>
</form>

Then, on the server side, when you analyze the form posted by the client, catch the field with a name that starts with "pwd" and use it as 'password'.

Duplicate keys in .NET dictionaries?

The way I use is just a

Dictionary<string, List<string>>

This way you have a single key holding a list of strings.

Example:

List<string> value = new List<string>();
if (dictionary.Contains(key)) {
     value = dictionary[key];
}
value.Add(newValue);

How should we manage jdk8 stream for null values

Although the answers are 100% correct, a small suggestion to improve null case handling of the list itself with Optional:

 List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList) will allow you to handle nicely the case when listOfStuff is null and return an emptyList instead of failing with NullPointerException.

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

Integer expression expected error in shell script

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
     Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
     Something something \n
else \n
    Yes it works for me :) \n

How to create a new variable in a data.frame based on a condition?

If you have a very limited number of levels, you could try converting y into factor and change its levels.

> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
  x y    w
1 1 1 good
2 2 4 fair
3 4 5  bad

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

Calling startActivity() from outside of an Activity?

For Multiple Instance of the same activity , use the following snippet,

Note : This snippet, I am using outside of my Activity. Make sure your AndroidManifest file doesn't contain android:launchMode="singleTop|singleInstance". if needed, you can change it to android:launchMode="standard".

Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);

This works fine for me. Hope, this saves times for someone. If anybody finds a better way, please share with us.