Programs & Examples On #Master

Gerrit error when Change-Id in commit messages are missing

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

a) I don't know how to execute step 1 in windows so skipped it and used hardcoded path in step 2 scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg .git/hooks/

b) In case you get below error, manually create "hooks" directory in .git folder

protocol error: expected control record

c) if you have submodule let's say "XX" then you need to repeat step 2 there as well and this time replace ${gitdir} with that submodules path

d) In case scp is not recognized by windows give full path of scp

"C:\Program Files\Git\usr\bin\scp.exe"

e) .git folder is present in your project repo and it's hidden folder

ElasticSearch: Unassigned Shards, how to fix?

I ran into exactly the same issue. This can be prevented by temporarily setting the shard allocation to false before restarting elasticsearch, but this does not fix the unassigned shards if they are already there.

In my case it was caused by lack of free disk space on the data node. The unassigned shards where still on the data node after the restart but they where not recognized by the master.

Just cleaning 1 of the nodes from the disk got the replication process started for me. This is a rather slow process because all the data has to be copied from 1 data node to the other.

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

First you use a full stop, then you hold down alt and press the letter H and put in another full stop. .?.

Fixing npm path in Windows 8 and 10

I've had this issue in 2 computers in my house using Windows 10 each. The problem began when i had to change few Environmental variables for projects that I've been working on Visual studio 2017 etc. After few months coming back to using node js and npm I had this issue again and non of the solutions above helped. I saw Sean's comment on Yar's solution and i mixed both solutions: 1) at the environmental variables window i had one extra variable that held this value: %APPDATA%\npm. I deleted it and the problem dissapeared!

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Angular 2 two way binding using ngModel is not working

As per Angular2 final, you do not even have to import FORM_DIRECTIVES as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.

Just replace ng-model with ngModel and wrap it in a box of bananas. But you have spilt the code into two files now:

app.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'ng-app',
  template: `
    <input id="name" type="text" [(ngModel)]="name"  />
    {{ name }}
  `
})
export class DataBindingComponent {
  name: string;

  constructor() {
    this.name = 'Jose';
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above

@NgModule({
  declarations: [DataBindingComponent],
  imports:      [BrowserModule, FormsModule],
  bootstrap:    [DataBindingComponent]
})
export default class MyAppModule {}

platformBrowserDynamic().bootstrapModule(MyAppModule);

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

How does ApplicationContextAware work in Spring?

ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class

public void setApplicationContext(ApplicationContext context) throws BeansException.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

My problem was a modified AuthorizedKeysFile, when the automation to populate /etc/ssh/authorized_keys had not yet been run.

$sudo grep AuthorizedKeysFile /etc/ssh/sshd_config
#AuthorizedKeysFile .ssh/authorized_keys
AuthorizedKeysFile  /etc/ssh/authorized_keys/%u

how to apply click event listener to image in android

In xml:

<ImageView  
 android:clickable="true"  
 android:onClick="imageClick"  
 android:src="@drawable/myImage">  
 </ImageView>  

In code

 public class Test extends Activity {  
  ........  
  ........  
 public void imageClick(View view) {  
  //Implement image click function  
 }  

How to dismiss notification after action has been clicked

In new APIs don't forget about TAG:

notify(String tag, int id, Notification notification)

and correspondingly

cancel(String tag, int id) 

instead of:

cancel(int id)

https://developer.android.com/reference/android/app/NotificationManager

Understanding the set() function

Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.

Here's an example of a set changing order after a lot of values are added and then removed:

>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
    s.remove(v)
>>> print(s)
{1, 6, 8}

This is implementation dependent though, and so you should not rely upon it.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I had a similar situation, where my master branch and the develop branch I was trying to merge had different commit histories. None of the above solutions worked for me. What did the trick was:

Starting from master:

git branch new_branch
git checkout new_branch
git merge develop --allow-unrelated-histories

Now in the new_branch, there are all the things from develop and I can easily merge into master, or create a pull request, as they now share the same commit hisotry.

How do you configure HttpOnly cookies in tomcat / java webapps?

Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.

private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
    if (response.containsHeader("SET-COOKIE")) {
        String sessionid = request.getSession().getId();
        String contextPath = request.getContextPath();
        String secure = "";
        if (request.isSecure()) {
            secure = "; Secure"; 
        }
        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
                         + "; Path=" + contextPath + "; HttpOnly" + secure);
    }
}

Selecting a Linux I/O Scheduler

You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)

Example:

elevator=deadline

This will make "deadline" the default I/O scheduler for all block devices.

If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.

https://github.com/kata198/ioschedset

If you're on Archlinux it's available in aur:

https://aur.archlinux.org/packages/ioschedset

Some example usage:

# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda:    bfq
sr0:    bfq

# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none

# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...

[sudo] password for username:
+ Successfully set sda to 'kyber'!

# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda:    kyber
sr0:    bfq

# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...

+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!

# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda:    mq-deadline

Usage should be self-explanatory. The tools are standalone and only require bash.

Hope this helps!

EDIT: Disclaimer, these are scripts I wrote.

php - get numeric index of associative array

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and just solved it. I had posted my own question on stackoverflow:

Can't PUT to my IHttpHandler, GET works fine

The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.

<modules runManagedModulesForWebDavRequests="true">
...
</modules>

So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

How to use Git and Dropbox together?

On MacOS you may also just stop Dropbox, make your changes and then relaunch Dropbox. I am using the following combination and am quite happy with it:

In both (your local git managed project directory and your remote git repository located on Dropbox) run the following command to disable auto-packing (which is the main problem with dropbox syncing)

git config --global gc.auto 0

Then from time to time, compress the repositories with dropbox disabled. For example I do the following in my bash-build-script whenever I make new releases of my apps.

osascript -e "tell application \"Dropbox\" to quit"

# Compress local
git gc --prune=now; git repack -a -d

# Compress remote
REPOS_DIR_REMOTE=`git remote get-url --push origin`
cd "${REPOS_DIR_REMOTE}"
git gc --prune=now; git repack -a -d

osascript -e "tell application \"Dropbox\" to launch"
osascript -e "display notification with title \"Compress Done\""

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How does the "position: sticky;" property work?

Check if an ancestor element has overflow set (e.g. overflow:hidden); try toggling it. You may have to go up the DOM tree higher than you expect =).

This may affect your position:sticky on a descendant element.

How do I tell if .NET 3.5 SP1 is installed?

Use Add/Remove programs from the Control Panel.

How to add multiple classes to a ReactJS Component?

When I have many varying classes, I have found the following to be useful.

The filter removes any of the null values and the join puts all the remaining values into a space separated string.

const buttonClasses = [
    "Button", 
    disabled ? "disabled" : null,
    active ? "active" : null
].filter((class) => class).join(" ")

<button className={buttonClasses} onClick={onClick} disabled={disabled ? disabled : false}>

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

How can I select the row with the highest ID in MySQL?

Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue, so Yes you can do it with the following query:

select * from tabel_name where employee_no='123' and id=(
   select max(id) from table_name where employee_no='123' and leave_type='5'
)

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

Filter by process/PID in Wireshark

You can check for port numbers with these command examples on wireshark:-

tcp.port==80

tcp.port==14220

Loop backwards using indices in Python?

I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)

def reverse(text):
    chars= []
    l = len(text)
    last = l-1
    for i in range (l):
        chars.append(text[last])
        last-=1

    result= ""   
    for c in chars:
        result += c
    return result
print reverse('hola')

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

What is the difference between application server and web server?

This is a detailed answer with some scenarios to clearly understand the difference and similarity, and how both can work in conjunction.

Application Server is a term that sometimes is mixed with a web server. While a web server handles mainly HTTP protocols, the application server deals with several different protocols, including, but not limited, to HTTP.

The Web server's main job is to display the site content and the application server is in charge of the logic, the interaction between the user and the displayed content. The application server is working in conjunction with the web server, where one displays and the other one interacts.

The information traveling back and forth between the server and its client is not restricted to simple display markup, but to interaction between the two.

In most cases, the server creates this interaction through a component API, such as J2EE (Java 2 Platform), EJB (Enterprise JavaBean) and other different application software models.

enter image description here

An example:

The best way to understand the difference between the scenarios where an application server works with the web server versus a scenario where there isn't an application server is through an online store.

Scenario 1: Web server without an application server

you have an online store with only a web server and no application server. The site will provide a display where you can choose a product from. When you submit a query, the site performs a lookup and returns an HTML result back to its client. The web server sends your query directly to the database server (be patient, I will explain this one in our next nugget) and waits for a response. Once received, the web server formulates the response into an HTML file and sends it to your web browser. This back and forth communication between the server and database server happens every time a query is run.

Scenario 2: Web server with an application server

if the query you want to run has already been done previously and no data has changed since then, the server will generate the results without having to send the request to the database server. This allows a real-time query where a second client can access the same info and receive real time, reliable information without sending another duplicate query to the database server. The server basically acts as an intermediate between the database server and the web server. This allows the information pulled to be reusable while in the first scenario, since this info is embedded in a particular and "customized" HTML page, this is not a reusable process. A second client will have to request the info again and receive another HTML embedded page with the info requested -highly inefficient. Not to mention that this type of server is very flexible due to its ability to manage its own resources, including security, transaction processing, messaging and resource pooling.

To support such a variety of complex tasks this server must have a built in redundancy, great processing power and high amount of RAM to handle all the data it's pulling in real time.

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

include and require functions require file path, but you are giving file URI instead. The parameter should not be the one that includes http/https.

Your code should be something like:

include ("folder/file.php");

Use space as a delimiter with cut command

cut -d ' ' -f 2

Where 2 is the field number of the space-delimited field you want.

How do I create a list of random numbers without duplicates?

In order to obtain a program that generates a list of random values without duplicates that is deterministic, efficient and built with basic programming constructs consider the function extractSamples defined below,

def extractSamples(populationSize, sampleSize, intervalLst) :
    import random
    if (sampleSize > populationSize) :
        raise ValueError("sampleSize = "+str(sampleSize) +" > populationSize (= " + str(populationSize) + ")")
    samples = []
    while (len(samples) < sampleSize) :
        i = random.randint(0, (len(intervalLst)-1))
        (a,b) = intervalLst[i]
        sample = random.randint(a,b)
        if (a==b) :
            intervalLst.pop(i)
        elif (a == sample) : # shorten beginning of interval                                                                                                                                           
            intervalLst[i] = (sample+1, b)
        elif ( sample == b) : # shorten interval end                                                                                                                                                   
            intervalLst[i] = (a, sample - 1)
        else :
            intervalLst[i] = (a, sample - 1)
            intervalLst.append((sample+1, b))
        samples.append(sample)
    return samples

The basic idea is to keep track of intervals intervalLst for possible values from which to select our required elements from. This is deterministic in the sense that we are guaranteed to generate a sample within a fixed number of steps (solely dependent on populationSize and sampleSize).

To use the above function to generate our required list,

In [3]: populationSize, sampleSize = 10**17, 10**5

In [4]: %time lst1 = extractSamples(populationSize, sampleSize, [(0, populationSize-1)])
CPU times: user 289 ms, sys: 9.96 ms, total: 299 ms
Wall time: 293 ms

We may also compare with an earlier solution (for a lower value of populationSize)

In [5]: populationSize, sampleSize = 10**8, 10**5

In [6]: %time lst = random.sample(range(populationSize), sampleSize)
CPU times: user 1.89 s, sys: 299 ms, total: 2.19 s
Wall time: 2.18 s

In [7]: %time lst1 = extractSamples(populationSize, sampleSize, [(0, populationSize-1)])
CPU times: user 449 ms, sys: 8.92 ms, total: 458 ms
Wall time: 442 ms

Note that I reduced populationSize value as it produces Memory Error for higher values when using the random.sample solution (also mentioned in previous answers here and here). For above values, we can also observe that extractSamples outperforms the random.sample approach.

P.S. : Though the core approach is similar to my earlier answer, there are substantial modifications in implementation as well as approach alongwith improvement in clarity.

Edit a specific Line of a Text File in C#

the easiest way is :

static void lineChanger(string newText, string fileName, int line_to_edit)
{
     string[] arrLine = File.ReadAllLines(fileName);
     arrLine[line_to_edit - 1] = newText;
     File.WriteAllLines(fileName, arrLine);
}

usage :

lineChanger("new content for this line" , "sample.text" , 34);

Is a Java hashmap search really O(1)?

If the number of buckets (call it b) is held constant (the usual case), then lookup is actually O(n).
As n gets large, the number of elements in each bucket averages n/b. If collision resolution is done in one of the usual ways (linked list for example), then lookup is O(n/b) = O(n).

The O notation is about what happens when n gets larger and larger. It can be misleading when applied to certain algorithms, and hash tables are a case in point. We choose the number of buckets based on how many elements we're expecting to deal with. When n is about the same size as b, then lookup is roughly constant-time, but we can't call it O(1) because O is defined in terms of a limit as n ? 8.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Lodash - difference between .extend() / .assign() and .merge()

Lodash version 3.10.1

Methods compared

  • _.merge(object, [sources], [customizer], [thisArg])
  • _.assign(object, [sources], [customizer], [thisArg])
  • _.extend(object, [sources], [customizer], [thisArg])
  • _.defaults(object, [sources])
  • _.defaultsDeep(object, [sources])

Similarities

  • None of them work on arrays as you might expect
  • _.extend is an alias for _.assign, so they are identical
  • All of them seem to modify the target object (first argument)
  • All of them handle null the same

Differences

  • _.defaults and _.defaultsDeep processes the arguments in reverse order compared to the others (though the first argument is still the target object)
  • _.merge and _.defaultsDeep will merge child objects and the others will overwrite at the root level
  • Only _.assign and _.extend will overwrite a value with undefined

Tests

They all handle members at the root in similar ways.

_.assign      ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge       ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults    ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }

_.assign handles undefined but the others will skip it

_.assign      ({}, { a: 'a'  }, { a: undefined }) // => { a: undefined }
_.merge       ({}, { a: 'a'  }, { a: undefined }) // => { a: "a" }
_.defaults    ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }

They all handle null the same

_.assign      ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.merge       ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.defaults    ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }

But only _.merge and _.defaultsDeep will merge child objects

_.assign      ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge       ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults    ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}

And none of them will merge arrays it seems

_.assign      ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge       ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults    ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }

All modify the target object

a={a:'a'}; _.assign      (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge       (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults    (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }

None really work as expected on arrays

Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.

_.assign      ([], ['a'], ['bb']) // => [ "bb" ]
_.merge       ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults    ([], ['a'], ['bb']) // => [ "a"  ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a"  ]

_.assign      ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge       ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults    ([], ['a','b'], ['bb']) // => [ "a", "b"  ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b"  ]

$ is not a function - jQuery error

In my case I was using jquery on my typescript file:

import * as $ from "jquery";

But this line gives me back an Object $ and it does not allow to use as a function (I can not use $('my-selector')). It solves my problem this lines, I hope it could help anyone else:

import * as JQuery from "jquery";
const $ = JQuery.default;

Selecting distinct values from a JSON

First we can just run map() function to get the new array with the results of calling a provided function on every element in the varjson.DATA.

varjson.DATA.map(({name})=>name))

After getting the array of name from the varjson.DATA. We can convert it into a set that will discard all duplicate entries of array and apply spread operator to get a array of unique names:

[...new Set(varjson.DATA.map(({name})=>name))]

_x000D_
_x000D_
const varjson = {_x000D_
  "DATA": [{_x000D_
      "id": 11,_x000D_
      "name": "ajax",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 12,_x000D_
      "name": "javascript",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 13,_x000D_
      "name": "jquery",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 14,_x000D_
      "name": "ajax",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 15,_x000D_
      "name": "jquery",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 16,_x000D_
      "name": "ajax",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    },_x000D_
    {_x000D_
      "id": 20,_x000D_
      "name": "ajax",_x000D_
      "subject": "OR",_x000D_
      "mark": 63_x000D_
    }_x000D_
  ],_x000D_
  "COUNT": "120"_x000D_
}_x000D_
_x000D_
console.log( [...new Set(varjson.DATA.map(({name})=>name))]);
_x000D_
_x000D_
_x000D_

Authenticate with GitHub using a token

For those coming from GitLab what's worked for me:

Step 1.

add remote

git remote add origin https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Step 2.

pull once

https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

now you are able to read/write to/from repository

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

How to access iOS simulator camera

Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.

How to make a smaller RatingBar?

How to glue the code given here ...

Step-1. You need your own rating stars in res/drawable ...

A full star

Empty star

Step-2 In res/drawable you need ratingstars.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/secondaryProgress"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/progress"
          android:drawable="@drawable/star" />
</layer-list>

Step-3 In res/values you need styles.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="foodRatingBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/ratingstars</item>
        <item name="android:minHeight">22dip</item>
        <item name="android:maxHeight">22dip</item>
    </style>
</resources>

Step-4 In your layout ...

<RatingBar 
      android:id="@+id/rtbProductRating"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:numStars="5"
      android:rating="3.5"
      android:isIndicator="false"
      style="@style/foodRatingBar"    
/>  

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Just put the

Response.End();

within a finally block instead of within the try block.

This has worked for me!!!.

I had the following problematic (with the Exception) code structure

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

The following works OK:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Set QLineEdit to accept only numbers

The best is QSpinBox.

And for a double value use QDoubleSpinBox.

QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));

Margin between items in recycler view Android

I made a class to manage this issue. This class set different margins for the items inside the recyclerView: only the first row will have a top margin and only the first column will have left margin.

public class RecyclerViewMargin extends RecyclerView.ItemDecoration {
private final int columns;
private int margin;

/**
 * constructor
 * @param margin desirable margin size in px between the views in the recyclerView
 * @param columns number of columns of the RecyclerView
 */
public RecyclerViewMargin(@IntRange(from=0)int margin ,@IntRange(from=0) int columns ) {
    this.margin = margin;
    this.columns=columns;

}

/**
 * Set different margins for the items inside the recyclerView: no top margin for the first row
 * and no left margin for the first column.
 */
@Override
public void getItemOffsets(Rect outRect, View view,
                           RecyclerView parent, RecyclerView.State state) {

    int position = parent.getChildLayoutPosition(view);
    //set right margin to all
    outRect.right = margin;
    //set bottom margin to all
    outRect.bottom = margin;
    //we only add top margin to the first row
    if (position <columns) {
        outRect.top = margin;
    }
    //add left margin only to the first column
    if(position%columns==0){
        outRect.left = margin;
        }
    }
}

you can set it in your recyclerview this way

 RecyclerViewMargin decoration = new RecyclerViewMargin(itemMargin, numColumns);
 recyclerView.addItemDecoration(decoration);

How to convert a DataTable to a string in C#?

Or, change the app to WinForms, use grid and bind DataTable to grid. If it is a demo/sample app.

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

console.log not working in Angular2 Component (Typescript)

It's not working because console.log() it's not in a "executable area" of the class "App".

A class is a structure composed by attributes and methods.

The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

_x000D_
_x000D_
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
 s: string = "Hello2";_x000D_
            _x000D_
  constructor() {_x000D_
    console.log(this.s)            _x000D_
  }            _x000D_
}
_x000D_
_x000D_
_x000D_

Think of class like a plain javascript object.

Would it make sense to expect this to work?

_x000D_
_x000D_
class:  {_x000D_
  s: string,_x000D_
  console.log(s)_x000D_
 }
_x000D_
_x000D_
_x000D_

If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

https://www.typescriptlang.org/play/index.html

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

This can also depend on the way you are invoking the SP from your C# code. If the SP returns some table type value then invoke the SP with ExecuteStoreQuery, and if the SP doesn't returns any value invoke the SP with ExecuteStoreCommand

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Return value in SQL Server stored procedure

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)

IF @AA> 0
    BEGIN
        SET @UserId = 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

allowing only alphabets in text box using java script

From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/

HTML

      <form name="f" onsubmit="return onlyAlphabets()">
         <input type="text" name="nm">
         <div id="notification"></div>
         <input type="submit">
      </form>

javascript

  function onlyAlphabets() {

  var regex = /^[a-zA-Z]*$/;
  if (regex.test(document.f.nm.value)) {

      //document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
      return true;
  } else {
      document.getElementById("notification").innerHTML = "Alphabets Only";
      return false;
  }


}

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

How to get the integer value of day of week

Use

day1 = (int)ClockInfoFromSystem.DayOfWeek;

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

Search for value in DataGridView in a column

Filter the data directly from DataTable or Dataset:

"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
   this.dataGridView1.DataSource = "MyTable".DefaultView;

Use this code on event KeyUp of Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

This is an old question but I didn't find the fix I used, so I've added it here.

In my case it was a namespace with the same name as a class in the parent namespace.

To find this, I used the object browser and searched for the name of the item that was already defined.

If it won't let you do this while you still have the error then temporarily change the name of the item it is complaining about and then find the offending item.

Difference between numpy.array shape (R, 1) and (R,)

The shape is a tuple. If there is only 1 dimension the shape will be one number and just blank after a comma. For 2+ dimensions, there will be a number after all the commas.

# 1 dimension with 2 elements, shape = (2,). 
# Note there's nothing after the comma.
z=np.array([  # start dimension
    10,       # not a dimension
    20        # not a dimension
])            # end dimension
print(z.shape)

(2,)

# 2 dimensions, each with 1 element, shape = (2,1)
w=np.array([  # start outer dimension 
    [10],     # element is in an inner dimension
    [20]      # element is in an inner dimension
])            # end outer dimension
print(w.shape)

(2,1)

What is the difference between GitHub and gist?

GitHub Gists

To gist or not to gist. That is the $64 question ...

GitHub Gists are Single ( or, multiple ) Simple Markdown Files with repo-like qualities that can be forked or cloned ( if public ).

Otherwise, not if private.

Kinda like a fancy scratch pad that can be shared.

Similar to this comment scratch pad that I am typing on now, but a bit more elaborate.

Whereas, an official, full GitHub repo is a full blown repository of source code src, supporting documents ( markdown or html, or both ) docs or root, images png, ico, svg, and a config.sys file for running Yaml variables hosted on a Jekyll server.

Does a simple Gist file support Yaml front matter?

Me thinks not.

From the official GitHub Gist documentation ...

The gist editor is powered by CodeMirror.

However, you can copy a public Gist ( or, a private Gist if the owner has granted you access via a link to the private Gist ) ...

And, you can then embed that public Gist into an "official" repo page.md using Visual Studio Code, as follows:

"You can embed a gist in any text field that supports Javascript, such as a blog post."

"To get the embed code, click the clipboard icon next to the Embed URL button of a gist."

Now, that's a cool feature.

Makes me want to search ( discover ) other peoples' gists, or OPG and incorporate their "public" work into my full-blown working repos.

"You can discover the PUBLIC gists others have created by going to the gist home page and clicking on the link ...

All Gists{:title='Click to Review the Discover Feature at GitHub Gists'}{:target='_blank'}."

Caveat. No support for Liquid tags at GitHub Gist.

I suppose if I do find something beneficial, I can always ping-back, or cite that source if I do use the work in my full-blown working repos.

Where is the implicit license posted for all gists made public by their authors?

Robert

P.S. This is a good comment. I think I will turn this into a gist and make it publically searchable over at GitHub Gists.

Note. When embedding the <script></script> html tag within the body of a Markdown (.md) file, you may get a warning "MD033" from your linter.

This should not, however, affect the rendering of the data ( src ) called from within the script tag.

To change the default warning flag to accommodate the called contents of a script tag from within Visual Studio Code, add an entry to the Markdownlint Configuration Object within the User Settings Json file, as follows:

// Begin Markdownlint Configuration Object
"markdownlint.config": {
  "MD013": false,
  "MD033": {"allowed_elements": ["script"]}
}// End Markdownlint Configuration Object

Note. Solution derived from GitHub Commit by David Anson

How to compress an image via Javascript in the browser?

Edit: As per the Mr Me comment on this answer, it looks like compression is now available for JPG/WebP formats ( see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL ).

As far as I know, you cannot compress images using canvas, instead, you can resize it. Using canvas.toDataURL will not let you choose the compression ratio to use. You can take a look at canimage that does exactly what you want : https://github.com/nfroidure/CanImage/blob/master/chrome/canimage/content/canimage.js

In fact, it's often sufficient to just resize the image to decrease it's size but if you want to go further, you'll have to use newly introduced method file.readAsArrayBuffer to get a buffer containing the image data.

Then, just use a DataView to read it's content according to the image format specification (http://en.wikipedia.org/wiki/JPEG or http://en.wikipedia.org/wiki/Portable_Network_Graphics).

It'll be hard to deal with image data compression, but it is worse a try. On the other hand, you can try to delete the PNG headers or the JPEG exif data to make your image smaller, it should be easier to do so.

You'll have to create another DataWiew on another buffer and fill it with the filtered image content. Then, you'll just have to encode you're image content to DataURI using window.btoa.

Let me know if you implement something similar, will be interesting to go through the code.

Extract file name from path, no matter what the os/path format

The Windows separator can be in a Unix filename or Windows Path. The Unix separator can only exist in the Unix path. The presence of a Unix separator indicates a non-Windows path.

The following will strip (cut trailing separator) by the OS specific separator, then split and return the rightmost value. It's ugly, but simple based on the assumption above. If the assumption is incorrect, please update and I will update this response to match the more accurate conditions.

a.rstrip("\\\\" if a.count("/") == 0 else '/').split("\\\\" if a.count("/") == 0 else '/')[-1]

sample code:

b = ['a/b/c/','a/b/c','\\a\\b\\c','\\a\\b\\c\\','a\\b\\c','a/b/../../a/b/c/','a/b/../../a/b/c']

for a in b:

    print (a, a.rstrip("\\" if a.count("/") == 0 else '/').split("\\" if a.count("/") == 0 else '/')[-1])

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

How to access a property of an object (stdClass Object) member/element of an array?

You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array

$object = array_shift($array);
var_dump($object->id);

Or refer to the thing by its index in the array.

var_dump( $array[0]->id );

Or, if you're not sure how many things are in the array, loop over the array

foreach($array as $key=>$value)
{
    var_dump($value->id);
    var_dump($array[$key]->id);
}

How do you format a Date/Time in TypeScript?

  1. You can create pipe inherited from PipeTransform base
  2. Then implement transform method

Used in Angular 4 - it's working. Best way to format a date is a pipe.

Create your custom pipe like this:

import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormat'
  })
  export class DateFormatPipe extends DatePipe implements PipeTransform {
    transform(value: any, args?: any): any {
       ///MMM/dd/yyyy 
       return super.transform(value, "MMM/dd/yyyy");
    }
  }

and it's used in a TypeScript class like this:

////my class////

export class MyComponent
{
  constructor(private _dateFormatPipe:DateFormatPipe)
  {
  }

  formatHereDate()
  {
     let myDate = this._dateFormatPipe.transform(new Date())//formatting current ///date here 
     //you can pass any date type variable 
  }
}

Node.js: Difference between req.query[] and req.params

You should be able to access the query using dot notation now.

If you want to access say you are receiving a GET request at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX and you want to fetch out the query used.

var type = req.query.type,
    email = req.query.email,
    utm = {
     source: req.query.utm_source,
     campaign: req.query.utm_campaign
    };

Params are used for the self defined parameter for receiving request, something like (example):

router.get('/:userID/food/edit/:foodID', function(req, res){
 //sample GET request at '/xavg234/food/edit/jb3552'

 var userToFind = req.params.userID;//gets xavg234
 var foodToSearch = req.params.foodID;//gets jb3552
 User.findOne({'userid':userToFind}) //dummy code
     .then(function(user){...})
     .catch(function(err){console.log(err)});
});

Convert dictionary values into array

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

Undo a Git merge that hasn't been pushed yet

I think you can do git rebase -i [hash] [branch_name] where [hash] is the identifying hash for however far back you want to rewind plus one (or however many commits back you want to go) and then delete the lines for the commits in the editor that you don't want any more. Save the file. Exit. Pray. And it should be rewound. You might have to do a git reset --hard, but it should be good at this point. You can also use this to pull specific commits out of a stack, if you don't want to keep them in your history, but that can leave your repository in a state that you probably don't want.

Convert a character digit to the corresponding integer in C

If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.

If you want to convert larger numbers then the following will do:

char *string = "24";

int value;

int assigned = sscanf(string, "%d", &value);

** don't forget to check the status (which should be 1 if it worked in the above case).

Paul.

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Remove rows with all or some NAs (missing values) in data.frame

For your first question, I have a code that I am comfortable with to get rid of all NAs. Thanks for @Gregor to make it simpler.

final[!(rowSums(is.na(final))),]

For the second question, the code is just an alternation from the previous solution.

final[as.logical((rowSums(is.na(final))-5)),]

Notice the -5 is the number of columns in your data. This will eliminate rows with all NAs, since the rowSums adds up to 5 and they become zeroes after subtraction. This time, as.logical is necessary.

The module was expected to contain an assembly manifest

I got the error in the following case:

  1. A .NET EXE file (#1) was referencing another .NET EXE file (#2)
  2. I was trying to obfuscate EXE #2 with Themida
  3. when running the EXE #1 it was crashing with the error "The module was expected to contain an assembly manifest"

I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

Free to try with a nagging banner... DevExpress XtraReports and XRCharts. Very nice dev tool, great support, speaking from experience.

CSS to make table 100% of max-width

Like this

demo

css

table{
    width:100%;
}

MySQL 'Order By' - sorting alphanumeric correctly

I had some good results with

SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC

Array inside a JavaScript Object?

_x000D_
_x000D_
var data = {_x000D_
  name: "Ankit",_x000D_
  age: 24,_x000D_
  workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]_x000D_
};_x000D_
_x000D_
for (const key in data) {_x000D_
  if (data.hasOwnProperty(key)) {_x000D_
    const element = data[key];_x000D_
      console.log(key+": ", element);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size for Android Studio processes, such as the core IDE, Gradle daemon, and Kotlin daemon.

If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust the heap sizes for your project manually. To do so, follow these steps:

Click File > Settings from the menu bar (or Android Studio > Preferences on macOS). Click Appearance & Behavior > System Settings > Memory Settings.

For more Info click

https://developer.android.com/studio/intro/studio-config

enter image description here

How to get absolute path to file in /resources folder of your project

Create the classLoader instance of the class you need, then you can access the files or resources easily. now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);

Simplest Way to Test ODBC on WIndows

For ad hoc queries, the ODBC Test utility is pretty handy. Its design and interface is more oriented toward testing various parts of the ODBC API. But it works quite nicely for running queries and showing the output. It is part of the Microsoft Data Access Components.

To run a query, you can click the connect button (or use ctrl-F), choose a data source, type a query, then ctrl-E to execute it and ctrl-R to display the results (e.g., if it is a SELECT or something that returns a cursor).

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

Rails: How do I create a default value for attributes in Rails activerecord's model?

For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.

For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).

Rather, you want to set the attribute in a before_validation on: create, like so:

before_validation :set_status_because_rails_cannot, on: :create

def set_status_because_rails_cannot
  self.status ||= 'P'
end

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

This is happening because of the CORS error. CORS stands for Cross Origin Resource Sharing. In simple words, this error occurs when we try to access a domain/resource from another domain.

Read More about it here: CORS error with jquery

To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.

How to get a cross-origin resource sharing (CORS) post request working

These links may help

How to call a stored procedure from Java and JPA

I am deploying my web application in Jboss AS. Should I use JPA to access the stored procedure or CallableStatement. Any advantage of using JPA in this case.

It is not really supported by JPA but it's doable. Still I wouldn't go this way:

  • using JPA just to map the result of a stored procedure call in some beans is really overkill,
  • especially given that JPA is not really appropriate to call stored procedure (the syntax will be pretty verbose).

I would thus rather consider using Spring support for JDBC data access, or a data mapper like MyBatis or, given the simplicity of your application, raw JDBC and CallableStatement. Actually, JDBC would probably be my choice. Here is a basic kickoff example:

CallableStatement cstmt = con.prepareCall("{call getEmployeeDetails(?, ?)}");
cstmt.setInt("employeeId", 123);
cstmt.setInt("companyId", 456);
ResultSet rs = cstmt.executeQuery();

Reference

Generate random string/characters in JavaScript

If you want just A-Z:

randomAZ(n: number): string {
      return Array(n)
        .fill(null)
        .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
        .map(a => String.fromCharCode(a))
        .join('')
 }

if (boolean == false) vs. if (!boolean)

Note: With ConcurrentMap you can use the more efficient

values.putIfAbsent(NoteColumns.CREATED_DATE, now);

I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.

Navigation drawer: How do I set the selected item at startup?

Following code will only make menu item selected:

navigationView.setCheckedItem(id);

To select and open the menu item, add following code after the above line.

onNavigationItemSelected(navigationView.getMenu().getItem(0));

How to use a servlet filter in Java to change an incoming servlet request url?

  1. Implement javax.servlet.Filter.
  2. In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
  3. Use HttpServletRequest#getRequestURI() to grab the path.
  4. Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
  5. Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
  6. Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter annotation for that instead.

Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.

Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

How to append output to the end of a text file

I would use printf instead of echo because it's more reliable and processes formatting such as new line \n properly.

This example produces an output similar to echo in previous examples:

printf "hello world"  >> read.txt   
cat read.txt
hello world

However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent

printf "hello\nworld"  >> read.txt   
cat read.txt
hello
world

Accessing all items in the JToken

In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);

foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
    Console.WriteLine(sub_obj.Key);
}

I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).

I think the parsing works according to the following principles:

  • Every object is abstracted as a JToken

  • Cast to JObject where you expect a Dictionary

  • Cast to JValue if the JToken represents a terminal node and is a value

  • Cast to JArray if its an array

  • JValue.Value gives you the .NET type you need

Using member variable in lambda capture list inside a member function

Summary of the alternatives:

capture this:

auto lambda = [this](){};

use a local reference to the member:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

C++14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

example: https://godbolt.org/g/dEKVGD

How to change the style of alert box?

I use sweetalert2 library. It's really simple, a lot of customization, modern, animated windows, eye-catching, and also nice design.

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href>Why do I have this issue?</a>'
})

Check this link

How to install mod_ssl for Apache httpd?

Are any other LoadModule commands referencing modules in the /usr/lib/httpd/modules folder? If so, you should be fine just adding LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to your conf file.

Otherwise, you'll want to copy the mod_ssl.so file to whatever directory the other modules are being loaded from and reference it there.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

As mentioned by @leocaseiro on github issue.

I found 3 solutions for those who are looking for easy fixes.

1) Moving from ngAfterViewInit to ngAfterContentInit

2) Moving to ngAfterViewChecked combined with ChangeDetectorRef as suggested on #14748 (comment)

3) Keep with ngOnInit() but call ChangeDetectorRef.detectChanges() after your changes.

How to build & install GLFW 3 and use it in a Linux project

The well-described answer is already there, but I went through this SHORTER recipe:

  1. Install Linuxbrew
  2. $ brew install glfw
  3. cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
  4. sudo cp -R GLFW /usr/include

Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include).

How to format code in Xcode?

Select first the text you want to format and then press Ctrl+I.

Use Cmd+A first if you wish to format all text in the selected file.

Note: this procedure only re-indents the lines, it does not do any advanced formatting.


In XCode 12 beta:

The new key binding to re-indent is control+I.

Return datetime object of previous month

Try this:

def monthdelta(date, delta):
    m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
    if not m: m = 12
    d = min(date.day, [31,
        29 if y%4==0 and (not y%100==0 or y%400 == 0) else 28,
        31,30,31,30,31,31,30,31,30,31][m-1])
    return date.replace(day=d,month=m, year=y)

>>> for m in range(-12, 12):
    print(monthdelta(datetime.now(), m))

    
2009-08-06 16:12:27.823000
2009-09-06 16:12:27.855000
2009-10-06 16:12:27.870000
2009-11-06 16:12:27.870000
2009-12-06 16:12:27.870000
2010-01-06 16:12:27.870000
2010-02-06 16:12:27.870000
2010-03-06 16:12:27.886000
2010-04-06 16:12:27.886000
2010-05-06 16:12:27.886000
2010-06-06 16:12:27.886000
2010-07-06 16:12:27.886000
2010-08-06 16:12:27.901000
2010-09-06 16:12:27.901000
2010-10-06 16:12:27.901000
2010-11-06 16:12:27.901000
2010-12-06 16:12:27.901000
2011-01-06 16:12:27.917000
2011-02-06 16:12:27.917000
2011-03-06 16:12:27.917000
2011-04-06 16:12:27.917000
2011-05-06 16:12:27.917000
2011-06-06 16:12:27.933000
2011-07-06 16:12:27.933000
>>> monthdelta(datetime(2010,3,30), -1)
datetime.datetime(2010, 2, 28, 0, 0)
>>> monthdelta(datetime(2008,3,30), -1)
datetime.datetime(2008, 2, 29, 0, 0)

Edit Corrected to handle the day as well.

Edit See also the answer from puzzlement which points out a simpler calculation for d:

d = min(date.day, calendar.monthrange(y, m)[1])

How to catch a specific SqlException error?

You can evaluate based on severity type. Note to use this you must be subscribed to OnInfoMessage

conn.InfoMessage += OnInfoMessage;
conn.FireInfoMessageEventOnUserErrors = true;

Then your OnInfoMessage would contain:

foreach(SqlError err in e.Errors) {
//Informational Errors
if (Between(Convert.ToInt16(err.Class), 0, 10, true)) {
    logger.Info(err.Message);
//Errors users can correct.
} else if (Between(Convert.ToInt16(err.Class), 11, 16, true)) {
    logger.Error(err.Message);
//Errors SysAdmin can correct.
} else if (Between(Convert.ToInt16(err.Class), 17, 19, true)) {
    logger.Error(err.Message);
//Fatal Errors 20+
} else {
    logger.Fatal(err.Message);
}}

This way you can evaluate on severity rather than on error number and be more effective. You can find more information on severity here.

private static bool Between( int num, int lower, int upper, bool inclusive = false )
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

Sending mail attachment using Java

This worked for me.

Here I assume my attachment is of a PDF type format.

Comments are made to understand it clearly.

public class MailAttachmentTester {
    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
        String to = "[email protected]";
        // Sender's email ID needs to be mentioned
        String from = "[email protected]";
        final String username = "[email protected]";//change accordingly
        final String password = "test";//change accordingly
        // Assuming you are sending email through relay.jangosmtp.net
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        // Get the Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        try {
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);
            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));
            // Set To: header field of the header.
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            // Set Subject: header field
            message.setSubject("Attachment");
            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();
            // Now set the actual message
            messageBodyPart.setText("Please find the attachment below");
            // Create a multipar message
            Multipart multipart = new MimeMultipart();
            // Set text message part
            multipart.addBodyPart(messageBodyPart);
            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            String filename = "D:/test.PDF";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            // Send the complete message parts
            message.setContent(multipart);
            // Send message
            Transport.send(message);
            System.out.println("Email Sent Successfully !!");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

} 

Table and Index size in SQL Server

This query comes from two other answers:

Get size of all tables in database

How to find largest objects in a SQL Server database?

, but I enhanced this to be universal. It uses sys.objects dictionary:

SELECT 
    s.NAME as SCHEMA_NAME,
    t.NAME AS OBJ_NAME,
    t.type_desc as OBJ_TYPE,
    i.name as indexName,
    sum(p.rows) as RowCounts,
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.objects t
INNER JOIN
    sys.schemas s ON t.SCHEMA_ID = s.SCHEMA_ID 
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%' AND
    i.OBJECT_ID > 255 AND   
    i.index_id <= 1
GROUP BY 
    s.NAME, t.NAME, t.type_desc, i.object_id, i.index_id, i.name 
ORDER BY
    sum(a.total_pages) DESC
;

Error message "No exports were found that match the constraint contract name"

Clearing the folders didn't work for me. So I went to 'Programs and Features' and used the change button to startup the Visual Studio 2013 setup.

In the setup I choose the repair function and that fixed the problem for me.

JVM heap parameters

To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

?: operator (the 'Elvis operator') in PHP

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

Java 8 LocalDate Jackson format

@JsonSerialize and @JsonDeserialize worked fine for me. They eliminate the need to import the additional jsr310 module:

@JsonDeserialize(using = LocalDateDeserializer.class)  
@JsonSerialize(using = LocalDateSerializer.class)  
private LocalDate dateOfBirth;

Deserializer:

public class LocalDateDeserializer extends StdDeserializer<LocalDate> {

    private static final long serialVersionUID = 1L;

    protected LocalDateDeserializer() {
        super(LocalDate.class);
    }


    @Override
    public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        return LocalDate.parse(jp.readValueAs(String.class));
    }

}

Serializer:

public class LocalDateSerializer extends StdSerializer<LocalDate> {

    private static final long serialVersionUID = 1L;

    public LocalDateSerializer(){
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException {
        gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}

Where to find extensions installed folder for Google Chrome on Mac?

For Mac EI caption/Mac Sierra, Chrome extension folders were located at

/Users/$USER/Library/Application\ Support/Google/Chrome/Profile*/Extensions/

Jquery to change form action

For variety's sake:

var actions = {input1: "action1.php", input2: "action2.php"};
$("#input1, #input2").click(function() {
    $(this).closest("form").attr("action", actions[this.id]);
});

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

What integer hash function are good that accepts an integer hash key?

This page lists some simple hash functions that tend to decently in general, but any simple hash has pathological cases where it doesn't work well.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

Only one thing needs to be done to solve the problem: upgrade TeamCity to version 8.1.x or higher because support for Visual Studio 2012/2013 and MSBuild Tools 2013 was only introduced in TeamCity 8.1. Once you've upgraded your TeamCity modify MSBuild Tools Version setting in your build step accordingly ans the problem will disappear. For more info read here: http://blog.turlov.com/2014/07/upgrade-teamcity-to-enable-support-for.html

Generate random int value from 3 to 6

Simply:

DECLARE @MIN INT=3; --We define minimum value, it can be generated.
DECLARE @MAX INT=6; --We define maximum value, it can be generated.

SELECT @MIN+FLOOR((@MAX-@MIN+1)*RAND(CONVERT(VARBINARY,NEWID()))); --And then this T-SQL snippet generates an integer between minimum and maximum integer values.

You can change and edit this code for your needs.

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

SQL update trigger only when column is modified

You have two way for your question :

1- Use Update Command in your Trigger.

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;
    IF UPDATE (QtyToRepair) 
    BEGIN
        UPDATE SCHEDULE 
        SET modified = GETDATE()
           , ModifiedUser = SUSER_NAME()
           , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S INNER JOIN Inserted I 
        ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END 
END

2- Use Join between Inserted table and deleted table

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;    

    UPDATE SCHEDULE 
    SET modified = GETDATE()
       , ModifiedUser = SUSER_NAME()
       , ModifiedHost = HOST_NAME()
    FROM SCHEDULE S 
    INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
    INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber                  
    WHERE S.QtyToRepair <> I.QtyToRepair
    AND D.QtyToRepair <> I.QtyToRepair
END

When you use update command for table SCHEDULE and Set QtyToRepair Column to new value, if new value equal to old value in one or multi row, solution 1 update all updated row in Schedule table but solution 2 update only schedule rows that old value not equal to new value.

Read MS Exchange email in C#

Um,

I might be a bit too late here but isn't this kinda the point to EWS ?

https://msdn.microsoft.com/en-us/library/dd633710(EXCHG.80).aspx

Takes about 6 lines of code to get the mail from a mailbox:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

//service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );

service.AutodiscoverUrl( "[email protected]" );

FindItemsResults<Item> findResults = service.FindItems(
   WellKnownFolderName.Inbox,
   new ItemView( 10 ) 
);

foreach ( Item item in findResults.Items )
{
   Console.WriteLine( item.Subject );
}

How to add google-services.json in Android?

  1. Download the "google-service.json" file from Firebase
  2. Go to this address in windows explorer "C:\Users\Your-Username\AndroidStudioProjects" You will see a list of your Android Studio projects
  3. Open a desired project, navigate to "app" folder and paste the .json file
  4. Go to Android Studio and click on "Sync with file system", located in dropdown menu (File>Sync with file system)
  5. Now sync with Gradle and everything should be fine

Importing CSV data using PHP/MySQL

$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
    $import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
    mysql_query($import) or die(mysql_error());
}
$i=1;
}

How do I exit the Vim editor?

After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit.

You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!).

Rails DB Migration - How To Drop a Table?

Open you rails console

ActiveRecord::Base.connection.execute("drop table table_name")

Converting integer to digit list

you can use:

First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345

l = [ int(item) for item in str(value) ]

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Pandas/Python: Set value of one column based on value in another column

Note the tilda that reverses the selection. It uses pandas methods (i.e. is faster than if/else).

df.loc[(df['c1'] == 'Value'), 'c2'] = 10
df.loc[~(df['c1'] == 'Value'), 'c2'] = df['c3']

Chrome / Safari not filling 100% height of flex parent

I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.

I managed to get it to work by adding both the height and min-height properties to the CSS class.

The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: 100px;
  height: 100px;
}

Hope this helps!

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

My requirement was to keep the password in a config file in encrypted form and decrypt when the program runs. For this I used the jasypt library (jasypt-1.9.3.jar). This is a very good library and we can accomplish the task with just 4 lines of code.

First, after adding jar to my project I imported the below library.

import org.jasypt.util.text.AES256TextEncryptor;

Then I created the below method. I then called this method by passing the text which I need to encrypt in password parameter. Using aesEncryptor.encrypt method, I encrypted the password which is stored to the myEncryptedPassword variable.

public void EncryptPassword(String password)
{   
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String myEncryptedPassword = aesEncryptor.encrypt(password);
    System.out.println(myEncryptedPassword );       
}

You might have noticed the method setPassword method and the value mypassword is used in the above code. This is to make sure that no one can decrypt the password even if they use the encrypted password using the same library.

Now I can see the value in the myEncryptedPassword variable something like h9oJ4P5P8ToRy38wvK11PUQCBrT1oH/zbMWuMrbOlI0rfZrj+qSg6f/u0jctOs/ZUf9t3shiwnEt05/nq8bnag==. This is the encrypted password. Keep this value in the config file.

I then created the below method to decrypt the password to be used in my program. The value of passwordFromConfigFile is the encrypted text which I got from the EncryptPassword method. Note that you have to use the same password in the aesEncryptor.setPassword method that you used to encrypt the password.

public String DecryptPassword(String passwordFromConfigFile)
{           
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String decryptedPassword = aesEncryptor.decrypt(passwordFromConfigFile);
    return decryptedPassword;   
}

The variable decryptedPassword will now have the decrypted password value.

Location of my.cnf file on macOS

If you are using macOS Sierra and the file doesn't exists, run

mysql --help or mysql --help | grep my.cnf

to see the possible locations and loading/reading sequence of my.cnf for mysql then create my.cnf file in one of the suggested directories then add the following line

[mysqld] sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can sudo touch /{preferred-path}/my.cnf then edit the file to add sql mode by

sudo nano /{preferred-path}/my.cnf

Then restart mysql, voilaah you are good to go. happy coding

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

if you are using nvm node version manager, use this command to create a symlink:

sudo ln -s "$(which node)" /usr/bin/node
sudo ln -s "$(which npm)" /usr/bin/npm
  • The first command creates a symlink for node
  • The second command creates a symlink for npm

System.web.mvc missing

Just in case someone is a position where he get's the same error. In my case downgrading Microsoft.AspNet.Mvc and then upgrading it again helped. I had this problem after installing Glimpse and removing it. System.Web.Mvc was references wrong somehow, cleaning the solution or rebuilding it didin't worked in my case. Just give it try if none of the above answers works for you.

UIButton title text color

I created a custom class MyButton extended from UIButton. Then added this inside the Identity Inspector:

enter image description here

After this, change the button type to Custom:

enter image description here

Then you can set attributes like textColor and UIFont for your UIButton for the different states:

enter image description here

Then I also created two methods inside MyButton class which I have to call inside my code when I want a UIButton to be displayed as highlighted:

- (void)changeColorAsUnselection{
    [self setTitleColor:[UIColor colorFromHexString:acColorGreyDark] 
               forState:UIControlStateNormal & 
                        UIControlStateSelected & 
                        UIControlStateHighlighted];
}

- (void)changeColorAsSelection{
    [self setTitleColor:[UIColor colorFromHexString:acColorYellow] 
               forState:UIControlStateNormal & 
                        UIControlStateHighlighted & 
                        UIControlStateSelected];
}

You have to set the titleColor for normal, highlight and selected UIControlState because there can be more than one state at a time according to the documentation of UIControlState. If you don't create these methods, the UIButton will display selection or highlighting but they won't stay in the UIColor you setup inside the UIInterface Builder because they are just available for a short display of a selection, not for displaying selection itself.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).

All I had to do was to install tkinter through the Linux bash terminal using the following command:

sudo apt-get install python3-tk

instead of installing it with pip or directly in the virtual environment in Pycharm.

Javac is not found

  1. Go to my computer;
  2. Right click properties;
  3. Go to advanced system settings;
  4. Go to environment variables;
  5. In user variables for user click on new(top new button, not on system variables);
  6. Set variable name as: Path
  7. Set the value of that variable to: C:\Program Files\Java\jdk1.7.0_76\bin
  8. Click ok;
  9. Click ok;
  10. Click ok.

Now you're set. Type javac in cmd. All javac options will be displayed.

Regular Expression for password validation

Thanks Nicholas Carey. I was going to use regex first but what you wrote changed my mind. It is so much easier to maintain this way.

//You can set these from your custom service methods
int minLen = 8;
int minDigit 2;
int minSpChar 2;

Boolean ErrorFlag = false;
//Check for password length
if (model.NewPassword.Length < minLen)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must be at least " + minLen + " characters long.");
}

//Check for Digits and Special Characters
int digitCount = 0;
int splCharCount = 0;
foreach (char c in model.NewPassword)
{
    if (char.IsDigit(c)) digitCount++;
    if (Regex.IsMatch(c.ToString(), @"[!#$%&'()*+,-.:;<=>?@[\\\]{}^_`|~]")) splCharCount++;
}

if (digitCount < minDigit)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minDigit + " digit(s).");
}
if (splCharCount < minSpChar)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minSpChar + " special character(s).");
}

if (ErrorFlag)
    return View(model);

What is the best way to concatenate two vectors?

Based on Kiril V. Lyadvinsky answer, I made a new version. This snippet use template and overloading. With it, you can write vector3 = vector1 + vector2 and vector4 += vector3. Hope it can help.

template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
    std::vector<T> AB;
    AB.reserve(A.size() + B.size());                // preallocate memory
    AB.insert(AB.end(), A.begin(), A.end());        // add A;
    AB.insert(AB.end(), B.begin(), B.end());        // add B;
    return AB;
}

template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
    A.reserve(A.size() + B.size());                // preallocate memory without erase original data
    A.insert(A.end(), B.begin(), B.end());         // add B;
    return A;                                        // here A could be named AB
}

How to determine when Fragment becomes visible in ViewPager

I used this and it worked !

mContext.getWindow().getDecorView().isShown() //boolean

Convert list to array in Java

Either:

Foo[] array = list.toArray(new Foo[0]);

or:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

Update:

It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

Clear ComboBox selected text

all depend on the configuration. for me works

comboBox.SelectedIndex = -1;

my configuration

DropDownStyle: DropDownList

(text can't be changed for the user)

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.

#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1

It's ok to have comment and blank lines before them.

Getting the parent div of element

Knowing the parent of an element is useful when you are trying to position them out the "real-flow" of elements.

Below given code will output the id of parent of element whose id is provided. Can be used for misalignment diagnosis.

<!-- Patch of code to find parent -->
<p id="demo">Click the button </p>
<button onclick="parentFinder()">Find Parent</button>
<script>
function parentFinder()
{
    var x=document.getElementById("demo"); 
    var y=document.getElementById("*id of Element you want to know parent of*");
    x.innerHTML=y.parentNode.id;
}
</script>
<!-- Patch ends -->

Android – Listen For Incoming SMS Messages

@Mike M. and I found an issue with the accepted answer (see our comments):

Basically, there is no point in going through the for loop if we are not concatenating the multipart message each time:

for (int i = 0; i < msgs.length; i++) {
    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
    msg_from = msgs[i].getOriginatingAddress();
    String msgBody = msgs[i].getMessageBody();
}

Notice that we just set msgBody to the string value of the respective part of the message no matter what index we are on, which makes the entire point of looping through the different parts of the SMS message useless, since it will just be set to the very last index value. Instead we should use +=, or as Mike noted, StringBuilder:

All in all, here is what my SMS receiving code looks like:

if (myBundle != null) {
    Object[] pdus = (Object[]) myBundle.get("pdus"); // pdus is key for SMS in bundle

    //Object [] pdus now contains array of bytes
    messages = new SmsMessage[pdus.length];
    for (int i = 0; i < messages.length; i++) {
         messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); //Returns one message, in array because multipart message due to sms max char
         Message += messages[i].getMessageBody(); // Using +=, because need to add multipart from before also
    }

    contactNumber = messages[0].getOriginatingAddress(); //This could also be inside the loop, but there is no need
}

Just putting this answer out there in case anyone else has the same confusion.

jQuery: Check if div with certain class name exists

Here is very sample solution for check class (hasClass) in Javascript:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
   // do something if 'hasClass' is exist.
}

Get size of folder or file

public long folderSize (String directory)
    {
        File curDir = new File(directory);
        long length = 0;
        for(File f : curDir.listFiles())
        {
            if(f.isDirectory())
            {               
                 for ( File child : f.listFiles()) 
                 {
                     length = length + child.length();
                 }

                System.out.println("Directory: " + f.getName() + " " + length + "kb");
            }
            else
            {
                length = f.length();
                System.out.println("File: " + f.getName() + " " + length + "kb");
            }
            length = 0;
        }
        return length;
    }

CASCADE DELETE just once

I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions. I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything. Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow. I call it like so: select delete_cascade('public','my_table','1');

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
 returns integer as $$
declare
    rx record;
    rd record;
    v_sql varchar;
    v_recursion_key varchar;
    recnum integer;
    v_primary_key varchar;
    v_rows integer;
begin
    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
            where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
        --raise notice '%',v_sql;
        --found a foreign key, now find the primary keys for any data that exists in any of those tables.
        for rd in execute v_sql
        loop
            v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
            if (v_recursion_key = any (p_recursion)) then
                --raise notice 'Avoiding infinite loop';
            else
                --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
                recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
            end if;
        end loop;
    end loop;
    begin
    --actually delete original record.
    v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
    execute v_sql;
    get diagnostics v_rows= row_count;
    --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
    recnum:= recnum +v_rows;
    exception when others then recnum=0;
    end;

    return recnum;
end;
$$
language PLPGSQL;

Read/Write String from/to a File in Android

Just a a bit modifications on reading string from a file method for more performance

private String readFromFile(Context context, String fileName) {
    if (context == null) {
        return null;
    }

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(fileName);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);               

            int size = inputStream.available();
            char[] buffer = new char[size];

            inputStreamReader.read(buffer);

            inputStream.close();
            ret = new String(buffer);
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

How to compile a 64-bit application using Visual C++ 2010 Express?

Note that Visual C++ compilers are removed when you upgrade Visual Studio 2010 Professional or Visual Studio 2010 Express to Visual Studio 2010 SP1 if Windows SDK v7.1 is installed.

For instructions on resolving this, see KB2519277 on the Microsoft Support site.

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

Laravel 5 How to switch from Production mode

Laravel 5 uses .env file to configure your app. .env should not be committed on your repository, like github or bitbucket. On your local environment your .env will look like the following:

# .env
APP_ENV=local

For your production server, you might have the following config:

# .env
APP_ENV=production

git switch branch without discarding local changes

You can either :

  • Use git stash to shelve your changes or,

  • Create another branch and commit your changes there, and then merge that branch into your working directory

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

How do I find the install time and date of Windows?

After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see this link ) I wanted a method without an additional utility. I settled on the creation date of "C:\System Volume Information" and it seemed to check out in various cases.

One-line of PowerShell to get it is:

([DateTime](Get-Item -Force 'C:\System Volume Information\').CreationTime).ToString('MM/dd/yyyy')

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

If you get this error while running the site in IIS 7+ on 64bit servers, you may have assemblies that are 32bit and your application pool will have the option "Enable 32-Bit Applications" set to False; Set this to true and restart the site to get it working.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

If you are in the shell of sf.net, try:

mysql --host=mysql-{LETTER} --user={LETTER}{GROUP ID}admin -p

Change {LETTER} and {GROUP ID} as shown in your MySQL Database of project admin profile.

How to start debug mode from command prompt for apache tomcat server?

These instructions worked for me on apache-tomcat-8.5.20 on mac os 10.13.3 using jdk1.8.0_152:

$ cd /path/to/apache-tomcat-8.5.20/bin
$ export JPDA_ADDRESS="localhost:12321"
$ ./catalina.sh jpda run

Now connect to port 12321 from IntelliJ/Eclipse and enjoy remote debugging.

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

And so I see from other answers that there are several ways of dealing with it. But I don't believe this. It has to be reduced into one way. I love IDE but, but if I follow the IDE steps provided from different answers I know this is not the fundamental algebra. My error looked like:

* What went wrong:
Execution failed for task ':compileJava'.
> Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

And the way to solve it scientifically is:

vi build.gradle

To change from:

java {
    sourceCompatibility = JavaVersion.toVersion('11')
    targetCompatibility = JavaVersion.toVersion('11')
}

to become:

java {
    sourceCompatibility = JavaVersion.toVersion('8')
    targetCompatibility = JavaVersion.toVersion('8')
}

The scientific method is that method that is open for argumentation and deals on common denominators.

TCP: can two different sockets share a port?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Vertically align text to top within a UILabel

There are two ways to fix this problem.One is

[mylabel setNumberOfLines:0];
[mylabel sizeToFit];

But the second way is more reliable for this approach, i.e,

 CGSize sizeToFit = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
 [mylabel setFrame:CGRectMake(mylabel.frame.origin.x, mylabel.frame.origin.y, sizeToFit.width, sizeToFit.height)];

entering "\n" is not such a good thing but yes if you know the constraints and the size of the data going to be displayed, may be it work good but cannot be expandable if text is longer than size of the label. The Second way ultimately set the frame according to the size of the text going to be displayed.

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

Download files from SFTP with SSH.NET library

While the example works, its not the correct way to handle the streams...

You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

       public void DownloadAll()
    {
        string host = @"sftp.domain.com";
        string username = "myusername";
        string password = "mypassword";

        string remoteDirectory = "/RemotePath/";
        string localDirectory = @"C:\LocalDriveFolder\Downloaded\";

        using (var sftp = new SftpClient(host, username, password))
        {
            sftp.Connect();
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                string remoteFileName = file.Name;
                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))

                    using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                    { 
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
            }

        }
    }

CSS width of a <span> tag

I would use the padding attribute. This will allow you add a set number of pixels to either side of the element without the element loosing its span qualities:

  • It won't become a block
  • It will float as you expect

This method will only add to the padding however, so if you change the length of the content (from Categories to Tags, for example) the size of the content will change and the overall size of the element will change as well. But if you really want to set a rigid size, you should do as mentioned above and use a div.

See the box model for more details about the box model, content, padding, margin, etc.

Not able to access adb in OS X through Terminal, "command not found"

Or the alternative solution could be

  1. Make sure you already install for android SDK. Usually it is located under /Users/your-user-name/Library/Android/sdk
  2. If the SDK is there then run this command. ./platform-tools/adb install your-apk-location

  3. From there you can generate the APK file That's the only sample to check if adb command is there

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

Print execution time of a shell command

Adding to @mob's answer:

Appending %N to date +%s gives us nanosecond accuracy:

start=`date +%s%N`;<command>;end=`date +%s%N`;echo `expr $end - $start`

Convert normal date to unix timestamp

var datestr = '2012.08.10';
var timestamp = (new Date(datestr.split(".").join("-")).getTime())/1000;

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

How to move certain commits to be based on another branch in git?

You can use git cherry-pick to just pick the commit that you want to copy over.

Probably the best way is to create the branch out of master, then in that branch use git cherry-pick on the 2 commits from quickfix2 that you want.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

In your Project open Global.asax.cs then right click on Method RouteConfig.RegisterRoutes(RouteTable.Routes); then click Go To Definition then at defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional} then change then Names of "Home" to your own controller Name and Index to your own View Name if you have changed the Names other then "HomeController" and "Index" Hope your Problem will be Solved.

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

C: How to free nodes in the linked list?

struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

C function that counts lines in file

Here is my function

char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);

void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
    ch = fgetc(myfile);
    if(ch == '\n')
        number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
    number_of_lines++;
fclose(myfile);
printf("number of lines in  %s   = %d",filename, number_of_lines);

}

Error in plot.new() : figure margins too large in R

I found this error today. Initially, I was trying to output it to a .jpeg file with low width and height.

jpeg("method1_test.jpg", width=900, height=900, res=40)

Later I increased the width and height to:

jpeg("method1_test.jpg", width=1900, height=1900, res=40)

The error was not there. :)

You can also play with the resolution, if the resolution is high, you need more width and height.

How do I pass JavaScript variables to PHP?

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

What is the difference between new/delete and malloc/free?

  • To use the malloc(), we need to include <stdlib.h> or <alloc.h> in the program which is not required for new.
  • new and delete can be overloaded but malloc can not.
  • Using the placement new, we can pass the address where we want to allocate memory but this is not possible in case of malloc.

how to run two commands in sudo?

I usually do:

sudo bash -c 'whoami; whoami'

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Listing only directories using ls in Bash?

Four (more) Reliable Options.

An unquoted asterisk * will be interpreted as a pattern (glob) by the shell. The shell will use it in pathname expansion. It will then generate a list of filenames that match the pattern.

A simple asterisk will match all filenames in the PWD (present working directory). A more complex pattern as */ will match all filenames that end in /. Thus, all directories. That is why the command:

1.- echo.

echo */
echo ./*/              ### Avoid misinterpreting filenames like "-e dir"

will be expanded (by the shell) to echo all directories in the PWD.


To test this: Create a directory (mkdir) named like test-dir, and cd into it:

mkdir test-dir; cd test-dir

Create some directories:

mkdir {cs,files,masters,draft,static}   # Safe directories.
mkdir {*,-,--,-v\ var,-h,-n,dir\ with\ spaces}  # Some a bit less secure.
touch -- 'file with spaces' '-a' '-l' 'filename'    # And some files:

The command echo ./*/ will remain reliable even with odd named files:

./--/ ./-/ ./*/ ./cs/ ./dir with spaces/ ./draft/ ./files/ ./-h/
./masters/ ./-n/ ./static/ ./-v var/

But the spaces in filenames make reading a bit confusing.


If instead of echo, we use ls. The shell is still what is expanding the list of filenames. The shell is the reason to get a list of directories in the PWD. The -d option to ls makes it list the present directory entry instead of the contents of each directory (as presented by default).

ls -d */

However, this command is (somewhat) less reliable. It will fail with the odd named files listed above. It will choke with several names. You need to erase one by one till you find the ones with problems.

2.- ls

The GNU ls will accept the "end of options" (--) key.

ls -d ./*/                     ### More reliable BSD ls
ls -d -- */                    ### More reliable GNU ls

3.-printf

To list each directory in its own line (in one column, similar to ls -1), use:

$ printf "%s\n" */        ### Correct even with "-", spaces or newlines.

And, even better, we could remove the trailing /:

$ set -- */; printf "%s\n" "${@%/}"        ### Correct with spaces and newlines.

An attempt like

$ for i in $(ls -d */); do echo ${i%%/}; done

will fail on:

  • some names (ls -d */) as already shown above.
  • will be affected by the value of IFS.
  • will split names on spaces and tabs (with default IFS).
  • each newline in the name will start a new echo command.

4.- Function

Finally, using the argument list inside a function will not affect the arguments list of the present running shell. Simply

$ listdirs(){ set -- */; printf "%s\n" "${@%/}"; }
$ listdirs

presents this list:

--
-
*
cs
dir with spaces
draft
files
-h
masters
-n
static
-v var

These options are safe with several types of odd filenames.

When to use a View instead of a Table?

Oh there are many differences you will need to consider

Views for selection:

  1. Views provide abstraction over tables. You can add/remove fields easily in a view without modifying your underlying schema
  2. Views can model complex joins easily.
  3. Views can hide database-specific stuff from you. E.g. if you need to do some checks using Oracles SYS_CONTEXT function or many other things
  4. You can easily manage your GRANTS directly on views, rather than the actual tables. It's easier to manage if you know a certain user may only access a view.
  5. Views can help you with backwards compatibility. You can change the underlying schema, but the views can hide those facts from a certain client.

Views for insertion/updates:

  1. You can handle security issues with views by using such functionality as Oracle's "WITH CHECK OPTION" clause directly in the view

Drawbacks

  1. You lose information about relations (primary keys, foreign keys)
  2. It's not obvious whether you will be able to insert/update a view, because the view hides its underlying joins from you

disable horizontal scroll on mobile web

This works for me across all mobile devices in both portrait and landscape modes.

<meta name="viewport" content="width=device-width, initial-scale = 0.86, maximum-scale=3.0, minimum-scale=0.86">

How do I resolve "Cannot find module" error using Node.js?

Remove your node_module root folder from your project(eg: myApp). Go to myApp folder and then type below command from terminal

>myApp>npm install

It will install all the dependency modules required for your project.

Eclipse java debugging: source not found

Well, here's what worked for me. I tried every possible solution on StackOverflow that there was. I tried changing my source location in the debug menu, I installed the m2e Eclipse plugin, I changed from embedded Maven, and I installed the run-jetty-run and nothing worked. Now, I will caveat that I was not trying to view an external person's source code, I just wanted to see my OWN code, but every time I "stepped in" to my methods that I wrote that were in MY project, I got the "Source now found" error.

After finally asking an expert, my issue was that the first thing Eclipse was doing was calling a ClassLoader, which you can see from the debug stack. All I had to do was F6 (step over) and then it took me back to my original call and then F5 (step in). And there was my code. Sigh...such a simple fix but an hour wasted.

Get the time difference between two datetimes

It is very simple with moment below code will return diffrence in hour from current time:

moment().diff('2021-02-17T14:03:55.811000Z', "h")

How to change default JRE for all Eclipse workspaces?

In eclipse go to

Window-> Java -> Installed JREs

You can remove your current installed jre and add the jdk by specifying the path to where the jdk is installed.

enter image description here

Five equal columns in twitter bootstrap

Create 5 elements with the class col-sm-2 and add to the first element also the class col-sm-offset-1

P.s. this will not be full width (it will be indented a little from the right and left of the screen)

The code should look something like this

<div class="col-sm-2 col-sm-offset-1"></div>
<div class="col-sm-2"></div>
<div class="col-sm-2"></div>
<div class="col-sm-2"></div>
<div class="col-sm-2"></div>

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.

The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.

How to print a percentage value in python?

Just to add Python 3 f-string solution

prob = 1.0/3.0
print(f"{prob:.0%}")

Converting from a string to boolean in Python?

you could always do something like

myString = "false"
val = (myString == "true")

the bit in parens would evaluate to False. This is just another way to do it without having to do an actual function call.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved.

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Export multiple classes in ES6 modules

For multiple classes in the same js file, extending Component from @wordpress/element, you can do that :

// classes.js
import { Component } from '@wordpress/element';

const Class1 = class extends Component {
}

const Class2 = class extends Component {
}

export { Class1, Class2 }

And import them in another js file :

import { Class1, Class2 } from './classes';