Programs & Examples On #Tokyo tyrant

Tokyo Tyrant is a package of network interface for Tokyo Cabinet, a key value database.

uncaught syntaxerror unexpected token U JSON

Most common case of this error happening is using template that is generating the control then changing the way id and/or nameare being generated by 'overriding' default template with something like

@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} )

and then forgetting to change ValidationMessageFor to

@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] })    

Hope this saves you some time.

Cannot catch toolbar home button click event

For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

        Dim aDate As DateTime = #3/1/2008# 'sample date
    Dim StartDate As DateTime = aDate.AddMonths(-1).AddDays(-(aDate.Day - 1))
    Dim EndDate As DateTime = StartDate.AddDays(DateTime.DaysInMonth(StartDate.Year, StartDate.Month) - 1)

    'to access just the date portion
    ' StartDate.Date
    ' EndDate.Date

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

What is git tag, How to create tags & How to checkout git remote tag(s)

This is bit out of context but in case you are here because you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

Is there a "standard" format for command line/shell help text?

yes, you're on the right track.

yes, square brackets are the usual indicator for optional items.

Typically, as you have sketched out, there is a commandline summary at the top, followed by details, ideally with samples for each option. (Your example shows lines in between each option description, but I assume that is an editing issue, and that your real program outputs indented option listings with no blank lines in between. This would be the standard to follow in any case.)

A newer trend, (maybe there is a POSIX specification that addresses this?), is the elimination of the man page system for documentation, and including all information that would be in a manpage as part of the program --help output. This extra will include longer descriptions, concepts explained, usage samples, known limitations and bugs, how to report a bug, and possibly a 'see also' section for related commands.

I hope this helps.

TabLayout tab selection

With the TabLayout provided by the Material Components Library just use the selectTab method:

TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));

enter image description here

It requires version 1.1.0.

Upload Progress Bar in PHP

Another uploader full JS : http://developers.sirika.com/mfu/

  • Its free ( BSD licence )
  • Internationalizable
  • cross browser compliant
  • you have the choice to install APC or not ( underterminate progress bar VS determinate progress bar )
  • Customizable look as it uses dojo template mechanism. You can add your class / Ids in the te templates according to your css

have fun

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

JavaScript Nested function

function x() {}

is equivalent (or very similar) to

var x = function() {}

unless I'm mistaken.

So there is nothing funny going on.

How do I spool to a CSV formatted file using SQLPLUS?

You could use csv hint. See the following example:

select /*csv*/ table_name, tablespace_name
from all_tables
where owner = 'SYS'
and tablespace_name is not null;

How to find NSDocumentDirectory in Swift?

Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.

But as to the reasons:

First, you are confusing the argument names and types. Take a look at the function definition:

func NSSearchPathForDirectoriesInDomains(
    directory: NSSearchPathDirectory,
    domainMask: NSSearchPathDomainMask,
    expandTilde: Bool) -> AnyObject[]!
  • directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.
  • Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
  • And finally, it returns an array, not just a single path.

So that leaves us with (updated for Swift 2.0):

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

and for Swift 3:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

Easiest way to convert a List to a Set in Java

Set<Foo> foo = new HashSet<Foo>(myList);

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

Fastest way to check if string contains only digits

If you are concerned about performance, use neither int.TryParse nor Regex - write your own (simple) function (DigitsOnly or DigitsOnly2 below, but not DigitsOnly3 - LINQ seems to incur a significant overhead).

Also, be aware that int.TryParse will fail if the string is too long to "fit" into int.

This simple benchmark...

class Program {

    static bool DigitsOnly(string s) {
        int len = s.Length;
        for (int i = 0; i < len; ++i) {
            char c = s[i];
            if (c < '0' || c > '9')
                return false;
        }
        return true;
    }

    static bool DigitsOnly2(string s) {
        foreach (char c in s) {
            if (c < '0' || c > '9')
                return false;
        }
        return true;
    }

    static bool DigitsOnly3(string s) {
        return s.All(c => c >= '0' && c <= '9');
    }

    static void Main(string[] args) {

        const string s1 = "916734184";
        const string s2 = "916734a84";

        const int iterations = 1000000;
        var sw = new Stopwatch();

        sw.Restart();
        for (int i = 0 ; i < iterations; ++i) {
            bool success = DigitsOnly(s1);
            bool failure = DigitsOnly(s2);
        }
        sw.Stop();
        Console.WriteLine(string.Format("DigitsOnly: {0}", sw.Elapsed));

        sw.Restart();
        for (int i = 0; i < iterations; ++i) {
            bool success = DigitsOnly2(s1);
            bool failure = DigitsOnly2(s2);
        }
        sw.Stop();
        Console.WriteLine(string.Format("DigitsOnly2: {0}", sw.Elapsed));

        sw.Restart();
        for (int i = 0; i < iterations; ++i) {
            bool success = DigitsOnly3(s1);
            bool failure = DigitsOnly3(s2);
        }
        sw.Stop();
        Console.WriteLine(string.Format("DigitsOnly3: {0}", sw.Elapsed));

        sw.Restart();
        for (int i = 0; i < iterations; ++i) {
            int dummy;
            bool success = int.TryParse(s1, out dummy);
            bool failure = int.TryParse(s2, out dummy);
        }
        sw.Stop();
        Console.WriteLine(string.Format("int.TryParse: {0}", sw.Elapsed));

        sw.Restart();
        var regex = new Regex("^[0-9]+$", RegexOptions.Compiled);
        for (int i = 0; i < iterations; ++i) {
            bool success = regex.IsMatch(s1);
            bool failure = regex.IsMatch(s2);
        }
        sw.Stop();
        Console.WriteLine(string.Format("Regex.IsMatch: {0}", sw.Elapsed));

    }

}

...produces the following result...

DigitsOnly: 00:00:00.0346094
DigitsOnly2: 00:00:00.0365220
DigitsOnly3: 00:00:00.2669425
int.TryParse: 00:00:00.3405548
Regex.IsMatch: 00:00:00.7017648

Find string between two substrings

These solutions assume the start string and final string are different. Here is a solution I use for an entire file when the initial and final indicators are the same, assuming the entire file is read using readlines():

def extractstring(line,flag='$'):
    if flag in line: # $ is the flag
        dex1=line.index(flag)
        subline=line[dex1+1:-1] #leave out flag (+1) to end of line
        dex2=subline.index(flag)
        string=subline[0:dex2].strip() #does not include last flag, strip whitespace
    return(string)

Example:

lines=['asdf 1qr3 qtqay 45q at $A NEWT?$ asdfa afeasd',
    'afafoaltat $I GOT BETTER!$ derpity derp derp']
for line in lines:
    string=extractstring(line,flag='$')
    print(string)

Gives:

A NEWT?
I GOT BETTER!

How to find the minimum value of a column in R?

If you need minimal value for particular column

min(data[,2])

Note: R considers NA both the minimum and maximum value so if you have NA's in your column, they return: NA. To remedy, use:

min(data[,2], na.rm=T)

Set background color in PHP?

Try this:

<style type="text/css">
  <?php include("bg-color.php") ?>
</style>

And bg-color.php can be something like:

<?php
//Don't forget to sanitize the input
$colour = $_GET["colour"];
?>
body {
    background-color: #<?php echo $colour ?>;
}

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Regex match everything after question mark?

\?(.*)

You want the content of the first capture group.

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to draw rounded rectangle in Android UI?

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:padding="10dp"
  android:shape="rectangle">
    <solid android:color="@color/colorAccent" /> 
    <corners
      android:bottomLeftRadius="500dp"
      android:bottomRightRadius="500dp"
      android:topLeftRadius="500dp"
      android:topRightRadius="500dp" />
</shape>

Now, in which element you want to use this shape just add: android:background="@drawable/custom_round_ui_shape"

Create a new XML in drawable named "custom_round_ui_shape"

What is a StackOverflowError?

The term "stack overrun (overflow)" is often used but a misnomer; attacks do not overflow the stack but buffers on the stack.

-- from lecture slides of Prof. Dr. Dieter Gollmann

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

Getting an element from a Set

Convert set to list, and then use get method of list

Set<Foo> set = ...;
List<Foo> list = new ArrayList<Foo>(set);
Foo obj = list.get(0);

Import Maven dependencies in IntelliJ IDEA

I faced the same problem and tried everything suggested which did not solve the issue, I was using Intellij version 13.1.3

Finally after spending more than couple of hours trying to fix it, I decided to try an upgraded version and opened the project in version 14.1.4 which ultimately resolved the issue. I would think this as a probable bug in the previous version.

I hope this helps!

Android EditText for password with android:hint

If you set

android:inputType="textPassword"

this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use

android:password="true"

property which allows you to enter any type of password without any restriction.

If you want to provide hint use

android:hint="hint text goes here"

example:

android:hint="password"

How to add new activity to existing project in Android Studio?

To add an Activity using Android Studio.

This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.

[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.

enter image description here

  1. Right click either java package/java folder/module, I recommend to select a java package then right click it so that the destination of the Activity will be saved there
  2. Select/Click New
  3. Select Activity
  4. Choose an Activity that you want to create, probably the basic one.

To add a Service, or a BroadcastReceiver, just do the same step.

How to change font of UIButton with Swift

Example: button.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)

  • If you want to use defaul font from it's own family, use for example: "HelveticaNeue"
  • If you want to specify family font, use for example: "HelveticaNeue-Bold"

How to concatenate strings in django templates?

In my project I did it like this:

@register.simple_tag()
def format_string(string: str, *args: str) -> str:
    """
    Adds [args] values to [string]
    String format [string]: "Drew %s dad's %s dead."
    Function call in template: {% format_string string "Dodd's" "dog's" %}
    Result: "Drew Dodd's dad's dog's dead."
    """
    return string % args

Here, the string you want concatenate and the args can come from the view, for example.

In template and using your case:

{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}

The nice part is that format_string can be reused for any type of string formatting in templates

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

What are all possible pos tags of NLTK?

You can download the list here: ftp://ftp.cis.upenn.edu/pub/treebank/doc/tagguide.ps.gz. It includes confusing parts of speech, capitalization, and other conventions. Also, wikipedia has an interesting section similar to this. Section: Part-of-speech tags used.

How to change JAVA.HOME for Eclipse/ANT

Under Windows you need to follow:

Start -> Control Panel -> System -> Advanced -> Environment Variables.

... and you need to set JAVA_HOME (which is distinct from the PATH variable you mention) to reference the JDK home directory, not the bin sub-directory; e.g. "C:\program files\java\jdk".

How to get error information when HttpWebRequest.GetResponse() fails

Is this possible using HttpWebRequest and HttpWebResponse?

You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.

So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

Remove substring from the string

You can use the slice method:

a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"

there is a non '!' version as well. More info can be seen in the documentation about other versions as well: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

Shell Script: Execute a python program from within a shell script

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

mysqli or PDO - what are the pros and cons?

There's one thing to keep in mind.

Mysqli does not support fetch_assoc() function which would return the columns with keys representing column names. Of course it's possible to write your own function to do that, it's not even very long, but I had really hard time writing it (for non-believers: if it seems easy to you, try it on your own some time and don't cheat :) )

Pass by Reference / Value in C++

Thanks so much everyone for all these input!

I quoted that sentence from a lecture note online: http://www.cs.cornell.edu/courses/cs213/2002fa/lectures/Lecture02/Lecture02.pdf

the first page the 6th slide

" Pass by VALUE The value of a variable is passed along to the function If the function modifies that value, the modifications stay within the scope of that function.

Pass by REFERENCE A reference to the variable is passed along to the function If the function modifies that value, the modifications appear also within the scope of the calling function.

"

Thanks so much again!

How do I hide the status bar in a Swift iOS app?

If you are presenting the view controller modally, try

viewController.hidesBottomBarWhenPushed = true
viewController.modalPresentationCapturesStatusBarAppearance = true

How do you make a div follow as you scroll?

Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.

div
{
    position:fixed;
    top:20px;
}

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

You perhaps use the wrong username.

I had a similar error. Ensure you're not using uppercase while logging into server.

Example: [email protected]

If you use ->setUsername('JacekPL'), this can cause an error. Use ->setUsername('jacekpl') instead. This solved my problem.

Command to collapse all sections of code?

In Visual Studio 2019:

Go to Tools > Options > Keyboard.

Search for Edit.ToggleAllOutlining

Use the shortcut listed there, or assign it the shortcut of choice.

How to disable EditText in Android

The XML editable property is deprecated since API LEVEL 15.

You should use now the inputType property with the value none. But there is a bug that makes this functionality useless.

Here you can follow the issue status.

Case insensitive comparison NSString

 NSString *stringA;
 NSString *stringB;

 if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
     // match
 }

Note: stringA && is required because when stringA is nil:

 stringA = nil;
 [stringA caseInsensitiveCompare:stringB] // return 0

and so happens NSOrderedSame is also defined as 0.

The following example is a typical pitfall:

 NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
 if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
     // what happens if "Rank" is not found in standardUserDefaults
 }

What is base 64 encoding used for?

To expand a bit on what Brad is saying: many transport mechanisms for email and Usenet and other ways of moving data are not "8 bit clean", which means that characters outside the standard ascii character set might be mangled in transit - for instance, 0x0D might be seen as a carriage return, and turned into a carriage return and line feed. Base 64 maps all the binary characters into several standard ascii letters and numbers and punctuation so they won't be mangled this way.

PHP decoding and encoding json with unicode characters

JSON_UNESCAPED_UNICODE was added in PHP 5.4 so it looks like you need upgrade your version of PHP to take advantage of it. 5.4 is not released yet though! :(

There is a 5.4 alpha release candidate on QA though if you want to play on your development machine.

Print text in Oracle SQL Developer SQL Worksheet window

You could set echo to on:

set echo on
REM Querying table
select * from dual;

In SQLDeveloper, hit F5 to run as a script.

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

To make the autoplay on html 5 elements work after the chrome 66 update you just need to add the muted property to the video element.

So your current video HTML

_x000D_
_x000D_
<video_x000D_
    title="Advertisement"_x000D_
    webkit-playsinline="true"_x000D_
    playsinline="true"_x000D_
    style="background-color: rgb(0, 0, 0); position: absolute; width: 640px; height: 360px;"_x000D_
    src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"_x000D_
    autoplay=""></video>
_x000D_
_x000D_
_x000D_

Just needs muted="muted"

_x000D_
_x000D_
<video_x000D_
    title="Advertisement"_x000D_
    style="background-color: rgb(0, 0, 0); position: absolute; width: 640px; height: 360px;"_x000D_
    src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"_x000D_
    autoplay="true"_x000D_
    muted="muted"></video>
_x000D_
_x000D_
_x000D_

I believe the chrome 66 update is trying to stop tabs creating random noise on the users tabs. That's why the muted property make the autoplay work again.

Python coding standards/best practices

I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.

If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

how to convert object into string in php

You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.

If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.

Some code to demonstrate the difference:

class MyObject {

  protected $name = 'JJ';

  public function __toString() {
    return "My name is: {$this->name}\n";
  }

}

$obj = new MyObject;

echo $obj;
echo serialize($obj);

Output:

My name is: JJ

O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}

Do I really need to encode '&' as '&amp;'?

if & is used in html then you should escape it

If & is used in javascript strings e.g. an alert('This & that'); or document.href you don't need to use it.

If you're using document.write then you should use it e.g. document.write(<p>this &amp; that</p>)

What is the Angular equivalent to an AngularJS $watch?

Try this when your application still demands $parse, $eval, $watch like behavior in Angular

https://github.com/vinayk406/angular-expression-parser

How do I post form data with fetch api?

Client

Do not set the content-type header.

// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');

fetch("api/SampleData",
    {
        body: formData,
        method: "post"
    });

Server

Use the FromForm attribute to specify that binding source is form data.

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpPost]
    public IActionResult Create([FromForm]UserDto dto)
    {
        return Ok();
    }
}

public class UserDto
{
    public string Name { get; set; }
    public string Password { get; set; }
}

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I had the same problem and solved it by passing path to a directory where CA keys are stored. On Ubuntu it was:

openssl s_client -CApath /etc/ssl/certs/ -connect address.com:443

C# 'or' operator?

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

Can I add jars to maven 2 build classpath without installing them?

You may create local repository on your project

For example if you have libs folder in project structure

  • In libs folder you should create directory structure like: /groupId/artifactId/version/artifactId-version.jar

  • In your pom.xml you should register repository

    <repository>
        <id>ProjectRepo</id>
        <name>ProjectRepo</name>
        <url>file://${project.basedir}/libs</url>
    </repository>
    
  • and add dependency as usual

    <dependency>
        <groupId>groupId</groupId>
        <artifactId>artifactId</artifactId>
        <version>version</version>
    </dependency>
    

That is all.

For detailed information: How to add external libraries in Maven

How to check if memcache or memcached is installed for PHP?

You have several options ;)

$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');

What port is used by Java RMI connection?

The port is available here: java.rmi.registry.Registry.REGISTRY_PORT (1099)

Codeigniter $this->input->post() empty while $_POST is working correctly

There's a few things you can look for help solve this.

  1. Has anything changed or been extended in the core CodeIgniter files. Check that system/core/Input.php is an original copy and the contents of application/library and application/core for additional files

  2. Do the other input methods work? What is the result of this when run beside your print_r call?

    echo $this->input->user_agent();

  3. What data is output from print_r? Look in application/config/config.php for the line $config['global_xss_filtering']. Is this set to TRUE or FALSE? If TRUE maybe the cross site scripting filter has a problem with the data you're posting (this is unlikely I think)

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Android ListView with onClick items

In your activity, where you defined your listview

you write

listview.setOnItemClickListener(new OnItemClickListener(){   
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        ItemClicked item = adapter.getItemAtPosition(position);

        Intent intent = new Intent(Activity.this,destinationActivity.class);
        //based on item add info to intent
        startActivity(intent);
    }
});

in your adapter's getItem you write

public ItemClicked getItem(int position){
    return items.get(position);
}

Remove white space above and below large text in an inline-block element

If its text that has to scale proportionally to the screenwidth, you can also use the font as an svg, you can just export it from something like illustrator. I had to do this in my case, because I wanted to align the top of left and right border with the font's top |TEXT| . Using line-height, the text will jump up and down when scaling the window.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

If you need a general purpose conversion from a string which per se is not a bool, you should better write a routine similar to the one depicted below. In keeping with the spirit of duck typing, I have not silently passed the error but converted it as appropriate for the current scenario.

>>> def str2bool(st):
try:
    return ['false', 'true'].index(st.lower())
except (ValueError, AttributeError):
    raise ValueError('no Valid Conversion Possible')


>>> str2bool('garbaze')

Traceback (most recent call last):
  File "<pyshell#106>", line 1, in <module>
    str2bool('garbaze')
  File "<pyshell#105>", line 5, in str2bool
    raise TypeError('no Valid COnversion Possible')
TypeError: no Valid Conversion Possible
>>> str2bool('false')
0
>>> str2bool('True')
1

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

How to select an item in a ListView programmatically?

        int i=99;//is what row you want to select and focus
        listViewRamos.FocusedItem = listViewRamos.Items[0];
        listViewRamos.Items[i].Selected = true;
        listViewRamos.Select();
        listViewRamos.EnsureVisible(i);//This is the trick

How to implement a read only property

You can do this:

public int Property { get { ... } private set { ... } }

No log4j2 configuration file found. Using default configuration: logging only errors to the console

i had same problem, but i noticed that i have no log4j2.xml in my project after reading on the net about this problem, so i copied the related code in a notepad and reverted the notepad file to xml and add to my project under the folder resources. it works for me.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
  <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="DEBUG">
  <AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

Reverse ip, find domain names on ip address

You can use nslookup on the IP. Reverse DNS is defined with the .in-addr.arpa domain.

Example:

nslookup somedomain.com

yields 123.21.2.3, and then you do:

nslookup 123.21.2.3

this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

where does MySQL store database files?

In any case you can know it:

mysql> select @@datadir;
+----------------------------------------------------------------+
| @@datadir                                                      |
+----------------------------------------------------------------+
| D:\Documents and Settings\b394382\My Documents\MySQL_5_1\data\ |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Thanks Barry Galbraith from the MySql Forum http://forums.mysql.com/read.php?10,379153,379167#msg-379167

CSS div element - how to show horizontal scroll bars only?

.box-author-txt {width:596px; float:left; padding:5px 0px 10px 10px;  border:1px #dddddd solid; -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; -o-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; overflow-x: scroll; white-space: nowrap; overflow-y: hidden;}


.box-author-txt ul{ vertical-align:top; height:auto; display: inline-block; white-space: nowrap; margin:0 9px 0 0; padding:0px;}
.box-author-txt ul li{ list-style-type:none;  width:140px; }

How to add months to a date in JavaScript?

I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):

var one_month_from_your_date = your_date_object.add(1).month();

What's nice about datejs is that it handles edge cases, because technically you can do this using the native Date object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs has taken care of for you.

Plus it's open source!

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.

If you look at the call signature of np.int, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int).

Note that np.vectorize is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int) as @FFT suggests).

Windows 7 SDK installation failure

Uninstalling all C++ redistributables and unchecking the C++ option worked for me. Note that I have VS2010 SP1, and VS2012 installed already.

Get the second largest number in a list in linear time

Why to complicate the scenario? Its very simple and straight forward

  1. Convert list to set - removes duplicates
  2. Convert set to list again - which gives list in ascending order

Here is a code

mlist = [2, 3, 6, 6, 5]
mlist = list(set(mlist))
print mlist[-2]

C++11 rvalues and move semantics confusion (return statement)

As already mentioned in comments to the first answer, the return std::move(...); construct can make a difference in cases other than returning of local variables. Here's a runnable example that documents what happens when you return a member object with and without std::move():

#include <iostream>
#include <utility>

struct A {
  A() = default;
  A(const A&) { std::cout << "A copied\n"; }
  A(A&&) { std::cout << "A moved\n"; }
};

class B {
  A a;
 public:
  operator A() const & { std::cout << "B C-value: "; return a; }
  operator A() & { std::cout << "B L-value: "; return a; }
  operator A() && { std::cout << "B R-value: "; return a; }
};

class C {
  A a;
 public:
  operator A() const & { std::cout << "C C-value: "; return std::move(a); }
  operator A() & { std::cout << "C L-value: "; return std::move(a); }
  operator A() && { std::cout << "C R-value: "; return std::move(a); }
};

int main() {
  // Non-constant L-values
  B b;
  C c;
  A{b};    // B L-value: A copied
  A{c};    // C L-value: A moved

  // R-values
  A{B{}};  // B R-value: A copied
  A{C{}};  // C R-value: A moved

  // Constant L-values
  const B bc;
  const C cc;
  A{bc};   // B C-value: A copied
  A{cc};   // C C-value: A copied

  return 0;
}

Presumably, return std::move(some_member); only makes sense if you actually want to move the particular class member, e.g. in a case where class C represents short-lived adapter objects with the sole purpose of creating instances of struct A.

Notice how struct A always gets copied out of class B, even when the class B object is an R-value. This is because the compiler has no way to tell that class B's instance of struct A won't be used any more. In class C, the compiler does have this information from std::move(), which is why struct A gets moved, unless the instance of class C is constant.

Add an object to an Array of a custom class

The array declaration should be:

Car[] garage = new Car[100];

You can also just assign directly:

garage[1] = new Car("Blue");

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

How to delete from multiple tables in MySQL?

Use a JOIN in the DELETE statement.

DELETE p, pa
      FROM pets p
      JOIN pets_activities pa ON pa.id = p.pet_id
     WHERE p.order > :order
       AND p.pet_id = :pet_id

Alternatively you can use...

DELETE pa
      FROM pets_activities pa
      JOIN pets p ON pa.id = p.pet_id
 WHERE p.order > :order
   AND p.pet_id = :pet_id

...to delete only from pets_activities

See this.

For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS, NOT EXISTS, IN, NOT IN and etc. But the one above where you specify from which tables to delete with an alias before the FROM clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

How to decompile to java files intellij idea

Someone had gave good answers. I made another instruction clue step by step. First, open your studio and search. You can find the decompier is Fernflower.

enter image description here

Second, we can find it in the plugins directory.

/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar

Third, run it, you will get the usage

java -cp "/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler

Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
Example: java -jar fernflower.jar -dgs=true c:\my\source\ c:\my.jar d:\decompiled\

Finally, The studio's nest options for decompiler list as follows according IdeaDecompiler.kt

-hdc=0 -dgs=1 -rsy=1 -rbr=1 -lit=1 -nls=1 -mpm=60 -lac=1

IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
        IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
        IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
        IFernflowerPreferences.REMOVE_BRIDGE to "1",
        IFernflowerPreferences.LITERALS_AS_IS to "1",
        IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
        **IFernflowerPreferences.BANNER to BANNER,**
        IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
        **IFernflowerPreferences.INDENT_STRING to indent,**
        **IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",**
        IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
         **IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")**

I cant find the sutialbe option for the asterisk items.

Hope these steps will make the question clear.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.

If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.

You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.

In a production system, it really depends. For oracle 10g and older, you could execute

LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);

In a separate session but have the following ready in case it takes too long.

alter system kill session '....

It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.

In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.

ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);

Finally it may be best to wait until there are few users in the system to do this kind of maintenance.

What are carriage return, linefeed, and form feed?

Consider an IBM 1403 impact printer. CR moved the print head to the start of the line, but did NOT advance the paper. This allowed for "overprinting", placing multiple lines of output on one line. Things like underlining were achieved this way, as was BOLD print. LF advanced the paper one line. If there was no CR, the next line would print as a staggered-step because LF didn't move the print head. FF advanced the paper to the next page. It typically also moved the print head to the start of the first line on the new page, but you might need CR for that. To be sure, most programmers coded CRFF instead of CRLF at the end of the last line on a page because an extra CR created by FF wouldn't matter.

Split an NSString to access one particular piece

NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];

Update 7/3/2018:

Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:

let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]

Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map

let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]

or

let firstBit = String(substrings[0])

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

JUnit: how to avoid "no runnable methods" in test utils classes

Be careful when using an IDE's code-completion to add the import for @Test.

It has to be import org.junit.Test and not import org.testng.annotations.Test, for example. If you do the latter, you'll get the "no runnable methods" error.

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Here is a quick solution I created some time ago. you can read more about it in my article:

http://ajax911.com/numbers-numeric-field-jquery/

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

If you had a table that already had a existing constraints based on lets say: name and lastname and you wanted to add one more unique constraint, you had to drop the entire constrain by:

ALTER TABLE your_table DROP CONSTRAINT constraint_name;

Make sure tha the new constraint you wanted to add is unique/ not null ( if its Microsoft Sql, it can contain only one null value) across all data on that table, and then you could re-create it.

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);

invalid byte sequence for encoding "UTF8"

I ran into this problem under Windows while working exclusively with psql (no graphical tools). To fix this problem, permanently change the default encoding of psql (client) to match the default encoding of the PostgreSQL server. Run the following command in CMD or Powershell:

setx PGCLIENTENCODING UTF8

Close and reopen you command prompt/Powershell for the change to take effect.

Change the encoding of the backup file from Unicode to UTF8 by opening it with Notepad and going to File -> Save As. Change the Encoding dropdown from Unicode to UTF8. (Also change the Save as type from Text Documents (.txt) to All Files in order to avoid adding the .txt extension to your backup file's name). You should now be able to restore your backup.

How to check if an integer is in a given range?

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);

it returns true if minValue <= x <= MaxValue - i.e within the range

it returns false if x < minValue or x > maxValue - i.e outofrange

Use with if condition as shown below:

int value = 10;
if(ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

below program checks, if any of the passed integer value in the hasTeen method is within the range of 13(inclusive) to 19(Inclusive)


import java.time.temporal.ValueRange;    
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));

    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

******OUTPUT******

true as 19 is part of range

true as 15 is part of range

false as all three value passed out of range

adb shell su works but adb root does not

adbd has a compilation flag/option to enable root access: ALLOW_ADBD_ROOT=1.

Up to Android 9: If adbd on your device is compiled without that flag, it will always drop privileges when starting up and thus "adb root" will not help at all. I had to patch the calls to setuid(), setgid(), setgroups() and the capability drops out of the binary myself to get a permanently rooted adbd on my ebook reader.

With Android 10 this changed; when the phone/tablet is unlocked (ro.boot.verifiedbootstate == "orange"), then adb root mode is possible in any case.

How do I escape a single quote in SQL Server?

If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after your query.

For example

SET QUOTED_IDENTIFIER OFF;

UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");

SET QUOTED_IDENTIFIER ON;
-- set OFF then ON again

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

The provider is not compatible with the version of Oracle client

We had the same problem, because the Oracle.Data.dll assembly on a network share was updated by our DBA's. Removing the reference from the project, and adding it again solved the problem.

Attributes / member variables in interfaces?

You can only do this with an abstract class, not with an interface.

Declare Rectangle as an abstract class instead of an interface and declare the methods that must be implemented by the sub-class as public abstract. Then class Tile extends class Rectangle and must implement the abstract methods from Rectangle.

How can I give the Intellij compiler more heap space?

GWT in Intellij 12

FWIW, I was getting a similar error with my GWT application during 'Build | Rebuild Project'.

This was caused by Intellij doing a full GWT compile which I didn't like because it is also a very lengthy process.

I disabled GWT compile by turning off the module check boxes under 'Project Structure | Facets | GWT'.

Alternatively there is a 'Compiler maximum heap size' setting in that location as well.

How are booleans formatted in Strings in Python?

>>> print "%r, %r" % (True, False)
True, False

This is not specific to boolean values - %r calls the __repr__ method on the argument. %s (for str) should also work.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

It's very easy to get memory leaks in a PHP script - especially if you use abstraction, such as an ORM. Try using Xdebug to profile your script and find out where all that memory went.

How to define an empty object in PHP

Use a generic object and map key value pairs to it.

$oVal = new stdClass();
$oVal->key = $value

Or cast an array into an object

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

Remove Identity from a column in a table

Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.

Lets suppose you have a table with two columns

ID Identity (1,1) | Name Varchar

and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4

DBCC CHECKIDENT([YourTable], RESEED, 3)

Make the Insert

INSERT  INTO [YourTable]
        ( Name )
VALUES  ( 'Client' )

And get your seed back to the highest ID, lets suppose is 15

DBCC CHECKIDENT([YourTable], RESEED, 15)

Done!

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

Is there an equivalent of lsusb for OS X

Homebrew users: you can get lsusb by installing usbutils formula from my tap:

brew install mikhailai/misc/usbutils

It installs the REAL lsusb based on Linux sources (version 007).

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Call an overridden method from super class in typescript

The order of execution is:

  1. A's constructor
  2. B's constructor

The assignment occurs in B's constructor after A's constructor—_super—has been called:

function B() {
    _super.apply(this, arguments);   // MyvirtualMethod called in here
    this.testString = "Test String"; // testString assigned here
}

So the following happens:

var b = new B();     // undefined
b.MyvirtualMethod(); // "Test String"

You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod() in B's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A's constructor and working that out somehow... there's lots of possibilities.

How to use global variable in node.js?

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

In my case. I didn't have missing outlets in xib-files after merging.

Shift + Command + K

solved my problem. I cleaned my project and rebuilt.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

To specify a Dockerfile when build, you can use:

docker build -t ubuntu-test:latest - < /path/to/your/Dockerfile

But it'll fail if there's ADD or COPY command that depends on relative path. There're many ways to specify a context for docker build, you can refer to docs of docker build for more info.

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>

CSS width of a <span> tag

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

Can I get "&&" or "-and" to work in PowerShell?

It depends on the context, but here's an example of "-and" in action:

get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }

So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".

What is javax.inject.Named annotation supposed to be used for?

Regarding #2, according to the JSR-330 spec:

This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.

So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.

Is 'bool' a basic datatype in C++?

Turbo c and c++ compiler does not support boolean (bool keyword) data type but dev c++ compiler supports boolean (bool keyword) data type.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

What is the meaning of the term "thread-safe"?

An easier way to understand it, is what make code not thread-safe. There's two main issue that will make a threaded application to have unwanted behavior.

  • Accessing shared variable without locking
    This variable could be modified by another thread while executing the function. You want to prevent it with a locking mechanism to be sure of the behavior of your function. General rule of thumb is to keep the lock for the shortest time possible.

  • Deadlock caused by mutual dependency on shared variable
    If you have two shared variable A and B. In one function, you lock A first then later you lock B. In another function, you start locking B and after a while, you lock A. This is a potential deadlock where first function will wait for B to be unlocked when second function will wait for A to be unlocked. This issue will probably not occur in your development environment and only from time to time. To avoid it, all locks must always be in the same order.

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Steps to send a https request to a rest service in Node js

Note if you are using https.request do not directly use the body from res.on('data',... This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'. Example -

  var options = {
    hostname: "www.google.com",
    port: 443,
    path: "/upload",
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(post_data)
    }
  };

  //change to http for local testing
  var req = https.request(options, function (res) {
    res.setEncoding('utf8');

    var body = '';

    res.on('data', function (chunk) {
      body = body + chunk;
    });

    res.on('end',function(){
      console.log("Body :" + body);
      if (res.statusCode != 200) {
        callback("Api call failed with response code " + res.statusCode);
      } else {
        callback(null);
      }
    });

  });

  req.on('error', function (e) {
    console.log("Error : " + e.message);
    callback(e);
  });

  // write data to request body
  req.write(post_data);
  req.end();

Appropriate datatype for holding percent values?

  • Hold as a decimal.
  • Add check constraints if you want to limit the range (e.g. between 0 to 100%; in some cases there may be valid reasons to go beyond 100% or potentially even into the negatives).
  • Treat value 1 as 100%, 0.5 as 50%, etc. This will allow any math operations to function as expected (i.e. as opposed to using value 100 as 100%).
  • Amend precision and scale as required (these are the two values in brackets columnName decimal(precision, scale). Precision says the total number of digits that can be held in the number, scale says how many of those are after the decimal place, so decimal(3,2) is a number which can be represented as #.##; decimal(5,3) would be ##.###.
  • decimal and numeric are essentially the same thing. However decimal is ANSI compliant, so always use that unless told otherwise (e.g. by your company's coding standards).

Example Scenarios

  • For your case (0.00% to 100.00%) you'd want decimal(5,4).
  • For the most common case (0% to 100%) you'd want decimal(3,2).
  • In both of the above, the check constraints would be the same

Example:

if object_id('Demo') is null
create table Demo
    (
        Id bigint not null identity(1,1) constraint pk_Demo primary key
        , Name nvarchar(256) not null constraint uk_Demo unique 
        , SomePercentValue decimal(3,2) constraint chk_Demo_SomePercentValue check (SomePercentValue between 0 and 1)
        , SomePrecisionPercentValue decimal(5,2) constraint chk_Demo_SomePrecisionPercentValue check (SomePrecisionPercentValue between 0 and 1)
    )

Further Reading:

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

We store latitude/longitude X 1,000,000 in our oracle database as NUMBERS to avoid round off errors with doubles.

Given that latitude/longitude to the 6th decimal place was 10 cm accuracy that was all we needed. Many other databases also store lat/long to the 6th decimal place.

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I had this problem in MacOS, and I solved it by linking the brew installed python 3 version, with

brew link python3

After that, it worked without a problem.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

As subarachnid said overflow-x hidden for both body and html worked Here's working example

**HTML**
<div class="contener">
  <div class="menu">
  das
  </div>
  <div class="hover">
    <div class="img1">
    First Strip
    </div>
     <div class="img2">
    Second Strip
    </div>
</div>
</div>
<div class="baner">
dsa
</div>

**CSS**
body, html{
  overflow-x:hidden;
}
body{
  margin:0;
}
.contener{
  width:100vw;
}
.baner{
   background-image: url("http://p3cdn4static.sharpschool.com/UserFiles/Servers/Server_3500628/Image/abstract-art-mother-earth-1.jpg");
   width:100vw;
   height:400px;
   margin-left:0;
   left:0;
}
.contener{
  height:100px;
}
.menu{
  display:flex;
  background-color:teal;
  height:100%;
  justify-content:flex-end;
  align:content:bottom;
}
.img1{
  width:150px;
  height:25px;
  transform:rotate(45deg);
  background-color:red;
  position:absolute;
  top:40px;
  right:-50px;
  line-height:25px;
  padding:0 20px;
  cursor:pointer;
  color:white;
  text-align:center;
  transition:all 0.4s;
}
.img2{
  width:190px;
  text-align:center;
  transform:rotate(45deg);
  background-color:#333;
  position:absolute;
  height:25px;
  line-height:25px;
  top:55px;
  right:-50px;
  padding:0 20px;
  cursor:pointer;
  color:white;
  transition:all 0.4s;
}
.hover{
  overflow:hidden;
}
.hover:hover .img1{
  background-color:#333;
  transition:all 0.4s;
}
.hover:hover .img2{
  background-color:blue;
  transition:all 0.4s;
}

Link

html/css buttons that scroll down to different div sections on a webpage

For something really basic use this:

<a href="#middle">Go To Middle</a>

Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.

How can I select the record with the 2nd highest salary in database Oracle?

This query helps me every time for problems like this. Replace N with position..

select *
from(
     select *
     from (select * from TABLE_NAME order by SALARY_COLUMN desc)
     where rownum <=N
    )
where SALARY_COLUMN <= all(
                select SALARY_COLUMN
                from (select * from TABLE_NAME order by SALARY_COLUMN desc)
                where rownum <=N
               );

ASP.NET Web Site or ASP.NET Web Application?

This may sound a bit obvious, but I think it's something that is misunderstood because Visual Studio 2005 only shipped with the web site originally. If your project deals with a website that is fairly limited and doesn't have a lot of logical or physical separation, the website is fine. However if it is truly a web application with different modules where many users add and update data, you are better off with the web application.

The biggest pro of the website model is that anything in the app_code section is dynamically compiled. You can make C# file updates without a full redeploy. However this comes at a great sacrifice. A lot of things happen under the covers that are difficult to control. Namespaces are difficult to control and specific DLL usage goes out the window by default for anything under app_code since everything is dynamically compiled.

The web application model does not have dynamic compilation, but you gain control over the things that I have mentioned.

If you are doing n-tier development, I highly recommend the web application model. If you are doing a limited web site or a quick and dirty implementation, the web site model may have advantages.

More detailed analysis can be found in:

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

Count records for every month in a year

This will give you the count per month for 2012;

SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);

Demo here.

php variable in html no other way than: <?php echo $var; ?>

I really think you should adopt Smarty template engine as a standard php lib for your projects.

http://www.smarty.net/

Name: {$name|capitalize}<br>

Insert current date in datetime format mySQL

If you Pass date from PHP you can use any format using STR_TO_DATE() mysql function . Let conseder you are inserting date via html form

$Tdate = "'".$_POST["Tdate"]."'" ;    //   10/04/2016
$Tdate = "STR_TO_DATE(".$Tdate.", '%d/%m/%Y')"  ;  
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$Tdate')");

The dateposted should be mysql date type . or mysql will adds 00:00:00
in some case You better insert date and time together into DB so you can do calculation with hours and seconds . () .

$Tdate=date('Y/m/d H:i:s') ; // this to get current date as text .
$Tdate = "STR_TO_DATE(".$Tdate.", '%d/%m/%Y %H:%i:%s')"  ;  

JavaScript displaying a float to 2 decimal places

let a = 0.0500
a.toFixed(2);

//output
0.05

How to solve time out in phpmyadmin?

I had this issue too and tried different memory expansion techniques I found on the web but had more troubles with it. I resolved to using the MySQL console source command, and of course you don't have to worry about phpMyAdmin or PHP maximum execution time and limits.

Syntax: source c:\path\to\dump_file.sql

Note: It's better to specify an absolute path to the dump file since the mysql working directory might not be known.

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

Combining the results of two SQL queries as separate columns

You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1

SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y

Nuget connection attempt failed "Unable to load the service index for source"

Some development environment may not be using neither a browser nor a proxy.

One solution would downloading the package from nugget such as the https://dotnet.myget.org/F/dotnet-core/api/v3/index.json to a shared directory then execute the following:

dotnet add package Microsoft.AspNetCore.StaticFiles -s "shared drive:\index.json"

I hope that works for you.  

java.lang.ClassNotFoundException on working app

What helped me in case of Android Studio: The problem occurred after renamning package of large project. So I did almost everything AS offers to clean and refresh the project officially, and it works. I'm not saying this is solution for everyone just in case you're using Android Studio. Done in Android Studio 3.5.1, Windows 10.

  • Alex's answer
  • Build > Clean Project
  • Build > Rebuild Project
  • File > Sync with File System
  • File > Sync project with Gradle Files
  • File > Invalidate Caches / Restart

System.MissingMethodException: Method not found?

In my case, my project was referencing Microsoft.Net.Compilers.2.10.0. When I switched it to Microsoft.Net.Compilers.2.7.0, the error went away. What a mysterious error with such a variety of causes.

Cannot attach the file *.mdf as database

I think that for SQL Server Local Db you shouldn't use the Initial Catalog property. I suggest to use:

<add name="DefaultConnection" 
     connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf" 
     providerName="System.Data.SqlClient" />

I think that local db doesn't support multiple database on the same mdf file so specify an initial catalog is not supported (or not well supported and I have some strange errors).

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

Convert string to date in Swift

Just your passing your dateformate and your date then you get Year,month,day,hour. Extra info

func GetOnlyDateMonthYearFromFullDate(currentDateFormate:NSString , conVertFormate:NSString , convertDate:NSString ) -> NSString
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = currentDateFormate as String
        let formatter = NSDateFormatter()
        formatter.dateFormat = Key_DATE_FORMATE as String
        let finalDate = formatter.dateFromString(convertDate as String)
        formatter.dateFormat = conVertFormate as String
        let dateString = formatter.stringFromDate(finalDate!)

        return dateString
    }


Get Year

let Year = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "YYYY", convertDate: "2016-04-14T10:44:00+0000") as String


Get Month

let month = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "MM", convertDate: "2016-04-14T10:44:00+0000") as String


Get Day

let day = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "dd", convertDate: "2016-04-14T10:44:00+0000") as String


Get Hour

let hour  = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "hh", convertDate: "2016-04-14T10:44:00+0000") as String

Setting Margin Properties in code

Margin = new Thickness(0, 0, 0, 0);

What is the difference between == and equals() in Java?

== operator always reference is compared. But in case of

equals() method

it's depends's on implementation if we are overridden equals method than it compares object on basic of implementation given in overridden method.

 class A
 {
   int id;
   String str;

     public A(int id,String str)
     {
       this.id=id;
       this.str=str;
     }

    public static void main(String arg[])
    {
      A obj=new A(101,"sam");
      A obj1=new A(101,"sam");

      obj.equals(obj1)//fasle
      obj==obj1 // fasle
    }
 }

in above code both obj and obj1 object contains same data but reference is not same so equals return false and == also. but if we overridden equals method than

 class A
 {
   int id;
   String str;

     public A(int id,String str)
     {
       this.id=id;
       this.str=str;
     }
    public boolean equals(Object obj)
    {
       A a1=(A)obj;
      return this.id==a1.id;
    }

    public static void main(String arg[])
    {
      A obj=new A(101,"sam");
      A obj1=new A(101,"sam");

      obj.equals(obj1)//true
      obj==obj1 // fasle
    }
 }

know check out it will return true and false for same case only we overridden

equals method .

it compare object on basic of content(id) of object

but ==

still compare references of object.

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

How do I connect to mongodb with node.js (and authenticate)?

var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;    
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'@'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){  
      if(err) 
        console.log(err);
      else
      {
        console.log('Mongo Conn....');

      }
    });
//for local server 
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){  
      if(err) 
        console.log(err);
      else
      {
        console.log('Mongo Conn....');

      }
    });

What is the difference between Numpy's array() and asarray() functions?

asarray(x) is like array(x, copy=False)

Use asarray(x) when you want to ensure that x will be an array before any other operations are done. If x is already an array then no copy would be done. It would not cause a redundant performance hit.

Here is an example of a function that ensure x is converted into an array first.

def mysum(x):
    return np.asarray(x).sum()

putting datepicker() on dynamically created elements - JQuery/JQueryUI

This is what worked for me on JQuery 1.3 and is showing on the first click/focus

function vincularDatePickers() {
    $('.mostrar_calendario').live('click', function () {
        $(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
    });
}

this needs that your input have the class 'mostrar_calendario'

Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"

See more about the difference here http://api.jquery.com/live/

SQL Server: Multiple table joins with a WHERE clause

Try this working fine....

SELECT computer.NAME, application.NAME,software.Version FROM computer LEFT JOIN software_computer ON(computer.ID = software_computer.ComputerID)
 LEFT JOIN software ON(software_computer.SoftwareID = Software.ID) LEFT JOIN application ON(application.ID = software.ApplicationID) 
 where computer.id = 1 group by application.NAME UNION SELECT computer.NAME, application.NAME,
 NULL as Version FROM computer, application WHERE application.ID not in ( SELECT s.applicationId FROM software_computer sc LEFT JOIN software s 
 on s.ID = sc.SoftwareId WHERE sc.ComputerId = 1 ) 
 AND computer.id = 1 

How do I use a custom Serializer with Jackson?

If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.

[ see also: Why does Java have transient fields? ]

java.lang.OutOfMemoryError: Java heap space

In netbeans, Go to 'Run' toolbar, --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up windo --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'. It could solve heap size problem.

Difference between require, include, require_once and include_once?

I was using function as below:

function doSomething() {
    require_once(xyz.php);
    ....
}

There were constant values declared in xyz.php.

I have to call this doSomething() function from another PHP script file.

But I observed behavior while calling this function in a loop, for first iteration doSomething() was getting constant values within xyz.php, but later every iteration doSomething() was not able to get the constant values declared in xyz.php.

I solved my problem by switching from require_once() to include(), updated doSomething() code is as below:

function doSomething() {
    include(xyz.php);
    ....
}

Now every iteration call to doSomething() gets the constant values defined in xyz.php.

Is it possible to use std::string in a constexpr?

No, and your compiler already gave you a comprehensive explanation.

But you could do this:

constexpr char constString[] = "constString";

At runtime, this can be used to construct a std::string when needed.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

Try below command using administrator permission. This command solved my issue. Hope it will resolve your problem.

git config --system --unset-all credential.helper

How to increase apache timeout directive in .htaccess?

if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")

Browser should report request timeout error.

You may do 2 things:

Based on CGI/Server side engine increase timeout there

PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds

In php.ini:

max_execution_time 60

Increase apache timeout - default is 300 (in version 2.4 it is 60).

In your httpd.conf (in server config or vhost config)

TimeOut 600

Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.

Second setting modify maximum amount of time the server will wait for certain events before failing a request

Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.

How can I calculate the difference between two ArrayLists?

In Java, you can use the Collection interface's removeAll method.

// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
    add("apple");
    add("orange");
}};

Collection secondList = new ArrayList() {{
    add("apple");
    add("orange");
    add("banana");
    add("strawberry");
}};

// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);

// Remove all elements in firstList from secondList
secondList.removeAll(firstList);

// Show the "after" list
System.out.println("Result: " + secondList);

The above code will produce the following output:

First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]

Django, creating a custom 500/404 error page

As one single line (for 404 generic page):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

What is the PostgreSQL equivalent for ISNULL()

Use COALESCE() instead:

SELECT COALESCE(Field,'Empty') from Table;

It functions much like ISNULL, although provides more functionality. Coalesce will return the first non null value in the list. Thus:

SELECT COALESCE(null, null, 5); 

returns 5, while

SELECT COALESCE(null, 2, 5);

returns 2

Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.

Swift - Integer conversion to Hours/Minutes/Seconds

The simplest way imho:

let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)

How to generate an MD5 file hash in JavaScript?

As a contemporary alternative, there is a standard now for client side cryptography. This has the advantage of being optimised by the browser itself.

Taken from the example in the documentation:

async function sha256(message) {

    // encode as UTF-8
    const msgBuffer = new TextEncoder('utf-8').encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
}

sha256('abc').then(hash => console.log(hash));

(async function() {
    const hash = await sha256('abc');
}());

MD5 is likely unsupported, however the likes of SHA-256, SHA-384, and SHA-512 are.

And those will likely be able to be calculated server side also.

Here's some documentation on usage: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest

And cross browser compatibility: https://caniuse.com/#feat=cryptography

Format numbers in django templates

Well I couldn't find a Django way, but I did find a python way from inside my model:

def format_price(self):
    import locale
    locale.setlocale(locale.LC_ALL, '')
    return locale.format('%d', self.price, True)

increase font size of hyperlink text html

increase the padding size of font and then try to increase font size:-

style="padding-bottom:40px; font-size: 50px;"

Apply jQuery datepicker to multiple instances

I just had the same problem.

The correct way to use date pick is $('.my_class').datepicker(); but you need to make sure you don't assign the same ID to multiple datepickers.

How to check if MySQL returns null/empty?

You can use is_null() function.

http://php.net/manual/en/function.is-null.php : in the comments :

mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.

Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:

[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
     if (is_null($qValues["foo"]))
         echo "No foo data!";
     else
         echo "Foo data=".$qValues["foo"];
[…]

Why do you use typedef when declaring an enum in C++?

In C, declaring your enum the first way allows you to use it like so:

TokenType my_type;

If you use the second style, you'll be forced to declare your variable like this:

enum TokenType my_type;

As mentioned by others, this doesn't make a difference in C++. My guess is that either the person who wrote this is a C programmer at heart, or you're compiling C code as C++. Either way, it won't affect the behaviour of your code.

How do I center text horizontally and vertically in a TextView?

You can also use the combination:

android:gravity="left|center"

Then, if textview width is more than "fill_parent" the text will still be aligned to left (not centered as with gravity set only to "center").

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

How to set time zone of a java.util.Date?

Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.

As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.

How to stop an app on Heroku?

Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.

According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

cordova Android requirements failed: "Could not find an installed version of Gradle"

SOLUTION FOR Mac

Sample problem but I found my solution with brew.
1. Make sure you have the latest Android Studio installed.
2. Confirm from SDK manager that you have the required SDKs installed.
3. (optional)you could have an AVD installed as well.
4. install Homebrew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

5. Then run brew update to make sure Homebrew is up to date.

brew update

6. Run brew doctor to make sure everything is safe

brew doctor

7. Add Homebrew's location to your $PATH in your .bash_profile or .zshrc file.

export PATH="/usr/local/bin:$PATH"

8. If you don't have Node already installed, add:

brew install node

9. (Optional) To test out your Node and npm install, try installing Grunt (you might be asked to run with sudo)

npm install -g grunt-cli

10. Install Gradle

brew install gradle

Run: cordova run android --device with you device connected on a Mac and you have gradle working this time.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.

Example:

SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.

Sources:

Object spread vs. Object.assign

I'd like to summarize status of the "spread object merge" ES feature, in browsers, and in the ecosystem via tools.

Spec

Browsers: in Chrome, in SF, Firefox soon (ver 60, IIUC)

  • Browser support for "spread properties" shipped in Chrome 60, including this scenario.
  • Support for this scenario does NOT work in current Firefox (59), but DOES work in my Firefox Developer Edition. So I believe it will ship in Firefox 60.
  • Safari: not tested, but Kangax says it works in Desktop Safari 11.1, but not SF 11
  • iOS Safari: not teseted, but Kangax says it works in iOS 11.3, but not in iOS 11
  • not in Edge yet

Tools: Node 8.7, TS 2.1

Links

Code Sample (doubles as compatibility test)

var x = { a: 1, b: 2 };
var y = { c: 3, d: 4, a: 5 };
var z = {...x, ...y};
console.log(z); // { a: 5, b: 2, c: 3, d: 4 }

Again: At time of writing this sample works without transpilation in Chrome (60+), Firefox Developer Edition (preview of Firefox 60), and Node (8.7+).

Why Answer?

I'm writing this 2.5 years after the original question. But I had the very same question, and this is where Google sent me. I am a slave to SO's mission to improve the long tail.

Since this is an expansion of "array spread" syntax I found it very hard to google, and difficult to find in compatibility tables. The closest I could find is Kangax "property spread", but that test doesn't have two spreads in the same expression (not a merge). Also, the name in the proposals/drafts/browser status pages all use "property spread", but it looks to me like that was a "first principal" the community arrived at after the proposals to use spread syntax for "object merge". (Which might explain why it is so hard to google.) So I document my finding here so others can view, update, and compile links about this specific feature. I hope it catches on. Please help spread the news of it landing in the spec and in browsers.

Lastly, I would have added this info as a comment, but I couldn't edit them without breaking the authors' original intent. Specifically, I can't edit @ChillyPenguin's comment without it losing his intent to correct @RichardSchulte. But years later Richard turned out to be right (in my opinion). So I write this answer instead, hoping it will gain traction on the old answers eventually (might take years, but that's what the long tail effect is all about, after all).

How to convert hex to ASCII characters in the Linux shell?

Bash one-liner

echo -n "5a" | while read -N2 code; do printf "\x$code"; done

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Jquery selector input[type=text]')

If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:

var $list = $("#tableOrForm :input[type='text']");

$list.each(function(){
    // Go on with your code.
});

What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:

var $currentItem = $(this);

This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.

Hope this helps anyone!

Concatenating date with a string in Excel

Thanks for the solution !

It works, but in a french Excel environment, you should apply something like

TEXTE(F2;"jj/mm/aaaa")

to get the date preserved as it is displayed in F2 cell, after concatenation. Best Regards

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

I got this error when trying to import MySQLdb.

What worked for me was to uninstall Python and then reinstall it.

I got the error after installing npm (https://www.npmjs.com/get-npm). One thing it did was install Python even though I already had it.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I saw it's solved, but I still want to share a solution which worked for me.

.env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]

MySQL admin:

 SELECT user, host FROM mysql.user

Thank you, spencer7593

Console:

php artisan cache:clear
php artisan config:cache

Now it works for me.

Laracasts answers

Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

Cannot get a text value from a numeric cell “Poi”

Use that code it definitely works and I modified it.

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.*;

public class TestApp {

    public static void main(String[] args) throws Exception {

        try {

            Class forName = Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
            con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
            con.setAutoCommit(false);
            PreparedStatement pstm = null;
            FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
            POIFSFileSystem fs = new POIFSFileSystem(input);
            Workbook workbook;
            workbook = WorkbookFactory.create(fs);
            Sheet sheet = workbook.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = (Row) sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String add = row.getCell(1).getStringCellValue();

                int  contact = (int) row.getCell(2).getNumericCellValue();

                String email = row.getCell(3).getStringCellValue();

                String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows " + i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        } catch (IOException e) {
        }
    }

}

Mipmap drawables for icons

If you build an APK for a target screen resolution like HDPI, the Android asset packageing tool,AAPT,can strip out the drawables for other resolution you don’t need.But if it’s in the mipmap folder,then these assets will stay in the APK, regardless of the target resolution.

Find records from one table which don't exist in another

The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.

SELECT * FROM Call WHERE 
NOT EXISTS (SELECT 'x' FROM Phone_book where 
Phone_book.phone_number = Call.phone_number)

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

Why do I get an error instantiating an interface?

IUser is the interface, you can't instantiate the interface.

You need to instantiate the concrete class that implements the interface.

IUser user = new User();

or

User user = new User();

How to get JavaScript variable value in PHP

Add a cookie with the javascript variable you want to access.

document.cookie="profile_viewer_uid=1";

Then acces it in php via

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];

How to make sure docker's time syncs with that of the host?

It appears there can by time drift if you're using Docker Machine, as this response suggests: https://stackoverflow.com/a/26454059/105562 , due to VirtualBox.

Quick and easy fix is to just restart your VM:

docker-machine restart default

Openssl is not recognized as an internal or external command

First navigate to your Java/jre/bin folder in cmd cd c:\Program Files (x86)\Java\jre7\bin

Then use : [change debug.keystore path to the correct location on your system] install openssl (for windows 32 or 64 as per your needs at c:\openssl )

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

So the whole command goes like this : [prompts to enter keystore password on execution ]

c:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.ex
e" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
Enter keystore password:

How to use a WSDL file to create a WCF service (not make a call)

You could use svcutil.exe to generate client code. This would include the definition of the service contract and any data contracts and fault contracts required.

Then, simply delete the client code: classes that implement the service contracts. You'll then need to implement them yourself, in your service.