Programs & Examples On #Push

In distributed version control, push is the action of sending local changes to a remote repository.

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Git Push Error: insufficient permission for adding an object to repository database

After you add some stuff... commit them and after all finished push it! BANG!! Start all problems... As you should notice there are some differences in the way both new and existent projects were defined. If some other person tries to add/commit/push same files, or content (git keep both as same objects), we will face the following error:

$ git push
Counting objects: 31, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (21/21), 2.07 KiB | 0 bytes/s, done.
Total 21 (delta 12), reused 0 (delta 0)
remote: error: insufficient permission for adding an object to repository database ./objects  remote: fatal: failed to write object

To solve this problem you have to have something in mind operational system's permissions system as you are restricted by it in this case. Tu understand better the problem, go ahead and check your git object's folder (.git/objects). You will probably see something like that:

<your user_name>@<the machine name> objects]$ ls -la
total 200
drwxr-xr-x 25 <your user_name> <group_name> 2048 Feb 10 09:28 .
drwxr-xr-x  3 <his user_name> <group_name> 1024 Feb  3 15:06 ..
drwxr-xr-x  2 <his user_name> <group_name> 1024 Jan 31 13:39 02
drwxr-xr-x  2 <his user_name> <group_name> 1024 Feb  3 13:24 08

*Note that those file's permissions were granted only for your users, no one will never can changed it... *

Level       u   g   o
Permission rwx r-x ---
Binary     111 101 000
Octal       7   5   0

SOLVING THE PROBLEM

If you have super user permission, you can go forward and change all permissions by yourself using the step two, in any-other case you will need to ask all users with objects created with their users, use the following command to know who they are:

$ ls -la | awk '{print $3}' | sort -u 
<your user_name>
<his user_name>

Now you and all file's owner users will have to change those files permission, doing:

$ chmod -R 774 .

After that you will need to add a new property that is equivalent to --shared=group done for the new repository, according to the documentation, this make the repository group-writable, do it executing:

$ git config core.sharedRepository group

https://coderwall.com/p/8b3ksg

php - push array into array - key issue

All these answers are nice however when thinking about it....
Sometimes the most simple approach without sophistication will do the trick quicker and with no special functions.

We first set the arrays:

$arr1 = Array(
"cod" => ddd,
"denum" => ffffffffffffffff,
"descr" => ggggggg,
"cant" => 3
);
$arr2 = Array
(
"cod" => fff,
"denum" => dfgdfgdfgdfgdfg,
"descr" => dfgdfgdfgdfgdfg,
"cant" => 33
);

Then we add them to the new array :

$newArr[] = $arr1;
$newArr[] = $arr2;

Now lets see our new array with all the keys:

print_r($newArr);

There's no need for sql or special functions to build a new multi-dimensional array.... don't use a tank to get to where you can walk.

Push Notifications in Android Platform

My understanding/experience with Android push notification are:

  1. C2DM GCM - If your target android platform is 2.2+, then go for it. Just one catch, device users have to be always logged with a Google Account to get the messages.

  2. MQTT - Pub/Sub based approach, needs an active connection from device, may drain battery if not implemented sensibly.

  3. Deacon - May not be good in a long run due to limited community support.

Edit: Added on November 25, 2013

GCM - Google says...

For pre-3.0 devices, this requires users to set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.*

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

rejected master -> master (non-fast-forward)

WARNING:

Going for a 'git pull' is not ALWAYS a solution, so be carefull. You may face this problem (the one that is mentioned in the Q) if you have intentionally changed your repository history. In that case, git is confusing your history changes with new changes in your remote repo. So, you should go for a git push --force, because calling git pull will undo all of the changes you made to your history, intentionally.

Firebase: how to generate a unique numeric ID for key?

https://firebase.google.com/docs/firestore/manage-data/transactions

Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.

push() a two-dimensional array

In your case you can do that without using push at all:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

Git push rejected "non-fast-forward"

In Eclipse do the following:

GIT Repositories > Remotes > Origin > Right click and say fetch

GIT Repositories > Remote Tracking > Select your branch and say merge

Go to project, right click on your file and say Fetch from upstream.

Array.push() if does not exist?

In case you need something simple without wanting to extend the Array prototype:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

Determine on iPhone if user has enabled push notifications

Below you'll find a complete example that covers both iOS8 and iOS7 (and lower versions). Please note that prior to iOS8 you can't distinguish between "remote notifications disabled" and "only View in lockscreen enabled".

BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // iOS8+
    remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;

    UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;

    noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
    alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
    badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
    soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;

} else {
    // iOS7 and below
    UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;

    noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
    alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
    badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
    soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}

NSLog(@"Notification type status:");
NSLog(@"  None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@"  Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@"  Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@"  Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");

What does '--set-upstream' do?

git branch --set-upstream <<origin/branch>> is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>

How do I properly force a Git push?

Just do:

git push origin <your_branch_name> --force

or if you have a specific repo:

git push https://git.... --force

This will delete your previous commit(s) and push your current one.

It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...

Short flag

Also note that -f is short for --force, so

git push origin <your_branch_name> -f

will also work.

Git: add vs push vs commit

  1. git add adds your modified files to the queue to be committed later. Files are not committed

  2. git commit commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a

  3. git push pushes your changes to the remote repository.

This figure from this git cheat sheet gives a good idea of the work flow

enter image description here

git add isn't on the figure because the suggested way to commit is the combined git commit -a, but you can mentally add a git add to the change block to understand the flow.

Lastly, the reason why push is a separate command is because of git's philosophy. git is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.

What are the differences between "git commit" and "git push"?

Well, basically git commit puts your changes into your local repo, while git push sends your changes to the remote location. Since git is a distributed version control system, the difference is that commit will commit changes to your local repository, whereas push will push changes up to a remote repo

source Google

http://gitref.org/basic/ this link will be very useful too

https://git-scm.com/docs/git-commit

Adding items to an object through the .push() method

Another way of doing it would be:

stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});

Read more here: Object.assign()

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD^ --soft (Save your changes, back to last commit)

git reset HEAD^ --hard (Discard changes, back to last commit)

git push >> fatal: no configured push destination

The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

git remote add demo_app '[email protected]:levelone/demo_app.git'

Difference between array_push() and $array[] =

When you call a function in PHP (such as array_push()), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.

Using $arr[] = 'some value'; does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[].

How can I push a specific commit to a remote, and not previous commits?

I did want to obmit a old big history and start from a fresh commit i choosed to:

rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo 
git push 

when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.

javascript push multidimensional array

In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

Instead, declare valueToPush as an object and push that onto cookie_value_add:

// Create valueToPush as an object {} rather than an array []
var valueToPush = {};

// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;

cookie_value_add.push(valueToPush);

// View the structure of cookie_value_add
console.dir(cookie_value_add);

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

They key thing to remember is 'origin' is not the value you may need to be using... it worked for me when I replaced 'origin' with repo's name.

Git push failed, "Non-fast forward updates were rejected"

Sometimes, while taking a pull from your git, the HEAD gets detached. You can check this by entering the command:

git branch 
  • (HEAD detached from 8790704)

    master

    develop

It's better to move to your branch and take a fresh pull from your respective branch.

git checkout develop

git pull origin develop

git push origin develop

git push rejected

If nothing works, try:

git pull --allow-unrelated-histories <repo> <branch>

then do:

git push --set-upstream origin master

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

Heroku: How to push different local Git branches to Heroku/master

You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :

 git remote add origin https://github.com/VijayNew/NewExample.git

And the commit failed because you need to git add some files you want to track.

How to add multiple files to Git at the same time

If you want to stage and commit all your files on Github do the following;

git add -A                                                                                
git commit -m "commit message"
git push origin master

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

Best way to "push" into C# array

The is no array.push(newValue) in C#. You don't push to an Array in C#. What we use for this is a List<T>. What you may want to consider (for teaching purpose only) is the ArrayList (no generic and it is a IList, so ...).

static void Main()
{
    // Create an ArrayList and add 3 elements.
    ArrayList list = new ArrayList();
    list.Add("One"); // Add is your push
    list.Add("Two");
    list.Add("Three");
}

git push to specific branch

git push origin amd_qlp_tester will work for you. If you just type git push, then the remote of the current branch is the default value.

Syntax of push looks like this - git push <remote> <branch>. If you look at your remote in .git/config file, you will see an entry [remote "origin"] which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.

Set up git to pull and push all branches

Solution without hardcoding origin in config

Use the following in your global gitconfig

[remote]
    push = +refs/heads/*
    push = +refs/tags/*

This pushes all branches and all tags

Why should you NOT hardcode origin in config?

If you hardcode:

  1. You'll end up with origin as a remote in all repos. So you'll not be able to add origin, but you need to use set-url.
  2. If a tool creates a remote with a different name push all config will not apply. Then you'll have to rename the remote, but rename will not work because origin already exists (from point 1) remember :)

Fetching is taken care of already by modern git

As per Jakub Narebski's answer:

With modern git you always fetch all branches (as remote-tracking branches into refs/remotes/origin/* namespace

Changing git commit message after push (given that no one pulled from remote)

additional information for same problem if you are using bitbucket pipeline

edit your message

git commit --amend

push to the sever

git push --force <repository> <branch>

then add --force to your push command on the pipeline

git ftp push --force

This will delete your previous commit(s) and push your current one.

remove the --force after first push

i tried it on bitbucket pipeline and its working fine

Unknown SSL protocol error in connection

The corporate HTTP proxy behind which I currently am sporadically gives this error. I can fix it by simply visiting bitbucket.org in a browser, then retyring the command. Have no idea why this works, but it does fix it for me (at least temporarily).

How to push a new folder (containing other folders and files) to an existing git repo?

You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

Declare an empty two-dimensional array in Javascript?

What's wrong with

var arr2 = new Array(10,20);
    arr2[0,0] = 5;
    arr2[0,1] = 2
    console.log("sum is   " + (arr2[0,0] +  arr2[0,1]))

should read out "sum is 7"

Close Form Button Event

Try This: Application.ExitThread();

How can I build multiple submit buttons django form?

one url to the same view! like so!

urls.py

url(r'^$', views.landing.as_view(), name = 'landing'),

views.py

class landing(View):
        template_name = '/home.html'
        form_class1 = forms.pynamehere1
        form_class2 = forms.pynamehere2
            def get(self, request):
                form1 = self.form_class1(None)
                form2 = self.form_class2(None)
                return render(request, self.template_name, { 'register':form1, 'login':form2,})

             def post(self, request):
                 if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
                        ## do what ever you want to do for first function ####
                 if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
                         ## do what ever you want to do for second function ####
                        ## return def post###  
                 return render(request, self.template_name, {'form':form,})
/home.html
    <!-- #### form 1 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ register.as_p }}
    <button type="submit" name="htmlsubmitbutton1">Login</button>
    </form>
    <!--#### form 2 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ login.as_p }}
    <button type="submit" name="htmlsubmitbutton2">Login</button>
    </form>

Excel: VLOOKUP that returns true or false?

You still have to wrap it in an ISERROR, but you could use MATCH() instead of VLOOKUP():

Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.

Here's a complete example, assuming you're looking for the word "key" in a range of cells:

=IF(ISERROR(MATCH("key",A5:A16,FALSE)),"missing","found")

The FALSE is necessary to force an exact match, otherwise it will look for the closest value.

How to get label of select option with jQuery?

I found this helpful

$('select[name=users] option:selected').text()

When accessing the selector using the this keyword.

$(this).find('option:selected').text()

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

Convert comma separated string of ints to int array

This has been asked before. .Net has a built-in ConvertAll function for converting between an array of one type to an array of another type. You can combine this with Split to separate the string to an array of strings

Example function:

 static int[] ToIntArray(this string value, char separator)
 {
     return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
 }

Taken from here

Reading data from DataGridView in C#

something like

for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
     for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
    {
        string value = dataGrid.Rows[rows].Cells[col].Value.ToString();

    }
} 

example without using index

foreach (DataGridViewRow row in dataGrid.Rows)
{ 
    foreach (DataGridViewCell cell in row.Cells)
    {
        string value = cell.Value.ToString();

    }
}

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

How to get the directory of the currently running file?

dir, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
    }

this is for golang version: go version go1.13.7 linux/amd64

works for me, for go run main.go. If I run go build -o fileName, and put the final executable in some other folder, then that path is given while running the executable.

How can I insert vertical blank space into an html document?

While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.

<p style="margin-bottom:3cm;">This is the first question?</p>

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

POST data with request module on Node.JS

I had to post key value pairs without form and I could do it easily like below:

var request = require('request');

request({
  url: 'http://localhost/test2.php',
  method: 'POST',
  json: {mes: 'heydude'}
}, function(error, response, body){
  console.log(body);
});

The AWS Access Key Id does not exist in our records

I made the mistake of setting my variables with quotation marks like this:

AWS_ACCESS_KEY_ID="..."

How do I get the last character of a string?

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) {

or, strings

if (str.endsWith("bar")) {

Compile error: package javax.servlet does not exist

This is what solved the problem for me:

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>

How to print something when running Puppet client?

You can run the client like this ...

puppet agent --test --debug --noop

with that command you get all the output you can get.

excerpt puppet agent help
* --test:
  Enable the most common options used for testing. These are 'onetime',
  'verbose', 'ignorecache', 'no-daemonize', 'no-usecacheonfailure',
  'detailed-exitcodes', 'no-splay', and 'show_diff'.

NOTE: No need to include --verbose when you use the --test|-t switch, it implies the --verbose as well.

How do I detect when someone shakes an iPhone?

You need to check the accelerometer via accelerometer:didAccelerate: method which is part of the UIAccelerometerDelegate protocol and check whether the values go over a threshold for the amount of movement needed for a shake.

There is decent sample code in the accelerometer:didAccelerate: method right at the bottom of AppController.m in the GLPaint example which is available on the iPhone developer site.

How to avoid the "Circular view path" exception with Spring MVC test

In my case, I had this problem while trying to serve JSP pages using Spring boot application.

Here's what worked for me:

application.properties

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

pom.xml

To enable support for JSPs, we would need to add a dependency on tomcat-embed-jasper.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

Change div width live with jQuery

You can't just use a percentage width for the div? Setting the width to 50% will make it 50% as wide as the window (assuming there is no parent element with a width assigned to it).

joining two select statements

You should use UNION if you want to combine different resultsets. Try the following:

(SELECT * 
 FROM ( SELECT * 
        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id  
        WHERE products_id = 181) AS A)
UNION 

(SELECT * 
 FROM ( SELECT * 
        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
        WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)

Java 8 stream reverse order

Here's the solution I've come up with:

private static final Comparator<Integer> BY_ASCENDING_ORDER = Integer::compare;
private static final Comparator<Integer> BY_DESCENDING_ORDER = BY_ASCENDING_ORDER.reversed();

then using those comparators:

IntStream.range(-range, 0).boxed().sorted(BY_DESCENDING_ORDER).forEach(// etc...

Get unique values from arraylist in java

I hope I understand your question correctly: assuming that the values are of type String, the most efficient way is probably to convert to a HashSet and iterate over it:

ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
   ... //Do something
}

Height of an HTML select box (dropdown)

Confirmed.

The part that drops down is set to either:

  1. The height needed to show all entries, or
  2. The height needed to show x entries (with scrollbars to see remaining), where x is
    • 20 in Firefox & Chrome
    • 30 in IE 6, 7, 8
    • 16 for Opera 10
    • 14 for Opera 11
    • 22 for Safari 4
    • 18 for Safari 5
    • 11 in IE 5.0, 5.5
  3. In IE/Edge, if there are no options, a stupidly high list of 11 blanks entries.

For (3) above you can see the results in this JSFiddle

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

How to build and run Maven projects after importing into Eclipse IDE

1.Update project

Right Click on your project maven > update project

2.Build project

Right Click on your project again. run as > Maven build

If you have not created a “Run configuration” yet, it will open a new configuration with some auto filled values.

You can change the name. "Base directory" will be a auto filled value for you. Keep it as it is. Give maven command to ”Goals” fields.

i.e, “clean install” for building purpose

Click apply

Click run.

3.Run project on tomcat

Right Click on your project again. run as > Run-Configuration. It will open Run-Configuration window for you.

Right Click on “Maven Build” from the right side column and Select “New”. It will open a blank configuration for you.

Change the name as you want. For the base directory field you can choose values using 3 buttons(workspace,FileSystem,Variables). You can also copy and paste the auto generated value from previously created Run-configuration. Give the Goals as “tomcat:run”. Click apply. Click run.

If you want to get more clear idea with snapshots use the following link.

Build and Run Maven project in Eclipse

(I hope this answer will help someone come after the topic of the question)

How to extract the n-th elements from a list of tuples?

I know that it could be done with a FOR but I wanted to know if there's another way

There is another way. You can also do it with map and itemgetter:

>>> from operator import itemgetter
>>> map(itemgetter(1), elements)

This still performs a loop internally though and it is slightly slower than the list comprehension:

setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))

Results:

Method 1: 1.25699996948
Method 2: 1.46600008011

If you need to iterate over a list then using a for is fine.

Twitter Bootstrap Datepicker within modal window

add z-index above 1051 in class datepicker

add something like this in page or css

<style>
.datepicker{z-index:1151 !important;}
</style>

How can I format a String number to have commas and round?

This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.

    String number = "1000500000.574";
    Double numParsed = Double.parseDouble(number);

    System.out.println(String.format("The input number is: %,.2f", numParsed));
    // Or
    String numString = String.format("%,.2f", numParsed);

For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.

For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Angular2: custom pipe could not be found

see this is working for me.

ActStatus.pipe.ts First this is my pipe

import {Pipe,PipeTransform} from "@angular/core";

@Pipe({
  name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
  transform(status:any):any{
    switch (status) {
      case 1:
        return "UN_PUBLISH";
      case 2:
        return "PUBLISH";
      default:
        return status
    }
  }
}

main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---

@NgModule({
  declarations:[ActStatusPipe], // <---
  imports:[CommonModule],
  exports:[ActStatusPipe] // <---
})

export class MainPipe{}

app.module.ts user this pipe module in any module.

@NgModule({
  declarations: [...],
  imports: [..., MainPipe], // <---
  providers: [...],
  bootstrap: [AppComponent]
})

you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.

  1. create pipe .
  2. create separate module and declare and export one or more pipe.
  3. user that pipe module.

How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).

Copy a variable's value into another

I solved it myself for the time being. The original value has only 2 sub-properties. I reformed a new object with the properties from a and then assigned it to b. Now my event handler updates only b, and my original a stays as it is.

var a = { key1: 'value1', key2: 'value2' },
    b = a;

$('#revert').on('click', function(e){
    //FAIL!
    b = a;

    //WIN
    b = { key1: a.key1, key2: a.key2 };
});

This works fine. I have not changed a single line anywhere in my code except for the above, and it works just how I wanted it to. So, trust me, nothing else was updating a.

How can I debug javascript on Android?

Raphael is not supported on pre 3.0 Android browsers, that's what your problem is. They have no support for SVG graphics. It does have support for canvas though. If you don't need to animate it, you could render the graphics with canvg:

http://code.google.com/p/canvg/

That's how we got around this issue for rendering SVG icons in the default Android browser.

String literals and escape characters in postgresql

Cool.

I also found the documentation regarding the E:

http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS

PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab. Also supported are \digits, where digits represents an octal byte value, and \xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\). Also, a single quote can be included in an escape string by writing \', in addition to the normal way of ''.

RecyclerView - Get view at particular position

You can as well do this, this will help when you want to modify a view after clicking a recyclerview position item

@Override
public void onClick(View view, int position) {

            View v =  rv_notifications.getChildViewHolder(view).itemView;
            TextView content = v.findViewById(R.id.tv_content);
            content.setText("Helloo");

        }

how to query LIST using linq

I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.

Example:
enter image description here

How to force Eclipse to ask for default workspace?

Sometimes you need to pay attention to howw Eclipse is launched. I ever pinned Eclipse by rigk-click on the excutable and pinning it to taskbar. In this way, the Eclipse is launched to use settings under c:\User\public\public Documents\eclipse" which is not very desirable.

However, if you pin it by creating a short-cut, then it will launch to use settings in the folder of Eclipse installation. Then everything makes much more sense.

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Creating random numbers with no duplicates

There is another way of doing "random" ordered numbers with LFSR, take a look at:

http://en.wikipedia.org/wiki/Linear_feedback_shift_register

with this technique you can achieve the ordered random number by index and making sure the values are not duplicated.

But these are not TRUE random numbers because the random generation is deterministic.

But depending your case you can use this technique reducing the amount of processing on random number generation when using shuffling.

Here a LFSR algorithm in java, (I took it somewhere I don't remeber):

public final class LFSR {
    private static final int M = 15;

    // hard-coded for 15-bits
    private static final int[] TAPS = {14, 15};

    private final boolean[] bits = new boolean[M + 1];

    public LFSR() {
        this((int)System.currentTimeMillis());
    }

    public LFSR(int seed) {
        for(int i = 0; i < M; i++) {
            bits[i] = (((1 << i) & seed) >>> i) == 1;
        }
    }

    /* generate a random int uniformly on the interval [-2^31 + 1, 2^31 - 1] */
    public short nextShort() {
        //printBits();

        // calculate the integer value from the registers
        short next = 0;
        for(int i = 0; i < M; i++) {
            next |= (bits[i] ? 1 : 0) << i;
        }

        // allow for zero without allowing for -2^31
        if (next < 0) next++;

        // calculate the last register from all the preceding
        bits[M] = false;
        for(int i = 0; i < TAPS.length; i++) {
            bits[M] ^= bits[M - TAPS[i]];
        }

        // shift all the registers
        for(int i = 0; i < M; i++) {
            bits[i] = bits[i + 1];
        }

        return next;
    }

    /** returns random double uniformly over [0, 1) */
    public double nextDouble() {
        return ((nextShort() / (Integer.MAX_VALUE + 1.0)) + 1.0) / 2.0;
    }

    /** returns random boolean */
    public boolean nextBoolean() {
        return nextShort() >= 0;
    }

    public void printBits() {
        System.out.print(bits[M] ? 1 : 0);
        System.out.print(" -> ");
        for(int i = M - 1; i >= 0; i--) {
            System.out.print(bits[i] ? 1 : 0);
        }
        System.out.println();
    }


    public static void main(String[] args) {
        LFSR rng = new LFSR();
        Vector<Short> vec = new Vector<Short>();
        for(int i = 0; i <= 32766; i++) {
            short next = rng.nextShort();
            // just testing/asserting to make 
            // sure the number doesn't repeat on a given list
            if (vec.contains(next))
                throw new RuntimeException("Index repeat: " + i);
            vec.add(next);
            System.out.println(next);
        }
    }
}

Git push error pre-receive hook declined

Seems the problem is with some services, like sidekiq. Running sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production outputs all the problems with config.

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

What's the best practice using a settings file in Python?

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

How do I do a case-insensitive string comparison?

Section 3.13 of the Unicode standard defines algorithms for caseless matching.

X.casefold() == Y.casefold() in Python 3 implements the "default caseless matching" (D144).

Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å' vs. 'a°'). D145 introduces "canonical caseless matching":

import unicodedata

def NFD(text):
    return unicodedata.normalize('NFD', text)

def canonical_caseless(text):
    return NFD(NFD(text).casefold())

NFD() is called twice for very infrequent edge cases involving U+0345 character.

Example:

>>> 'å'.casefold() == 'a°'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('a°')
True

There are also compatibility caseless matching (D146) for cases such as '?' (U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.

How to add a TextView to a LinearLayout dynamically in Android?

If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.

It Should be like this.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    </LinearLayout>

Convert XLS to CSV on command line

There's an Excel OLEDB data provider built into Windows; you can use this to 'query' the Excel sheet via ADO.NET and write the results to a CSV file. There's a small amount of coding required, but you shouldn't need to install anything on the machine.

jQuery/Javascript function to clear all the fields of a form

    <form id="form" method="post" action="action.php">
      <input type="text" class="removeLater" name="name" /> Username<br/>
      <input type="text" class="removeLater" name="pass" /> Password<br/>
      <input type="text" class="removeLater" name="pass2" /> Password again<br/>
    </form>
    <script>
$(function(){
    $("form").submit(function(e){
         //do anything you want
         //& remove values
         $(".removeLater").val('');
    }

});
</script>

T-SQL: Selecting rows to delete via joins

I'm using this

DELETE TableA 
FROM TableA a
INNER JOIN
TableB b on b.Bid = a.Bid
AND [condition]

and @TheTXI way is good as enough but I read answers and comments and I found one things must be answered is using condition in WHERE clause or as join condition. So I decided to test it and write an snippet but didn't find a meaningful difference between them. You can see sql script here and important point is that I preferred to write it as commnet because of this is not exact answer but it is large and can't be put in comments, please pardon me.

Declare @TableA  Table
(
  aId INT,
  aName VARCHAR(50),
  bId INT
)
Declare @TableB  Table
(
  bId INT,
  bName VARCHAR(50)  
)

Declare @TableC  Table
(
  cId INT,
  cName VARCHAR(50),
  dId INT
)
Declare @TableD  Table
(
  dId INT,
  dName VARCHAR(50)  
)

DECLARE @StartTime DATETIME;
SELECT @startTime = GETDATE();

DECLARE @i INT;

SET @i = 1;

WHILE @i < 1000000
BEGIN
  INSERT INTO @TableB VALUES(@i, 'nameB:' + CONVERT(VARCHAR, @i))
  INSERT INTO @TableA VALUES(@i+5, 'nameA:' + CONVERT(VARCHAR, @i+5), @i)

  SET @i = @i + 1;
END

SELECT @startTime = GETDATE()

DELETE a
--SELECT *
FROM @TableA a
Inner Join @TableB b
ON  a.BId = b.BId
WHERE a.aName LIKE '%5'

SELECT Duration = DATEDIFF(ms,@StartTime,GETDATE())

SET @i = 1;
WHILE @i < 1000000
BEGIN
  INSERT INTO @TableD VALUES(@i, 'nameB:' + CONVERT(VARCHAR, @i))
  INSERT INTO @TableC VALUES(@i+5, 'nameA:' + CONVERT(VARCHAR, @i+5), @i)

  SET @i = @i + 1;
END

SELECT @startTime = GETDATE()

DELETE c
--SELECT *
FROM @TableC c
Inner Join @TableD d
ON  c.DId = d.DId
AND c.cName LIKE '%5'

SELECT Duration    = DATEDIFF(ms,@StartTime,GETDATE())

If you could get good reason from this script or write another useful, please share. Thanks and hope this help.

Array to Hash Ruby

Just use Hash.[] with the values in the array. For example:

arr = [1,2,3,4]
Hash[*arr] #=> gives {1 => 2, 3 => 4}

How can I send an Ajax Request on button click from a form with 2 buttons?

Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

$("#button_1, #button_2").on("click", function(e) {
    e.preventDefault();
    $.ajax({type: "POST",
        url: "/pages/test/",
        data: { id: $(this).val(), access_token: $("#access_token").val() },
        success:function(result) {
          alert('ok');
        },
        error:function(result) {
          alert('error');
        }
    });
});

What is an Endpoint?

An endpoint is a URL pattern used to communicate with an API.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Even though this is a pretty old questions with multiple accepted answers, I'd like to share how to resolve an obscure "undefined reference to" error.

Different versions of libraries

I was using an alias to refer to std::filesystem::path: filesystem is in the standard library since C++17 but my program needed to also compile in C++14 so I decided to use a variable alias:

#if (defined _GLIBCXX_EXPERIMENTAL_FILESYSTEM) //is the included filesystem library experimental? (C++14 and newer: <experimental/filesystem>)
using path_t = std::experimental::filesystem::path;
#elif (defined _GLIBCXX_FILESYSTEM) //not experimental (C++17 and newer: <filesystem>)
using path_t = std::filesystem::path;
#endif

Let's say I have three files: main.cpp, file.h, file.cpp:

  • file.h #include's <experimental::filesystem> and contains the code above
  • file.cpp, the implementation of file.h, #include's "file.h"
  • main.cpp #include's <filesystem> and "file.h"

Note the different libraries used in main.cpp and file.h. Since main.cpp #include'd "file.h" after <filesystem>, the version of filesystem used there was the C++17 one. I used to compile the program with the following commands:

$ g++ -g -std=c++17 -c main.cpp -> compiles main.cpp to main.o
$ g++ -g -std=c++17 -c file.cpp -> compiles file.cpp and file.h to file.o
$ g++ -g -std=c++17 -o executable main.o file.o -lstdc++fs -> links main.o and file.o

This way any function contained in file.o and used in main.o that required path_t gave "undefined reference" errors because main.o referred to std::filesystem::path but file.o to std::experimental::filesystem::path.

Resolution

To fix this I just needed to change <experimental::filesystem> in file.h to <filesystem>.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

in angular 7, you have to import "ReactiveFormsModule".

import {FormsModule, ReactiveFormsModule} from '@angular/forms';

I solved this issue by this import.It would help you.

Using "margin: 0 auto;" in Internet Explorer 8

As explained by buti-oxa this is a bug with the way IE8 handles replaced elements. If you don't want to add an explicit width to your button then you can change it to an inline-block and center align the contents:

<div style="height: 500px; width: 500px; background-color: Yellow; text-align: center;">
  <input type="submit" style="display: inline-block;" />
</div>

If you want this to work in older versions of Mozilla (including FF2) that don't support inline-block then you can add display: -moz-inline-stack; to the button.

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

How to unescape HTML character entities in Java?

The following library can also be used for HTML escaping in Java: unbescape.

HTML can be unescaped this way:

final String unescapedText = HtmlEscape.unescapeHtml(escapedText); 

How to create a property for a List<T>

It's possible to have a property of type List<T> but your class needs to be passed the T too.

public class ClassName<T>
{
  public List<T> MyProperty { get; set; }
}

how to align text vertically center in android

Try to put android:gravity="center_vertical|right" inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true" inside your scrollView.

Simple way to count character occurrences in a string

You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)

Regular Expression for alphanumeric and underscores

Required Format Allow these 3:

  1. 0142171547295
  2. 014-2171547295
  3. 123abc

Don't Allow other formats:

validatePnrAndTicketNumber(){
    let alphaNumericRegex=/^[a-zA-Z0-9]*$/;
    let numericRegex=/^[0-9]*$/;
    let numericdashRegex=/^(([1-9]{3})\-?([0-9]{10}))$/;
   this.currBookingRefValue = this.requestForm.controls["bookingReference"].value;
   if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){
     this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
   }else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){
    this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
   }else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){
    this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
   }else{
    this.requestForm.controls["bookingReference"].setErrors({'pattern': true});
   }
}
<input name="booking_reference" type="text" [class.input-not-empty]="bookingRef.value"
    class="glyph-input form-control floating-label-input" id="bookings_bookingReference"
    value="" maxlength="14" aria-required="true" role="textbox" #bookingRef
    formControlName="bookingReference" (focus)="resetMessageField()" (blur)="validatePnrAndTicketNumber()"/>

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

Dynamically change color to lighter or darker by percentage CSS (Javascript)

If you need to brute force it for older browser compatibility, you can use Colllor to automatically select similar color variations.

Example (color: #a9dbb4):

enter image description here

Difference between float and decimal data type

I found this useful:

Generally, Float values are good for scientific Calculations, but should not be used for Financial/Monetary Values. For Business Oriented Math, always use Decimal.

Source: http://code.rohitink.com/2013/06/12/mysql-integer-float-decimal-data-types-differences/

Maven error: Not authorized, ReasonPhrase:Unauthorized

You have an old password in the settings.xml. It is trying to connect to the repositories, but is not able to, since the password is not updated. Once you update and re-run the command, you should be good.

Calling a user defined function in jQuery

The following is the right method

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

Getting the first character of a string with $str[0]

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

MSIE and addEventListener Problem in Javascript?

Using <meta http-equiv="X-UA-Compatible" content="IE=9">, IE9+ does support addEventListener by removing the "on" in the event name, like this:

 var btn1 = document.getElementById('btn1');
 btn1.addEventListener('mousedown', function() {
   console.log('mousedown');
 });

SQL Server Installation - What is the Installation Media Folder?

Check in Administration Tools\Services (or type services.msc in the console if you a service named SQL Server (SQLEXPRESS). If you do then it is installed.

From Visual Studio open Server Explorer (menu View\Server Explorer or CTRL + W, L). Right click Data Connections and choose Create New SQL Server Database. After that create tables and stuff...

If you want the Management Studio to manage the server you must download and install it from:

http://www.microsoft.com/downloads/en/details.aspx?FamilyId=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

How to get HttpRequestMessage data

  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

Copy table to a different database on a different SQL Server

Yes. add a linked server entry, and use select into using the four part db object naming convention.

Example:

SELECT * INTO targetTable 
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]

Conda environments not showing up in Jupyter Notebook

Using only environment variables:

python -m ipykernel install --user --name $(basename $VIRTUAL_ENV)

No grammar constraints (DTD or XML schema) detected for the document

For me it was a Problem with character encoding and unix filemode running eclipse on Windows:

Just marked the complete code, cutted and pasted it back (in short: CtrlA-CtrlX-CtrlV) and everything was fine - no more "No grammar constraints..." warnings

jQuery: count number of rows in a table

If you use <tbody> or <tfoot> in your table, you'll have to use the following syntax or you'll get a incorrect value:

var rowCount = $('#myTable >tbody >tr').length;

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

Common elements comparison between 2 lists

use set intersections, set(list1) & set(list2)

>>> def common_elements(list1, list2):
...     return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>

Note that result list could be different order with original list.

JQuery DatePicker ReadOnly

I set the following beforeShow event handler (in the options parameter) to achieve this functionality.

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }

Change button text from Xcode?

There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:

[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal];
[btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];

Then switch the button state to Selected:

[btnCheckButton setSelected:YES];

Then switch the button state to Normal:

[btnCheckButton setSelected:NO];

Select query with date condition

select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate=  (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;

That should work.

Is there a way to make a DIV unselectable?

The following CSS code works almost modern browser:

.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

For IE, you must use JS or insert attribute in html tag.

<div id="foo" unselectable="on" class="unselectable">...</div>

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

Giving multiple conditions in for loop in Java

You can also replace complicated condition with single method call to make it less evil in maintain.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

Potentially, inconsistency of the node JS versions is what causes the problem. As stated in the documentation. Be sure to use one of the lts release. E.g. specify this in your Dockerfile:

# Pull lts from docker registry
FROM node:8.12.0

# ...

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

Visual studio code CSS indentation and formatting

I recommend using Prettier as it's very extensible but still works perfectly out of the box:

1. CMD + Shift + P -> Format Document

or

1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection

Full-screen responsive background image

You can also make full screen banner section without use of JavaScript, pure css based responsive full screen banner section , using height: 100vh; in banner main div, here have live example for this

#bannersection {
    position: relative;
    display: table;
    width: 100%;
    background: rgba(99,214,250,1);
    height: 100vh;
}

https://www.htmllion.com/fullscreen-header-banner-section.html

CSS to line break before/after a particular `inline-block` item

When rewriting the html is allowed, you can nest <ul>s within the <ul> and just let the inner <li>s display as inline-block. This would also semantically make sense IMHO, as the grouping also is reflected within the html.


<ul>
    <li>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>Item 4</li>
            <li>Item 5</li>
            <li>Item 6</li>
        </ul>
    </li>
</ul>

li li { display:inline-block; }

Demo

_x000D_
_x000D_
$(function() { $('img').attr('src', 'http://phrogz.net/tmp/alphaball.png'); });
_x000D_
h3 {_x000D_
  border-bottom: 1px solid #ccc;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
}_x000D_
ul {_x000D_
  margin: 0.5em auto;_x000D_
  list-style-type: none;_x000D_
}_x000D_
li li {_x000D_
  text-align: center;_x000D_
  display: inline-block;_x000D_
  padding: 0.1em 1em;_x000D_
}_x000D_
img {_x000D_
  width: 64px;_x000D_
  display: block;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h3>Features</h3>_x000D_
<ul>_x000D_
  <li>_x000D_
    <ul>_x000D_
      <li><img />Smells Good</li>_x000D_
      <li><img />Tastes Great</li>_x000D_
      <li><img />Delicious</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>_x000D_
    <ul>_x000D_
      <li><img />Wholesome</li>_x000D_
      <li><img />Eats Children</li>_x000D_
      <li><img />Yo' Mama</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Opening a new tab to read a PDF file

Use the below attribute in tag to open it in next tab

target="_blank"

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

How do you execute an arbitrary native command from a string?

If you want to use the call operator, the arguments can be an array stored in a variable:

$prog = 'c:\windows\system32\cmd.exe'
$myargs = '/c','dir','/x'
& $prog $myargs

The call operator works with ApplicationInfo objects too.

$prog = get-command cmd
$myargs = -split '/c dir /x'
& $prog $myargs

What is the difference between 'typedef' and 'using' in C++11?

They are equivalent, from the standard (emphasis mine) (7.1.3.2):

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Amazon S3 boto - how to create a folder?

Append "_$folder$" to your folder name and call put.

    String extension = "_$folder$";
    s3.putObject("MyBucket", "MyFolder"+ extension, new ByteArrayInputStream(new byte[0]), null);

see: http://www.snowgiraffe.com/tech/147/creating-folders-programmatically-with-amazon-s3s-api-putting-babies-in-buckets/

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

In Ubuntu, Installing latest version of gradle solved the issue for me.

Try these steps to install the latest version,

sudo add-apt-repository ppa:cwchien/gradle

sudo apt-get update

sudo apt-get install gradle

then build using,

cordova build android or ionic cordova build android

Note: If you install gradle from ubuntu repo, it will install the old version 1.4 and will not help, so sudo apt-get install gradle alone will not help most times, if you did not add the repo ppa:cwchien/gradle earlier

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Loop in react-native

 render() {
    var myloop = [];

    for (let i = 0; i < 10; i++) {
      myloop.push(
        <View key={i}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
        </View>
      );
    }

     return (

            <View >
              <Text >Welcome to React Native!</Text>
               {myloop}
            </View>


        );
      }

Output 1 2 3 4 5 6 7 8 9

What is the fastest factorial function in JavaScript?

 used closure  for this with the helper (getFact) , I think this approach is neat hope this helps  


    factorial of n : using closures*/

    function getFact(num) {

        if (num > 1)
            return num * getFact(num - 1);
        else
            return 1;

    }


    function makeFact(fn) {
        return function(num) {
            return fn(num);
        }


    }

   makeFact(getFact)(5) //120

SQL to generate a list of numbers from 1 to 100

Using GROUP BY CUBE:

SELECT ROWNUM
FROM (SELECT 1 AS c FROM dual GROUP BY CUBE(1,1,1,1,1,1,1) ) sub
WHERE ROWNUM <=100;

Rextester Demo

"R cannot be resolved to a variable"?

For me the error got fixed by making some changes in Android SDK Manager.
Whatever be the latest API level available, install its "SDK Platform". For me latest API level available was 16, so I installed its's SDK Platform as shown in the image below. It works fine now.

Screenshot of Android SDK Manager after fixing the problem
Cheers, Mayank

enum Values to NSString (iOS)

Below is a example of Enum Struct that is Objective-C friendly in the event you need to use Swift Code in Legacy projects written in Objective-C.

Example:

contentType.filename. toString()

returns "filename"


contentType.filename. rawValue

returns the Int Value, 1 (since its the second item on struct)

@objc enum contentType:Int {

    //date when content was created [RFC2183]
    case creationDate

    //name to be used when creating file    [RFC2183]
    case filename

    //whether or not processing is required [RFC3204]
    case handling

    //date when content was last modified   [RFC2183]
    case modificationDate

    //original field name in form   [RFC7578]
    case name

    //Internet media type (and parameters) of the preview output desired from a processor by the author of the MIME content [RFC-ietf-appsawg-text-markdown-12]
    case previewType

    //date when content was last read   [RFC2183]
    case readDate

    //approximate size of content in octets [RFC2183]
    case size

    //type or use of audio content  [RFC2421]
    case voice

    func toString() -> String {
        switch self {
        case .creationDate:
            return "creation-date"
        case .filename:
            return "filename"
        case .handling:
            return "handling"
        case .modificationDate:
            return "modification-date"
        case .name:
            return "name"
        case .previewType:
            return "preview-type"
        case .readDate:
                return "read-date"
        case .size:
            return "size"
        case .voice:
            return "voice"
        }
    }//eom
}//eo-enum

Convert timestamp to date in MySQL query

FROM_UNIXTIME(unix_timestamp, [format]) is all you need

FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'

FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.

The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

PySpark: withColumn() with two conditions and three outcomes

The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.

from pyspark.sql import functions as F
df=df.withColumn('new_column', 
    F.when(F.col('fruit1')==F.col('fruit2'), 1)
    .otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
    .otherwise(0))

Creating default object from empty value in PHP?

no you do not .. it will create it when you add the success value to the object.the default class is inherited if you do not specify one.

Reliable way to convert a file to a byte[]

All these answers with .ReadAllBytes(). Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?

A comment was made on one of the posts regarding .ReadAllBytes():

File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file 
and it failed) – juanjo.arana Mar 13 '13 at 1:31

A better approach, to me, would be something like this, with BinaryReader:

public static byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        var binaryReader = new BinaryReader(fs); 
        fileData = binaryReader.ReadBytes((int)fs.Length); 
    }
    return fileData;
}

But that's just me...

Of course, this all assumes you have the memory to handle the byte[] once it is read in, and I didn't put in the File.Exists check to ensure the file is there before proceeding, as you'd do that before calling this code.

Android Studio Emulator and "Process finished with exit code 0"

I was getting the following error when starting the emulator and none of the answers fixed it.

Emulator: Process finished with exit code -1073741515 (0xC0000135)

Finally I found that Visual C++ is not installed in my system. If it is not installed please install Visual C++ and check.

Please find the link below to download latest Visual C++.

https://support.microsoft.com/en-in/help/2977003/the-latest-supported-visual-c-downloads

Git error: "Please make sure you have the correct access rights and the repository exists"

I come across this error while uploading project to gitlab. I didn't clone from git but instead upload project. For pushing your code to gitlab you have two ways either using ssh or https. If you use https you have to enter username and password of gitlab account. For pushing you code to git you can use following one.

Pushing to Git for the first time

>$ cd
>$ mkdir .ssh;cd .ssh
>$ ssh-keygen -o -t rsa -b 4096 -C "[email protected]"

The -C parameter is optional, it provides a comment at the end of your key to distinguish it from others if you have multiple. This will create id_rsa (your private key) and id_rsa.pub (your public key). We pass our public key around and keep our private key — well, private. Gitlab’s User Settings is where you would then add your public key to your account, allowing us to finally push.

In your project location(Directory) use below command

git init

It Transform the current directory into a Git repository. This adds a .git subdirectory to the current directory and makes it possible to start recording revisions of the project.

Push Using https path

git push --set-upstream https://gitlab.com/Account_User_Name/Your_Project_Name.git master

Push Using ssh path

git push --set-upstream [email protected]:Account_User_Name/Your_project_Name.git master

— set-upstream: tells git the path to origin. If Git has previously pushed on your current branch, it will remember where origin is

master: this is the name of the branch I want to push to when initializing

How to add some non-standard font to a website?

@font-face {
font-family: "CustomFont";
src: url("CustomFont.eot");
src: url("CustomFont.woff") format("woff"),
url("CustomFont.otf") format("opentype"),
url("CustomFont.svg#filename") format("svg");
}

How to prevent tensorflow from allocating the totality of a GPU memory?

For Tensorflow 2.0 this this solution worked for me. (TF-GPU 2.0, Windows 10, GeForce RTX 2070)

physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.experimental.set_memory_growth(physical_devices[0], True)

How to determine day of week by passing specific date?

Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

Get the day value by providing the current time stamp.

List submodules in a Git repository

Just the submodule paths please, ma'am...

git config --list | grep \^submodule | cut -f 2 -d .
Vendor/BaseModel
Vendor/ObjectMatcher
Vendor/OrderedDictionary
Vendor/_ObjC
Vendor/XCodeHelpers

Assign one struct to another in C

Yes if the structure is of the same type. Think it as a memory copy.

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

Validate that a string is a positive integer

This is how I validate that a string is a positive integer.

_x000D_
_x000D_
var str = "123";
var str1 = "1.5";
var str2 = "-123";

console.log("is str positive integer: ", Number.isInteger(Number(str)) && Number(str) > 0)
console.log("is str1 positive integer: ", Number.isInteger(Number(str1)) && Number(str1) > 0)
console.log("is str2 positive integer: ", Number.isInteger(Number(str2)) && Number(str2) > 0)
_x000D_
_x000D_
_x000D_

How to solve a pair of nonlinear equations using Python?

You can use nsolve of sympy, meaning numerical solver.

Example snippet:

from sympy import *

L = 4.11 * 10 ** 5
nu = 1
rho = 0.8175
mu = 2.88 * 10 ** -6
dP = 20000
eps = 4.6 * 10 ** -5

Re, D, f = symbols('Re, D, f')

nsolve((Eq(Re, rho * nu * D / mu),
       Eq(dP, f * L / D * rho * nu ** 2 / 2),
       Eq(1 / sqrt(f), -1.8 * log ( (eps / D / 3.) ** 1.11 + 6.9 / Re))),
      (Re, D, f), (1123, -1231, -1000))

where (1123, -1231, -1000) is the initial vector to find the root. And it gives out:

enter image description here

The imaginary part are very small, both at 10^(-20), so we can consider them zero, which means the roots are all real. Re ~ 13602.938, D ~ 0.047922 and f~0.0057.

How to convert XML to JSON in Python?

Jacob Smullyan wrote a utility called pesterfish which uses effbot's ElementTree to convert XML to JSON.

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE

Using a cursor with dynamic SQL in a stored procedure

First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:

There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction

Row-By-Row Processing Without Cursor

That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.

But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....

window.onload vs document.onload

In short

  • window.onload is not supported by IE 6-8
  • document.onload is not supported by any modern browser (event is never fired)

_x000D_
_x000D_
window.onload   = () => console.log('window.onload works');   // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
_x000D_
_x000D_

hadoop copy a local file system folder to HDFS

If you copy a folder from local then it will copy folder with all its sub folders to HDFS.

For copying a folder from local to hdfs, you can use

hadoop fs -put localpath

or

hadoop fs -copyFromLocal localpath

or

hadoop fs -put localpath hdfspath

or

hadoop fs -copyFromLocal localpath hdfspath

Note:

If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.

To copy from hdfs to local

 hadoop fs -get hdfspath localpath

Working with TIFFs (import, export) in Python using numpy

I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.

import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.

Reactjs setState() with a dynamic key name?

I had a similar problem.

I wanted to set the state of where the 2nd level key was stored in a variable.

e.g. this.setState({permissions[perm.code]: e.target.checked})

However this isn't valid syntax.

I used the following code to achieve this:

this.setState({
  permissions: {
    ...this.state.permissions,
    [perm.code]: e.target.checked
  }
});

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

getPath() returns the path used to create the File object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)

File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"

File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"

File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"

getAbsolutePath() will resolve the path based on the execution location or drive. So if run from c:\test:

path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"

getCanonicalPath() is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.

As to when to use them. It depends on what you are trying to achieve. getPath() is useful for portability. getAbsolutePath() is useful to find the file system location, and getCanonicalPath() is particularly useful to check if two files are the same.

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

How to split elements of a list?

I had to split a list for feature extraction in two parts lt,lc:

ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)

featsets = [(act_features((lt)),lc) 
              for lc, lt in ltexts]

def act_features(atext):
  features = {}
  for word in nltk.word_tokenize(atext):
     features['cont({})'.format(word.lower())]=True
  return features

How to parse XML in Bash?

While it seems like "never parse XML, JSON... from bash without a proper tool" is sound advice, I disagree. If this is side job, it is waistfull to look for the proper tool, then learn it... Awk can do it in minutes. My programs have to work on all above mentioned and more kinds of data. Hell, I do not want to test 30 tools to parse 5-7-10 different formats I need if I can awk the problem in minutes. I do not care about XML, JSON or whatever! I need a single solution for all of them.

As an example: my SmartHome program runs our homes. While doing it, it reads plethora of data in too many different formats I can not control. I never use dedicated, proper tools since I do not want to spend more than minutes on reading the data I need. With FS and RS adjustments, this awk solution works perfectly for any textual format. But, it may not be the proper answer when your primary task is to work primarily with loads of data in that format!

The problem of parsing XML from bash I faced yesterday. Here is how I do it for any hierarchical data format. As a bonus - I assign data directly to the variables in a bash script.

To make thins easier to read, I will present solution in stages. From the OP test data, I created a file: test.xml

Parsing said XML in bash and extracting the data in 90 chars:

awk 'BEGIN { FS="<|>"; RS="\n" }; /host|username|password|dbname/ { print $2, $4 }' test.xml

I normally use more readable version since it is easier to modify in real life as I often need to test differently:

awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2,$4}' test.xml

I do not care how is the format called. I seek only the simplest solution. In this particular case, I can see from the data that newline is the record separator (RS) and <> delimit fields (FS). In my original case, I had complicated indexing of 6 values within two records, relating them, find when the data exists plus fields (records) may or may not exist. It took 4 lines of awk to solve the problem perfectly. So, adapt idea to each need before using it!

Second part simply looks it there is wanted string in a line (RS) and if so, prints out needed fields (FS). The above took me about 30 seconds to copy and adapt from the last command I used this way (4 times longer). And that is it! Done in 90 chars.

But, I always need to get the data neatly into variables in my script. I first test the constructs like so:

awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2"=\""$4"\"" }' test.xml

In some cases I use printf instead of print. When I see everything looks well, I simply finish assigning values to variables. I know many think "eval" is "evil", no need to comment :) Trick works perfectly on all four of my networks for years. But keep learning if you do not understand why this may be bad practice! Including bash variable assignments and ample spacing, my solution needs 120 chars to do everything.

eval $( awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2"=\""$4"\"" }' test.xml ); echo "host: $host, username: $username, password: $password dbname: $dbname"

How can I run code on a background thread on Android?

An Alternative to AsyncTask is robospice. https://github.com/octo-online/robospice.

Some of the features of robospice.

1.executes asynchronously (in a background AndroidService) network requests (ex: REST requests using Spring Android).notify you app, on the UI thread, when result is ready.

2.is strongly typed ! You make your requests using POJOs and you get POJOs as request results.

3.enforce no constraints neither on POJOs used for requests nor on Activity classes you use in your projects.

4.caches results (in Json with both Jackson and Gson, or Xml, or flat text files, or binary files, even using ORM Lite).

5.notifies your activities (or any other context) of the result of the network request if and only if they are still alive

6.no memory leak at all, like Android Loaders, unlike Android AsyncTasks notifies your activities on their UI Thread.

7.uses a simple but robust exception handling model.

Samples to start with. https://github.com/octo-online/RoboSpice-samples.

A sample of robospice at https://play.google.com/store/apps/details?id=com.octo.android.robospice.motivations&feature=search_result.

PadLeft function in T-SQL

More efficient way is :

Select id, LEN(id)
From TableA
Order by 2,1 

The result :
id
----
1
2
12
123
1234

What's the difference between commit() and apply() in SharedPreferences

The docs give a pretty good explanation of the difference between apply() and commit():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

I had the same issue.

just removed all my worskspace:

C:\Users\<name>\.<eclipse similar name>

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Adding an answer that's completely based on and indebted to divestoclimb with a hint from Shaun Stone. Just wanted to spell it out in detail since it's a common problem and the solution is a bit confusing.

This is using Hibernate 4.1.4.Final, though I suspect anything after 3.6 will work.

First, create divestoclimb's UtcTimestampTypeDescriptor

public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
    public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>( javaTypeDescriptor, this ) {
            @Override
            protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
                st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
            }
        };
    }

    public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicExtractor<X>( javaTypeDescriptor, this ) {
            @Override
            protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
                return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
            }
        };
    }
}

Then create UtcTimestampType, which uses UtcTimestampTypeDescriptor instead of TimestampTypeDescriptor as the SqlTypeDescriptor in the super constructor call but otherwise delegates everything to TimestampType:

public class UtcTimestampType
        extends AbstractSingleColumnStandardBasicType<Date>
        implements VersionType<Date>, LiteralType<Date> {
    public static final UtcTimestampType INSTANCE = new UtcTimestampType();

    public UtcTimestampType() {
        super( UtcTimestampTypeDescriptor.INSTANCE, JdbcTimestampTypeDescriptor.INSTANCE );
    }

    public String getName() {
        return TimestampType.INSTANCE.getName();
    }

    @Override
    public String[] getRegistrationKeys() {
        return TimestampType.INSTANCE.getRegistrationKeys();
    }

    public Date next(Date current, SessionImplementor session) {
        return TimestampType.INSTANCE.next(current, session);
    }

    public Date seed(SessionImplementor session) {
        return TimestampType.INSTANCE.seed(session);
    }

    public Comparator<Date> getComparator() {
        return TimestampType.INSTANCE.getComparator();        
    }

    public String objectToSQLString(Date value, Dialect dialect) throws Exception {
        return TimestampType.INSTANCE.objectToSQLString(value, dialect);
    }

    public Date fromStringValue(String xml) throws HibernateException {
        return TimestampType.INSTANCE.fromStringValue(xml);
    }
}

Finally, when you initialize your Hibernate configuration, register UtcTimestampType as a type override:

configuration.registerTypeOverride(new UtcTimestampType());

Now timestamps shouldn't be concerned with the JVM's time zone on their way to and from the database. HTH.

Create table with jQuery - append

Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.

var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;           


$.each(data, function(i) {
  if(!(i%numCols)) tRow = $('<tr>');

  tCell = $('<td>').html(data[i]);

  $('table').append(tRow.append(tCell));
});
?

http://jsfiddle.net/n7cyE/93/

Why catch and rethrow an exception in C#?

Don't do this,

try 
{
...
}
catch(Exception ex)
{
   throw ex;
}

You'll lose the stack trace information...

Either do,

try { ... }
catch { throw; }

OR

try { ... }
catch (Exception ex)
{
    throw new Exception("My Custom Error Message", ex);
}

One of the reason you might want to rethrow is if you're handling different exceptions, for e.g.

try
{
   ...
}
catch(SQLException sex)
{
   //Do Custom Logging 
   //Don't throw exception - swallow it here
}
catch(OtherException oex)
{
   //Do something else
   throw new WrappedException("Other Exception occured");
}
catch
{
   System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
   throw; //Chuck everything else back up the stack
}

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

In my case i just went through following steps in windows 10.

  1. goto control panel
  2. click administrative
  3. click services
  4. find OracelServeceXE, OracleXEClrAgeng, OracleXETNSListener
  5. Right click and press Start/Restart
  6. After Completing Process. Check it will work or it will work ;)
  7. Done
  8. All the Best.

jQuery append() - return appended elements

I think you could do something like this:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.

$child is then the jquery wrapped child div that was added.

Why can't radio buttons be "readonly"?

I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.

<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>

For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.

<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>

This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.

Using an Alias in a WHERE clause

 SELECT A.identifier
 , A.name
 , TO_NUMBER(DECODE( A.month_no
         , 1, 200803 
         , 2, 200804 
         , 3, 200805 
         , 4, 200806 
         , 5, 200807 
         , 6, 200808 
         , 7, 200809 
         , 8, 200810 
         , 9, 200811 
         , 10, 200812 
         , 11, 200701 
         , 12, 200702
         , NULL)) as MONTH_NO
 , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A, table_b B
WHERE .identifier = B.identifier
HAVING MONTH_NO > UPD_DATE

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

How to stop/shut down an elasticsearch node?

The Head plugin for Elasticsearch provides a great web based front end for Elasticsearch administration, including shutting down nodes. It can run any Elasticsearch commands as well.

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Localhost not working in chrome and firefox

In case the browser LAN proxy setting solution doesn't work for you:

As mentioned in this similar Q&A How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Simply changing the port number of your web project can be a quick fix.

enter image description here

How can I URL encode a string in Excel VBA?

Version of the above supporting UTF8:

Private Const CP_UTF8 = 65001

#If VBA7 Then
  Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As LongPtr, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As LongPtr, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long _
    ) As Long
#Else
  Private Declare Function WideCharToMultiByte Lib "kernel32" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As Long, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long _
    ) As Long
#End If

Public Function UTF16To8(ByVal UTF16 As String) As String
Dim sBuffer As String
Dim lLength As Long
If UTF16 <> "" Then
    #If VBA7 Then
        lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, 0, 0, 0, 0)
    #Else
        lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, 0, 0, 0, 0)
    #End If
    sBuffer = Space$(lLength)
    #If VBA7 Then
        lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, CLngPtr(StrPtr(sBuffer)), LenB(sBuffer), 0, 0)
    #Else
        lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, StrPtr(sBuffer), LenB(sBuffer), 0, 0)
    #End If
    sBuffer = StrConv(sBuffer, vbUnicode)
    UTF16To8 = Left$(sBuffer, lLength - 1)
Else
    UTF16To8 = ""
End If
End Function

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False, _
   Optional UTF8Encode As Boolean = True _
) As String

Dim StringValCopy As String: StringValCopy = IIf(UTF8Encode, UTF16To8(StringVal), StringVal)
Dim StringLen As Long: StringLen = Len(StringValCopy)

If StringLen > 0 Then
    ReDim Result(StringLen) As String
    Dim I As Long, CharCode As Integer
    Dim Char As String, Space As String

  If SpaceAsPlus Then Space = "+" Else Space = "%20"

  For I = 1 To StringLen
    Char = Mid$(StringValCopy, I, 1)
    CharCode = Asc(Char)
    Select Case CharCode
      Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
        Result(I) = Char
      Case 32
        Result(I) = Space
      Case 0 To 15
        Result(I) = "%0" & Hex(CharCode)
      Case Else
        Result(I) = "%" & Hex(CharCode)
    End Select
  Next I
  URLEncode = Join(Result, "")

End If
End Function

Enjoy!

how to convert JSONArray to List of Object using camel-jackson

/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}

Deserialize JSON array(or list) in C#

This code works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Json
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DeserializeNames());
            Console.ReadLine();
        }

        public static string DeserializeNames()
        {
            var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

            JavaScriptSerializer ser = new JavaScriptSerializer();

            nameList myNames = ser.Deserialize<nameList>(jsonData);

            return ser.Serialize(myNames);
        }

        //Class descriptions

        public class name
        {
            public string last { get; set; }
        }

        public class nameList
        {
            public List<name> name { get; set; }
        }
    }
}

How to increase timeout for a single test case in mocha

From command line:

mocha -t 100000 test.js

Converting dictionary to JSON

json.dumps() returns the JSON string representation of the python dict. See the docs

You can't do r['rating'] because r is a string, not a dict anymore

Perhaps you meant something like

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

How to uninstall Golang?

For Windows 10:

  1. Go to Apps in the Settings App.
  2. Look for Go Programming Language * in the list and uninstall it.
  3. Remove C:\Go\bin from your PATH environment variable (only if you don't plan on installing another version of golang)

ValidateAntiForgeryToken purpose, explanation and example

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.

A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.

It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:

[HttpPost]  
[ValidateAntiForgeryToken]  
public ActionResult CreateProduct(Product product)  
{
  if (ModelState.IsValid)  
  {
    //your logic 
  }
  return View(ModelName);
}

It is derived from System.Web.Mvc namespace.

And in your view, add this code to add the token so it is used to validate the form upon submission.

@Html.AntiForgeryToken()

What are the ways to sum matrix elements in MATLAB?

You are trying to sum up all the elements of 2-D Array

In Matlab use

Array_Sum = sum(sum(Array_Name));

How do I add an "Add to Favorites" button or link on my website?

Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon

Trying to make some order:

it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.

The problem is that it takes its values from the calling <a ..> tag: title as the bookmark name and href as the bookmark address. so this is my code:

javascript:

$("#bookmarkme").click(function () {
  var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
  var name = "Snir's Homepage";

  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
    alert("In order to bookmark go to the homepage and press " 
        + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 
            'Command/Cmd' : 'CTRL') + "+D.")
  } 
  else if (window.sidebar) { // Mozilla Firefox Bookmark
    //important for firefox to add bookmarks - remember to check out the checkbox on the popup
    $(this).attr('rel', 'sidebar');
    //set the appropriate attributes
    $(this).attr('href', url);
    $(this).attr('title', name);

    //add bookmark:
    //  window.sidebar.addPanel(name, url, '');
    //  window.sidebar.addPanel(url, name, '');
    window.sidebar.addPanel('', '', '');
  } 
  else if (window.external) { // IE Favorite
        window.external.addFavorite(url, name);
  } 
  return;
});

html:

  <a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>

In internet explorer there is a different between 'addFavorite': <a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a> and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>.

example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html

Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf

How to install PHP mbstring on CentOS 6.2

do the following:

sudo nano /etc/yum.repos.d/CentOS-Base.repo

under the section updates, comment out the mirrorlist line (put a # in front of the line), then on a new line write:

baseurl=http://centos.intergenia.de/$releasever/updates/$basearch/

now try:

yum install php-mbstring

(afterwards you'll probably want to uncomment the mirrorlist and comment out the baseurl)

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Python: SyntaxError: keyword can't be an expression

I guess many of us who came to this page have a problem with Scikit Learn, one way to solve it is to create a dictionary with parameters and pass it to the model:

params = {'C': 1e9, 'gamma': 1e-07}
cls = SVC(**params)    

How to find a Java Memory Leak

There are tools that should help you find your leak, like JProbe, YourKit, AD4J or JRockit Mission Control. The last is the one that I personally know best. Any good tool should let you drill down to a level where you can easily identify what leaks, and where the leaking objects are allocated.

Using HashTables, Hashmaps or similar is one of the few ways that you can acually leak memory in Java at all. If I had to find the leak by hand I would peridically print the size of my HashMaps, and from there find the one where I add items and forget to delete them.

Add CSS3 transition expand/collapse

http://jsfiddle.net/Bq6eK/215/

I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.

As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.

I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.

The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.

My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.

Using two CSS classes on one element

If you only have two items, you can do this:

.social {
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
    border: none;
}

.social:first-child { 
    padding-top:0;
    border-bottom: dotted 1px #6d6d6d;
}

Get a particular cell value from HTML table using JavaScript

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

How do I get the name of a Ruby class?

If you want to get a class name from inside a class method, class.name or self.class.name won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

module Foo
  class Bar
    def self.say_name
      puts "I'm a #{name}!"
    end
  end
end

Foo::Bar.say_name

output:

I'm a Foo::Bar!

How to set Apache Spark Executor memory

You can build command using following example

 spark-submit    --jars /usr/share/java/postgresql-jdbc.jar    --class com.examples.WordCount3  /home/vaquarkhan/spark-scala-maven-project-0.0.1-SNAPSHOT.jar --jar  --num-executors 3 --driver-memory 10g **--executor-memory 10g** --executor-cores 1  --master local --deploy-mode client  --name wordcount3 --conf "spark.app.id=wordcount" 

Extracting the last n characters from a string in R

UPDATE: as noted by mdsumner, the original code is already vectorised because substr is. Should have been more careful.

And if you want a vectorised version (based on Andrie's code)

substrRight <- function(x, n){
  sapply(x, function(xx)
         substr(xx, (nchar(xx)-n+1), nchar(xx))
         )
}

> substrRight(c("12345","ABCDE"),2)
12345 ABCDE
 "45"  "DE"

Note that I have changed (nchar(x)-n) to (nchar(x)-n+1) to get n characters.

How do I create 7-Zip archives with .NET?

SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.

As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

For me this was the solution.

The problem was that the SVN server was behind a reverse-proxy (pound). And the reverse proxy had to be told to allow OPTIONS.

Extract a substring using PowerShell

Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.

It's not completely intuitive because of the fact the first letter is referred to by index = 0, but it does:

  • Allow a second index number that is longer than the string, without generating an error
  • Extract substrings in reverse
  • Extract substrings from the end of the string

Here are some examples:

PS > 'Hello World'[0..2]

Yields the result (index values included for clarity - not generated in output):

H [0]
e [1]
l [2]

Which can be made more useful by passing -join '':

PS > 'Hello World'[0..2] -join ''
Hel

There are some interesting effects you can obtain by using different indices:

Forwards

Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:

PS > 'Hello World'[3..300] -join ''
lo World

Unlike:

PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.

Backwards

If you supply a second index value that is lower than the first, the string is returned in reverse:

PS > 'Hello World'[4..0] -join ''
olleH

From End

If you use negative numbers you can refer to a position from the end of the string. To extract 'World', the last 5 letters, we use:

PS > 'Hello World'[-5..-1] -join ''
World

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

How to search in an array with preg_match?

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

How to unpublish an app in Google Play Developer Console

TL;DR: (As of September 2020) Open the Play Console. Select an app. Select Release > Setup >Advanced settings. On the App Availability tab, select Unpublish.

Setup - Advanced settings Unpublish app dialog Verify app unpublished

From https://support.google.com/googleplay/android-developer/answer/9859350?hl=en&ref_topic=9872026:

When you unpublish an app, existing users can still use your app and receive app updates. Your app won’t be available for new users to find and download on Google Play.

Prerequisites

  • You have accepted the latest Developer Distribution Agreement.
  • Your app has no errors that need to be addressed, such as failing to fill in the content rating questionnaire or provide details about your app's target audience and content.
  • Managed publishing is not active for the app you want to unpublish.

To unpublish your app:

Open the Play Console. Select an app. Select Release > Setup > Advanced settings. On the App Availability tab, select Unpublish.

How to Disable Managed publishing

Managed publishing overview Managed publishing toggle dialog

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

On IntelliJ go to Preference -> Build, Execution, Deployment -> Build Tools -> Maven. Turn on the checkbox for "Always update snapshots" apply and save changes then do mvn clean install

Detect end of ScrollView

I went through the solutions on the internet. Mostly solutions didn't work in the project I'm working on. Following solutions work fine for me.

Using onScrollChangeListener (works on API 23):

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollY;

                if(scrollY==0){
                    //top detected
                }
                if(bottom==0){
                    //bottom detected
                }
            }
        });
    }

using scrollChangeListener on TreeObserver

 scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollView.getScrollY();

            if(scrollView.getScrollY()==0){
                //top detected
            }
            if(bottom==0) {
                //bottom detected
            }
        }
    });

Hope this solution helps :)

AttributeError: Module Pip has no attribute 'main'

To verify whether is your pip installation problem, try using easy_install to install an earlier version of pip:

easy_install pip==9.0.1

If this succeed, pip should be working now. Then you can go ahead to install any other version of pip you want with:

pip install pip==10....

Or you can just stay with version 9.0.1, as your project requires version >= 9.0.

Try building your project again.

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

Calculating distance between two points, using latitude longitude?

Note: this solution only works for short distances.

I tried to use dommer's posted formula for an application and found it did well for long distances but in my data I was using all very short distances, and dommer's post did very poorly. I needed speed, and the more complex geo calcs worked well but were too slow. So, in the case that you need speed and all the calculations you're making are short (maybe < 100m or so). I found this little approximation to work great. it assumes the world is flat mind you, so don't use it for long distances, it works by approximating the distance of a single Latitude and Longitude at the given Latitude and returning the Pythagorean distance in meters.

public class FlatEarthDist {
    //returns distance in meters
    public static double distance(double lat1, double lng1, 
                                      double lat2, double lng2){
     double a = (lat1-lat2)*FlatEarthDist.distPerLat(lat1);
     double b = (lng1-lng2)*FlatEarthDist.distPerLng(lat1);
     return Math.sqrt(a*a+b*b);
    }

    private static double distPerLng(double lat){
      return 0.0003121092*Math.pow(lat, 4)
             +0.0101182384*Math.pow(lat, 3)
                 -17.2385140059*lat*lat
             +5.5485277537*lat+111301.967182595;
    }

    private static double distPerLat(double lat){
            return -0.000000487305676*Math.pow(lat, 4)
                -0.0033668574*Math.pow(lat, 3)
                +0.4601181791*lat*lat
                -1.4558127346*lat+110579.25662316;
    }
}

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

How to list all installed packages and their versions in Python?

To run this in later versions of pip (tested on pip==10.0.1) use the following:

from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
    print(requirement)

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.

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

How to change the commit author for one specific commit?

When doing git rebase -i there is this interesting bit in the doc:

If you want to fold two or more commits into one, replace the command "pick" for the second and subsequent commits with "squash" or "fixup". If the commits had different authors, the folded commit will be attributed to the author of the first commit. The suggested commit message for the folded commit is the concatenation of the commit messages of the first commit and of those with the "squash" command, but omits the commit messages of commits with the "fixup" command.

  • If you have an history of A-B-C-D-E-F,
  • and you want to change commits B and D (= 2 commits),

then you can do:

  • git config user.name "Correct new name"
  • git config user.email "[email protected]"
  • create empty commits (one for each commit):
    • you need a message for rebase purpose
    • git commit --allow-empty -m "empty"
  • start the rebase operation
    • git rebase -i B^
    • B^ selects the parent of B.
  • you will want to put one empty commit before each commit to modify
  • you will want to change pick to squash for those.

Example of what git rebase -i B^ will give you:

pick sha-commit-B some message
pick sha-commit-C some message
pick sha-commit-D some message
pick sha-commit-E some message
pick sha-commit-F some message
# pick sha-commit-empty1 empty
# pick sha-commit-empty2 empty

change that to:

# change commit B's author
pick sha-commit-empty1 empty
squash sha-commit-B some message
# leave commit C alone
pick sha-commit-C some message
# change commit D's author
pick sha-commit-empty2 empty
squash sha-commit-D some message
# leave commit E-F alone
pick sha-commit-E some message
pick sha-commit-F some message

It will prompt you to edit the messages:

# This is a combination of 2 commits.
# The first commit's message is:

empty

# This is the 2nd commit message:

...some useful commit message there...

and you can just remove the first few lines.

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:

<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>

The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:

<script>var jsonData = <?php include('stuff.json');?>;</script>

The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.

What is a void pointer in C++?

Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

General Syntax:

void* pointer_variable;

void *pVoid; // pVoid is a void pointer

A void pointer can point to objects of any data type:

int nValue;
float fValue;

struct Something
{
    int nValue;
    float fValue;
};

Something sValue;

void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid

However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

int nValue = 5;
void *pVoid = &nValue;

// can not dereference pVoid because it is a void pointer

int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Source: link

Cosine Similarity between 2 Number Lists

import math
from itertools import izip

def dot_product(v1, v2):
    return sum(map(lambda x: x[0] * x[1], izip(v1, v2)))

def cosine_measure(v1, v2):
    prod = dot_product(v1, v2)
    len1 = math.sqrt(dot_product(v1, v1))
    len2 = math.sqrt(dot_product(v2, v2))
    return prod / (len1 * len2)

You can round it after computing:

cosine = format(round(cosine_measure(v1, v2), 3))

If you want it really short, you can use this one-liner:

from math import sqrt
from itertools import izip

def cosine_measure(v1, v2):
    return (lambda (x, y, z): x / sqrt(y * z))(reduce(lambda x, y: (x[0] + y[0] * y[1], x[1] + y[0]**2, x[2] + y[1]**2), izip(v1, v2), (0, 0, 0)))

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

One particular case : Before learning bootstrap grid system, make sure browser zoom is set to 100% (a hundred percent). For example : If screen resolution is (1600px x 900px) and browser zoom is 175%, then "bootstrap-ped" elements will be stacked.

HTML

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-4">class="col-lg-4"</div>
        <div class="col-lg-4">class="col-lg-4"</div>
    </div>
</div>

Chrome zoom 100%

Browser 100 percent - elements placed horizontally

Chrome zoom 175%

Browser 175 percent - stacked elements

Constructors in JavaScript objects

In JavaScript the invocation type defines the behaviour of the function:

  • Direct invocation func()
  • Method invocation on an object obj.func()
  • Constructor invocation new func()
  • Indirect invocation func.call() or func.apply()

The function is invoked as a constructor when calling using new operator:

function Cat(name) {
   this.name = name;
}
Cat.prototype.getName = function() {
   return this.name;
}

var myCat = new Cat('Sweet'); // Cat function invoked as a constructor

Any instance or prototype object in JavaScript have a property constructor, which refers to the constructor function.

Cat.prototype.constructor === Cat // => true
myCat.constructor         === Cat // => true

Check this post about constructor property.

Twitter Bootstrap vs jQuery UI?

We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.

Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.

So I see no point in using something that will eventually be outdated...

Get Locale Short Date Format using javascript

Using en-CA as an example, if you're using date-fns:

_x000D_
_x000D_
<script type="module">
  import { enCA } from 'https://cdn.skypack.dev/date-fns/locale';
  console.log(enCA.formatLong.date({width:'short'}))
  // yyyy-MM-dd
</script>
_x000D_
_x000D_
_x000D_

Source: https://github.com/date-fns/date-fns/blob/master/src/locale/en-CA/_lib/formatLong/index.js

For CLDR & Paul Irish:

import locale from 'cldr-dates-modern/main/en-CA/ca-gregorian.json'
console.log(locale.main['en-CA'].dates.calendars.gregorian.dateFormats.short)
// y-MM-dd

Source: https://github.com/unicode-cldr/cldr-dates-modern/blob/master/main/en-CA/ca-gregorian.json

HTTPS using Jersey Client

For Jersey 2 you'd need to modify the code:

        return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

You may also get this warning for MS Fakes assemblies which isn't as easy to resolve since the f.csproj is build on command. Luckily the Fakes xml allows you to add it in there.

Set Google Maps Container DIV width and height 100%

This Work for me.

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

#cont{
    position: relative;
    width: 300px;
    height: 300px;
}
#map_canvas{
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
</style> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=APIKEY"></script>
<script type="text/javascript">
function initialize() {
    console.log("Initializing...");
  var latlng = new google.maps.LatLng(LAT, LNG);
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
}
</script>
</head>

<body onload="initialize()">
<div id="cont">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</div>
</body>
</html>