Programs & Examples On #Gitk

A graphical browser for the git distributed version control system which allows you to quickly manage branches, and search/review commit logs and diffs.

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

Install gitk on Mac

For Mojave users, I found this page very useful, particularly this suggestion:

/usr/bin/wish $(which gitk)

...without that, the window did not display correctly!

MySQL connection not working: 2002 No such file or directory

Make sure your local server (MAMP, XAMPP, WAMP, etc..) is running.

How to find the length of an array in shell?

$ a=(1 2 3 4)
$ echo ${#a[@]}
4

RegEx for matching UK Postcodes

Some of the regexs above are a little restrictive. Note the genuine postcode: "W1K 7AA" would fail given the rule "Position 3 - AEHMNPRTVXY only used" above as "K" would be disallowed.

the regex:

^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$

Seems a little more accurate, see the Wikipedia article entitled 'Postcodes in the United Kingdom'.

Note that this regex requires uppercase only characters.

The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC.

Slide right to left Android Animations

You can make your own animations. For example create xml file in res/anim like this

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/linear_interpolator">
    <translate
            android:fromXDelta="100%p"
            android:toXDelta="0"
            android:startOffset="0"
            android:duration="500"
            /> </set>

Then override animations in selected activity:

   overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);

How can I split a text file using PowerShell?

Here is my solution to split a file called patch6.txt (about 32,000 lines) into separate files of 1000 lines each. Its not quick, but it does the job.

$infile = "D:\Malcolm\Test\patch6.txt"
$path = "D:\Malcolm\Test\"
$lineCount = 1
$fileCount = 1

foreach ($computername in get-content $infile)
{
    write $computername | out-file -Append $path_$fileCount".txt"
    $lineCount++

    if ($lineCount -eq 1000)
    {
        $fileCount++
        $lineCount = 1
    }
}

How to check if a String is numeric in Java

You can use NumberFormat#parse:

try
{
     NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
    // Not a number.
}

Python time measure function

I don't see what the problem with the timeit module is. This is probably the simplest way to do it.

import timeit
timeit.timeit(a, number=1)

Its also possible to send arguments to the functions. All you need is to wrap your function up using decorators. More explanation here: http://www.pythoncentral.io/time-a-python-function/

The only case where you might be interested in writing your own timing statements is if you want to run a function only once and are also want to obtain its return value.

The advantage of using the timeit module is that it lets you repeat the number of executions. This might be necessary because other processes might interfere with your timing accuracy. So, you should run it multiple times and look at the lowest value.

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

Spring Data JPA find by embedded object property

The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

How to create an Oracle sequence starting with max value from a table?

Bear in mid, the MAX value will only be the maximum of committed values. It might return 1234, and you may need to consider that someone has already inserted 1235 but not committed.

How can I obfuscate (protect) JavaScript?

I am using Closure-Compiler utility for the java-script obfuscation. It minifies the code and has more options for obfuscation. This utility is available at Google code at below URL:
Closure Tools

But now a days I am hearing much of UglifyJS. You can find various comparison between Closure Compiler and UglifyJS in which Uglify seems to be a winner.
UglifyJS: A Fast New JavaScript Compressor For Node.js That’s On Par With Closure

Soon I would give chance to UglifyJS.

Why use a ReentrantLock if one can use synchronized(this)?

Lets assume this code is running in a thread:

private static ReentrantLock lock = new ReentrantLock();

void accessResource() {
    lock.lock();
    if( checkSomeCondition() ) {
        accessResource();
    }
    lock.unlock();
}

Because the thread owns the lock it will allow multiple calls to lock(), so it re-enter the lock. This can be achieved with a reference count so it doesn't has to acquire lock again.

rand() returns the same number each time the program is run

random functions like borland complier

using namespace std;

int sys_random(int min, int max) {
   return (rand() % (max - min+1) + min);
}

void sys_randomize() {
    srand(time(0));
}

What causes a TCP/IP reset (RST) flag to be sent?

One thing to be aware of is that many Linux netfilter firewalls are misconfigured.

If you have something like:

-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -p tcp -j REJECT --reject-with tcp-reset

then packet reordering can result in the firewall considering the packets invalid and thus generating resets which will then break otherwise healthy connections.

Reordering is particularly likely with a wireless network.

This should instead be:

-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -m state --state INVALID -j DROP

-A FORWARD -p tcp -j REJECT --reject-with tcp-reset

Basically anytime you have:

... -m state --state RELATED,ESTABLISHED -j ACCEPT

it should immediately be followed by:

... -m state --state INVALID -j DROP

It's better to drop a packet then to generate a potentially protocol disrupting tcp reset. Resets are better when they're provably the correct thing to send... since this eliminates timeouts. But if there's any chance they're invalid then they can cause this sort of pain.

UITableView, Separator color where to set?

Now you should be able to do it directly in the IB.

Not sure though, if this was available when the question was posted originally.

enter image description here

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Insert and set value with max()+1 problems

Use table alias in subquery:

INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES 
  ((SELECT MAX( customer_id ) FROM customers C) +1, 'jim', 'sock')

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

Accessing localhost of PC from USB connected Android mobile device

Google posted a solution for this kind of problem here.

The steps:

  • Connect your Android device and your development machine with USB debugging enabled
  • Open Chrome in your development machine, open new tab, right click in the new browser tab, click inspect
  • Click the three dots icon on right top side three dots, -> More Tools, Remote Devices.
  • Look at bottom of the screen, make sure your device name is appeared on the list with Green colored dot.
  • Look below at the settings part, check the Port forwarding mark
  • Add rule. Example, if your python web server is running on your machine localhost:5000 and you want to access it from your device port 3333, you type 3333 on the left part, and type localhost:5000, and click add rule.
  • Voila, now you can access your web server from your device. Try open new browser tab, and visit http://localhost:3333 from your device

Will iOS launch my app into the background if it was force-quit by the user?

This might help you

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

Source: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Truncate to three decimals in Python

Maybe this way:

def myTrunc(theNumber, theDigits):

    myDigits = 10 ** theDigits
    return (int(theNumber * myDigits) / myDigits)

Changing the space between each item in Bootstrap navbar

Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.

If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.

In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.

@media (min-width: 992px){
    .navbar li {
        margin-left : 1em;
        margin-right : 1em;
    }
}

You don't have permission to access / on this server

Check file permissions of the /var/www/html and the ALLOW directive in your apache conf

Make sure all files are readable by the webserver and the allow directive is like

 <Directory "/var/www/html">
    Order allow,deny
    Allow from all
  </Directory>

if you can see files then consider sorting the directive to be more restrictive

Python: Figure out local timezone

tzlocal from dateutil.

Code example follows. Last string suitable for use in filenames.

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> str(datetime.now(tzlocal()))
'2015-04-01 11:19:47.980883-07:00'
>>> str(datetime.now(tzlocal())).replace(' ','-').replace(':','').replace('.','-')
'2015-04-01-111947-981879-0700'
>>> 

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

How to modify PATH for Homebrew?

There are many ways to update your path. Jun1st answer works great. Another method is to augment your .bash_profile to have:

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

The line above places /usr/local/bin and /usr/local/sbin in front of your $PATH. Once you source your .bash_profile or start a new terminal you can verify your path by echo'ing it out.

$ echo $PATH
/usr/local/bin:/usr/local/sbin:/Users/<your account>/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

Once satisfied with the result running $ brew doctor again should no longer produce your error.

This blog post helped me out in resolving issues I ran into. http://moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

Document Root PHP

<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
    <br />
<a href="/hello.html">go to with html</a>

Try this yourself and find that they are not exactly the same.

$_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

HTML's / renders the root of the server url, in my case, localhost/

But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

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

Why do you need to put #!/bin/bash at the beginning of a script file?

The shebang is a directive to the loader to use the program which is specified after the #! as the interpreter for the file in question when you try to execute it. So, if you try to run a file called foo.sh which has #!/bin/bash at the top, the actual command that runs is /bin/bash foo.sh. This is a flexible way of using different interpreters for different programs. This is something implemented at the system level and the user level API is the shebang convention.

It's also worth knowing that the shebang is a magic number - a human readable one that identifies the file as a script for the given interpreter.

Your point about it "working" even without the shebang is only because the program in question is a shell script written for the same shell as the one you are using. For example, you could very well write a javascript file and then put a #! /usr/bin/js (or something similar) to have a javascript "Shell script".

Detect Safari using jQuery

    // Safari uses pre-calculated pixels, so use this feature to detect Safari
    var canva = document.createElement('canvas');
    var ctx = canva.getContext("2d");
    var img = ctx.getImageData(0, 0, 1, 1);
    var pix = img.data;     // byte array, rgba
    var isSafari = (pix[3] != 0);   // alpha in Safari is not zero

Placing/Overlapping(z-index) a view above another view in android

You can't use a LinearLayout for this, but you can use a FrameLayout. In a FrameLayout, the z-index is defined by the order in which the items are added, for example:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/my_drawable"
        android:scaleType="fitCenter"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:padding="5dp"
        android:text="My Label"
        />
</FrameLayout>

In this instance, the TextView would be drawn on top of the ImageView, along the bottom center of the image.

Build android release apk on Phonegap 3.x CLI

In PhoneGap 3.4.0 you can call:

cordova build android --release

If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:

key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp

Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.

How do you get the logical xor of two variables in Python?

We can easily find xor of two variables by the using:

def xor(a,b):
    return a !=b

Example:

xor(True,False) >>> True

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

How to stop Python closing immediately when executed in Microsoft Windows

If you just want a delay

from time import *

sleep(20)

What is the difference between Cygwin and MinGW?

As a simplification, it's like this:

  • Compile something in Cygwin and you are compiling it for Cygwin.

  • Compile something in MinGW and you are compiling it for Windows.

About Cygwin

The purpose of Cygwin is to make porting Unix-based applications to Windows much easier, by emulating many of the small details that Unix-based operating systems provide, and are documented by the POSIX standards. Your application can use Unix feature such as pipes, Unix-style file and directory access, and so forth, and it can be compiled with Cygwin which will act as a compatibility layer around your application, so that many of those Unix-specific paradigms can continue to be used.

When you distribute your software, the recipient will need to run it along with the Cygwin run-time environment (provided by the file cygwin1.dll). You may distribute this with your software, but your software will have to comply with its open source license. It may even be the case that even just linking your software with it, but distributing the dll separately, may still require you to honor the open source license.

About MinGW

MinGW aims to simply be a Windows port of the GNU compiler tools, such as GCC, Make, Bash, and so on. It does not attempt to emulate or provide comprehensive compatibility with Unix, but instead it provides the minimum necessary environment to use GCC (the GNU compiler) and a small number of other tools on Windows. It does not have a Unix emulation layer like Cygwin, but as a result your application needs to specifically be programmed to be able to run in Windows, which may mean significant alteration if it was created to rely on being run in a standard Unix environment and uses Unix-specific features such as those mentioned earlier. By default, code compiled in MinGW's GCC will compile to a native Windows X86 target, including .exe and .dll files, though you could also cross-compile with the right settings, since you are basically using the GNU compiler tools suite.

MinGW is essentially an alternative to the Microsoft Visual C++ compiler and its associated linking/make tools. It may be possible in some cases to use MinGW to compile something that was intended for compiling with Microsoft Visual C++, with the right libraries and in some cases with other modifications.

MinGW includes some basic standard libraries for interacting with the Windows operating system, but as with the normal standard libraries included in the GNU compiler collection these don't impose licensing restrictions on software you have created.

For non-trivial software applications, making them cross-platform can be a considerable challenge unless you use a comprehensive cross-platform framework. At the time I wrote this the Qt framework was one of the most popular for this purpose, allowing the building of graphical applications that work across operating systems including Windows, but there are other options too. If you use such a framework from the start, you can not only reduce your headaches when it comes time to port to another platform but you can use the same graphical widgets - windows, menus and controls - across all platforms if you're writing a GUI app, and have them appear native to the user.

How to format strings in Java

In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.

For example:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

Python's time.clock() vs. time.time() accuracy?

Short answer: use time.clock() for timing in Python.

On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.

time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.

How do I concatenate two text files in PowerShell?

Since most of the other replies often get the formatting wrong (due to the piping), the safest thing to do is as follows:

add-content $YourMasterFile -value (get-content $SomeAdditionalFile)

I know you wanted to avoid reading the content of $SomeAdditionalFile into a variable, but in order to save for example your newline formatting i do not think there is proper way to do it without.

A workaround would be to loop through your $SomeAdditionalFile line by line and piping that into your $YourMasterFile. However this is overly resource intensive.

Python ValueError: too many values to unpack

for k, m in self.materials.items():

example:

miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
    print("%s: %s" % (k, v))

Checking session if empty or not

Check if the session is empty or not in C# MVC Version Lower than 5.

if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
    //cast it and use it
    //business logic
}

Check if the session is empty or not in C# MVC Version Above 5.

if(Session["emp_num"] != null)
{
    //cast it and use it
    //business logic
}

What is the difference between join and merge in Pandas?

I always use join on indices:

import pandas as pd
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]}).set_index('key')
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]}).set_index('key')
left.join(right, lsuffix='_l', rsuffix='_r')

     val_l  val_r
key            
foo      1      4
bar      2      5

The same functionality can be had by using merge on the columns follows:

left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]})
left.merge(right, on=('key'), suffixes=('_l', '_r'))

   key  val_l  val_r
0  foo      1      4
1  bar      2      5

Does bootstrap 4 have a built in horizontal divider?

Bootstrap 4 define a CSS style for the HTML built-in horizontal divider <hr />, so just use it.

You can also customize margin with spacing utilities: mt for margin top, mb for margin bottom and my for margin top and bottom. The integer represent spacing 1 for small margin and 5 for huge margin. Here is an example:

<hr class="mt-2 mb-3"/>
<!-- OR -->
<hr class="my-3"/>
<!-- It's like -->
<hr class="mt-3 mb-3"/>

I used to be using just a div with border-top like:

<div class="border-top my-3"></div>

but it's a silly method to make the work done, and you can have some issues. So just use <hr />.

Interpreting "condition has length > 1" warning from `if` function

if statement is not vectorized. For vectorized if statements you should use ifelse. In your case it is sufficient to write

w <- function(a){
if (any(a>0)){
  a/sum(a)
}
  else 1
}

or a short vectorised version

ifelse(a > 0, a/sum(a), 1)

It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse gives output vector of length equal to length of a.

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

How to give a delay in loop execution using Qt

EDIT (removed wrong solution). EDIT (to add this other option):

Another way to use it would be subclass QThread since it has protected *sleep methods.

QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);

Here's the code to create your own *sleep method.

#include <QThread>    

class Sleeper : public QThread
{
public:
    static void usleep(unsigned long usecs){QThread::usleep(usecs);}
    static void msleep(unsigned long msecs){QThread::msleep(msecs);}
    static void sleep(unsigned long secs){QThread::sleep(secs);}
};

and you call it by doing this:

Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);

This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

CodeIgniter Select Query

Thats quite simple. For example, here is a random code of mine:

function news_get_by_id ( $news_id )
{

    $this->db->select('*');
    $this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human",  FALSE );
    $this->db->select("DATE_FORMAT( date, '%H:%i') as time_human",      FALSE );


    $this->db->from('news');

    $this->db->where('news_id', $news_id );


    $query = $this->db->get();

    if ( $query->num_rows() > 0 )
    {
        $row = $query->row_array();
        return $row;
    }

}   

This will return the "row" you selected as an array so you can access it like:

$array = news_get_by_id ( 1 );
echo $array['date_human'];

I also would strongly advise, not to chain the query like you do. Always have them separately like in my code, which is clearly a lot easier to read.

Please also note that if you specify the table name in from(), you call the get() function without a parameter.

If you did not understand, feel free to ask :)

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How can I check if a file exists in Perl?

if(-e $base_path){print "Something";}

would do the trick

Best way to concatenate List of String objects?

Rather than depending on ArrayList.toString() implementation, you could write a one-liner, if you are using java 8:

String result = sList.stream()
                     .reduce("", String::concat);

If you prefer using StringBuffer instead of String since String::concat has a runtime of O(n^2), you could convert every String to StringBuffer first.

StringBuffer result = sList.stream()
                           .map(StringBuffer::new)
                           .reduce(new StringBuffer(""), StringBuffer::append);

How to write dynamic variable in Ansible playbook

I am sure there is a smarter way for doing what you want but this should work:

- name         : Test var
  hosts        : all
  gather_facts : no
  vars:
    myvariable : false
  tasks:
    - name: param1
      set_fact:
        myvariable: "{{param1}}"
      when: param1 is defined

    - name: param2
      set_fact:
        myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
      when: param2 is defined

    - name: param3
      set_fact:
        myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
      when: param3 is defined

    - name: default
      set_fact:
        myvariable: "default"
      when: not myvariable

    - debug:
       var=myvariable

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

How to change collation of database, table, column?

I read it here, that you need to convert each table manually, it is not true. Here is a solution how to do it with a stored procedure:

DELIMITER $$

DROP PROCEDURE IF EXISTS changeCollation$$

-- character_set parameter could be 'utf8'
-- or 'latin1' or any other valid character set
CREATE PROCEDURE changeCollation(IN character_set VARCHAR(255))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_table_name varchar(255) DEFAULT "";
DECLARE v_message varchar(4000) DEFAULT "No records";

-- This will create a cursor that selects each table,
-- where the character set is not the one
-- that is defined in the parameter

DECLARE alter_cursor CURSOR FOR SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE()
AND COLLATION_NAME NOT LIKE CONCAT(character_set, '_%');

-- This handler will set the value v_finished to 1
-- if there are no more rows

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

OPEN alter_cursor;

-- Start a loop to fetch each rows from the cursor
get_table: LOOP

-- Fetch the table names one by one
FETCH alter_cursor INTO v_table_name;

-- If there is no more record, then we have to skip
-- the commands inside the loop
IF v_finished = 1 THEN
LEAVE get_table;
END IF;

IF v_table_name != '' THEN

IF v_message = 'No records' THEN
SET v_message = '';
END IF;

-- This technic makes the trick, it prepares a statement
-- that is based on the v_table_name parameter and it means
-- that this one is different by each iteration inside the loop

SET @s = CONCAT('ALTER TABLE ',v_table_name,
' CONVERT TO CHARACTER SET ', character_set);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET v_message = CONCAT('The table ', v_table_name ,
' was changed to the default collation of ', character_set,
'.\n', v_message);

SET v_table_name = '';

END IF;
-- Close the loop and the cursor
END LOOP get_table;
CLOSE alter_cursor;

-- Returns information about the altered tables or 'No records'
SELECT v_message;

END $$

DELIMITER ;

After the procedure is created call it simply:

CALL changeCollation('utf8');

For more details read this blog.

How to store file name in database, with other info while uploading image to server using PHP?

You have an ID for each photo so my suggestion is you rename the photo. For example you rename it by the date

<?php
 $date = getdate();
 $name .= $date[hours];
 $name .= $date[minutes];
 $name .= $date[seconds];
 $name .= $date[year];
 $name .= $date[mon];
 $name .= $date[mday];
?>

note: don't forget the file extension of your file or you can generate random string for the photo, but I would not recommend that. I would also recommend you to check the file extension before you upload it to your directory.

<?php 
if ((($_FILES["photo"]["type"] == "image/jpeg")
            || ($_FILES["photo"]["type"] == "image/pjpg"))
            && ($_FILES["photo"]["size"] < 100000000))
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"], $target.$name);

                if(mysql_query("your query"))
                {
                    //success handling
                }
                else 
                {
                    //failed handling
                }
            }
            else
            {
                //error handling
            }
?>

Hope this might help.

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How do I register a .NET DLL file in the GAC?

The above solutions look marvelous. However, to be simple, all you need I guess is to enter the assembly name along with its full path like:

gacutil -i C:\MyDlls\GacDeployedAssemblies\dllname.dll

Paying attention to C:\MyDlls\GacDeployedAssemblies

How do I prevent DIV tag starting a new line?

div is a block element, which always takes up its own line.

use the span tag instead

How do I move an existing Git submodule within a Git repository?

In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:

  1. Edit .gitmodules changing submodule name and path to be "ext/AFNetworking"
  2. Move submodule's git directory from ".git/modules/AFNetworking" to ".git/modules/ext/AFNetworking"
  3. Move library from "AFNetworking" to "ext/AFNetworking"
  4. Edit ".git/modules/ext/AFNetworking/config" and fix the [core] worktree line. Mine changed from ../../../AFNetworking to ../../../../ext/AFNetworking
  5. Edit "ext/AFNetworking/.git" and fix gitdir. Mine changed from ../.git/modules/AFNetworking to ../../git/modules/ext/AFNetworking
  6. git add .gitmodules
  7. git rm --cached AFNetworking
  8. git submodule add -f <url> ext/AFNetworking

Finally, I saw in the git status:

matt$ git status
# On branch ios-master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   .gitmodules
#   renamed:    AFNetworking -> ext/AFNetworking

Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)

<hr> tag in Twitter Bootstrap not functioning correctly?

I solved this by setting the HR background-color to black like so:

<hr style="width: 100%; color: black; height: 1px; background-color:black;" />

What is the shortcut to Auto import all in Android Studio?

These are the shortcuts used in Android studio

Go to class CTRL + N
Go to file CTRL + Shift + N
Navigate open tabs ALT + Left-Arrow; ALT + Right-Arrow
Look up recent files CTRL + E
Go to line CTRL + G
Navigate to last edit location CTRL + SHIFT + BACKSPACE
Go to declaration CTRL + B
Go to implementation CTRL + ALT + B
Go to source F4
Go to super Class CTRL + U
Show Call hierarchy CTRL + ALT + H
Search in path/project CTRL + SHIFT + F

Programming Shortcuts:-

Reformat code CTRL + ALT + L
Optimize imports CTRL + ALT + O
Code Completion CTRL + SPACE
Issue quick fix ALT + ENTER
Surround code block CTRL + ALT + T
Rename and Refractor Shift + F6
Line Comment or Uncomment CTRL + /
Block Comment or Uncomment CTRL + SHIFT + /
Go to previous/next method ALT + UP/DOWN
Show parameters for method CTRL + P
Quick documentation lookup CTRL + Q
Delete a line CTRL + Y
View declaration in layout CTRL + B

For more info visit Things worked in Android

Why is Dictionary preferred over Hashtable in C#?

One more difference that I can figure out is:

We can not use Dictionary<KT,VT> (generics) with web services. The reason is no web service standard supports the generics standard.

How to run single test method with phpunit?

The following command runs the test on a single method:

phpunit --filter testSaveAndDrop EscalationGroupTest escalation/EscalationGroupTest.php

phpunit --filter methodName ClassName path/to/file.php

For newer versions of phpunit, it is just:

phpunit --filter methodName path/to/file.php

How can I make my string property nullable?

C# 8.0 is published now so you can make reference types nullable too. For this you have to add

#nullable enable

Feature over your namespace. It is detailed here

For example something like this will work:

#nullable enable
namespace TestCSharpEight
{
  public class Developer
  {
    public string FullName { get; set; }
    public string UserName { get; set; }

    public Developer(string fullName)
    {
        FullName = fullName;
        UserName = null;
    }
}}

Also you can have a look this nice article from John Skeet that explains details.

undefined reference to 'std::cout'

Yes, using g++ command worked for me:

g++ my_source_code.cpp

Viewing contents of a .jar file

You can open them with most decompression utilities these days, then just get something like DJ Java Decompiler if you want to view the source.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

How to determine the Schemas inside an Oracle Data Pump Export file

You need to search for OWNER_NAME.

cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u

cat -v turn the dumpfile into visible text.

grep -o shows only the match so we don't see really long lines

uniq -u removes duplicate lines so you see less output.

This works pretty well, even on large dump files, and could be tweaked for usage in a script.

How can I use Guzzle to send a POST request in JSON?

For Guzzle 5, 6 and 7 you do it like this:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

What is the difference between `git merge` and `git merge --no-ff`?

Other answers indicate perfectly well that --no-ff results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.

This answer may provide context for when to use or not to use --no-ff.

Merging from feature into the main branch: use --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
$ git commit -am  "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature

Merging changes from main into feature branch: leave off --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am  "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

How do I edit SSIS package files?

You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.

Have a look at this link:

http://www.microsoft.com/downloads/details.aspx?familyid=3C856B93-369F-4C6F-9357-C35384179543&displaylang=en

How to have multiple conditions for one if statement in python

I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:

cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
    print("At least " + str(nr_conds) + " conditions are fullfilled")

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
    print("All conditions are fullfilled")

This means you can just change in the two initial lists, at least for me this makes it easier.

CustomErrors mode="Off"

Actually, what I figured out while hosting my web app is the the code you developed on your local Machine is of higher version than the hosting company offers you. If you have admin privileges you may be able to change the Microsoft ASP.NET version support under web hosting setting

Load json from local file with http.get() in angular 2

try: this.navItems = this.http.get("data/navItems.json");

How to copy a map?

Individual element copy, it seems to work for me with just a simple example.

maps := map[string]int {
    "alice":12,
    "jimmy":15,
}

maps2 := make(map[string]int)
for k2,v2 := range maps {
    maps2[k2] = v2
}

maps2["miki"]=rand.Intn(100)

fmt.Println("maps: ",maps," vs. ","maps2: ",maps2)

Convert DataTable to CSV stream

You can try using something like this. In this case I used one stored procedure to get more data tables and export all of them using CSV.

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace bo
{
class Program
{
    static private void CreateCSVFile(DataTable dt, string strFilePath)
    {
        #region Export Grid to CSV
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        int iColCount = dt.Columns.Count;

        // First we will write the headers.

        //DataTable dt = m_dsProducts.Tables[0];
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(";");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount -1 )
                {
                    sw.Write(";");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();

        #endregion
    }
    static void Main(string[] args)
    {
        string strConn = "connection string to sql";
        string direktorij = @"d:";
        SqlConnection conn = new SqlConnection(strConn); 
        SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add('@skl_id', SqlDbType.Int).Value = 158;
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            string datoteka  = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
            DataTable tabela = ds.Tables[i];
            CreateCSVFile(tabela,datoteka );
            Console.WriteLine("Generišem tabelu {0}", datoteka);
        }
        Console.ReadKey();
    }
  }
}

What is the correct way to create a single-instance WPF application?

Not using Mutex though, simple answer:

System.Diagnostics;    
...
string thisprocessname = Process.GetCurrentProcess().ProcessName;

if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

Put it inside the Program.Main().
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Sample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //simple add Diagnostics namespace, and these 3 lines below 
            string thisprocessname = Process.GetCurrentProcess().ProcessName;
            if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample());
        }
    }
}

You can add MessageBox.Show to the if-statement and put "Application already running".
This might be helpful to someone.

Launch Bootstrap Modal on page load

Just add the following-

class="modal show"

Working Example-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal show" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Android: How can I get the current foreground activity (from a service)?

Update: this no longer works with other apps' activities as of Android 5.0


Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

Example here

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

Here's an example.

    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    componentInfo.getPackageName();

You will need the following permission on your manifest:

<uses-permission android:name="android.permission.GET_TASKS"/>

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

Cannot ping AWS EC2 instance

  1. Make sure you are using the Public IP of you aws ec2 instance to ping.

  2. edit the secuity group that is attached to your EC2 instance and add an inbound rule for ICMP protocol.

  3. try pinging, if this doesnt fix, then add outbound rule for ICMP in the security group.

All combinations of a list of lists

Numpy can do it:

 >>> import numpy
 >>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
 >>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]

Get properties and values from unknown object

Here's something I use to transform an IEnumerable<T> into a DataTable that contains columns representing T's properties, with one row for each item in the IEnumerable:

public static DataTable ToDataTable<T>(IEnumerable<T> items)
{
    var table = CreateDataTableForPropertiesOfType<T>();
    PropertyInfo[] piT = typeof(T).GetProperties();
    foreach (var item in items)
    {
        var dr = table.NewRow();
        for (int property = 0; property < table.Columns.Count; property++)
        {
            if (piT[property].CanRead)
            {
                var value = piT[property].GetValue(item, null);
                if (piT[property].PropertyType.IsGenericType)
                {
                    if (value == null)
                    {
                        dr[property] = DBNull.Value;
                    }
                    else
                    {
                        dr[property] = piT[property].GetValue(item, null);
                    }
                }
                else
                {
                    dr[property] = piT[property].GetValue(item, null);
                }
            }
        }
        table.Rows.Add(dr);
    }
    return table;
}

public static DataTable CreateDataTableForPropertiesOfType<T>()
{
    DataTable dt = new DataTable();
    PropertyInfo[] piT = typeof(T).GetProperties();
    foreach (PropertyInfo pi in piT)
    {
        Type propertyType = null;
        if (pi.PropertyType.IsGenericType)
        {
            propertyType = pi.PropertyType.GetGenericArguments()[0];
        }
        else
        {
            propertyType = pi.PropertyType;
        }
        DataColumn dc = new DataColumn(pi.Name, propertyType);

        if (pi.CanRead)
        {
            dt.Columns.Add(dc);
        }
    }
    return dt;
}

This is "somewhat" overcomplicated, but it's actually quite good for seeing what the outcome is, as you can give it a List<T> of, for example:

public class Car
{
    string Make { get; set; }
    int YearOfManufacture {get; set; }
}

And you'll be returned a DataTable with the structure:

Make (string)
YearOfManufacture (int)

With one row per item in your List<Car>

SELECT * FROM in MySQLi

I was looking for a nice and complete example of how to bind multiple query parameters dynamically to any SELECT, INSERT, UPDATE and DELETE query. Alec mentions in his answer a way of how to bind result, for me the get_result() after execute() function for SELECT queries works just fine, and am able to retrieve all the selected results into an array of associative arrays.

Anyway, I ended up creating a function where I am able to dynamically bind any amount of parameters to a parametrized query ( using call_user_func_array function) and obtain a result of the query execution. Below is the function with its documentation (please read before it before using - especially the $paremetersTypes - Type specification chars parameter is important to understand)

     /**
     * Prepares and executes a parametrized QUERY (SELECT, INSERT, UPDATE, DELETE)
     *
     * @param[in] $dbConnection mysqli database connection to be used for query execution
     * @param[in] $dbQuery parametrized query to be bind parameters for and then execute
     * @param[in] $isDMQ boolean value, should be set to TRUE for (DELETE, INSERT, UPDATE - Data manipulaiton queries), FALSE for SELECT queries
     * @param[in] $paremetersTypes String representation for input parametrs' types as per http://php.net/manual/en/mysqli-stmt.bind-param.php
     * @param[in] $errorOut A variable to be passed by reference where a string representation of an error will be present if a FAUILURE occurs
     * @param[in] $arrayOfParemetersToBind Parameters to be bind to the parametrized query, parameters need to be specified in an array in the correct order 
     * @return array of feched records associative arrays for SELECT query on SUCCESS, TRUE for INSERT, UPDATE, DELETE queries on SUCCESS, on FAIL sets the error and returns NULL 
     */
    function ExecuteMySQLParametrizedQuery($dbConnection, $dbQuery, $isDMQ, $paremetersTypes, &$errorOut, $arrayOfParemetersToBind)
    {
        $stmt = $dbConnection->prepare($dbQuery);

        $outValue = NULL;

        if ($stmt === FALSE)
            $errorOut = 'Failed to prepare statement for query: ' . $dbQuery;
        else if ( call_user_func_array(array($stmt, "bind_param"), array_merge(array($paremetersTypes), $arrayOfParemetersToBind)) === FALSE)
            $errorOut = 'Failed to bind required parameters to query: ' . $dbQuery . '  , parameters :' . json_encode($arrayOfParemetersToBind);
        else if (!$stmt->execute())
            $errorOut = "Failed to execute query [$dbQuery] , erorr:" . $stmt->error;
        else
        {
            if ($isDMQ)
               $outValue = TRUE;
            else
            {
                $result = $stmt->get_result();

                if ($result === FALSE) 
                     $errorOut = 'Failed to obtain result from statement for query ' . $dbQuery;
                else
                    $outValue = $result->fetch_all(MYSQLI_ASSOC);
            }
        }

        $stmt->close();

        return $outValue;
    }

usage:

    $param1 = "128989";
    $param2 = "some passcode";


    $insertQuery = "INSERT INTO Cards (Serial, UserPin) VALUES (?, ?)";
    $rowsInserted = ExecuteMySQLParametrizedQuery($dbConnection, $insertQuery, TRUE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($rowsInserted === NULL)
        echo 'error ' . $errorOut;
    else
        echo "successfully inserted row";


    $selectQuery = "SELECT CardID FROM Cards WHERE Serial like ? AND UserPin like ?";
    $arrayOfCardIDs = ExecuteMySQLParametrizedQuery($dbConnection, $selectQuery, FALSE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($arrayOfCardIDs === NULL) 
        echo 'error ' . $errorOut;
    else
    {
        echo 'obtained result array of ' . count($arrayOfCardIDs) . 'selected rows';

        if (count($arrayOfCardIDs) > 0) 
            echo 'obtained card id = ' . $arrayOfCardIDs[0]['CardID'];
    }

Get all rows from SQLite

Update queueAll() method as below:

public Cursor queueAll() {

     String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
     Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

     return cursor;
}

Update readFileFromSQLite() method as below:

public ArrayList<String> readFileFromSQLite() {

    fileName = new ArrayList<String>();

    fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
    fileSQLiteAdapter.openToRead();

    cursor = fileSQLiteAdapter.queueAll();

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do 
            {
                String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
                fileName.add(name);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    fileSQLiteAdapter.close();

    return fileName;
}

How can I run a html file from terminal?

You can make the file accessible via a web server then you can use curl or lynx

How to get current user in asp.net core

Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^

// Stores UserManager
private readonly UserManager<ApplicationUser> _manager; 

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)  
{  
    _manager = manager;  
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()  
{  
    return await _manager.GetUserAsync(HttpContext.User);  
}  

// Generic demo method.
public async Task DemoMethod()  
{  
    var user = await GetCurrentUser(); 
    string userEmail = user.Email; // Here you gets user email 
    string userId = user.Id;
}  

That code goes to controller named DemoController. Won't work without both await (won't compile) ;)

What is Ruby's double-colon `::`?

Ruby on rails uses :: for namespace resolution.

class User < ActiveRecord::Base

  VIDEOS_COUNT = 10
  Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}

end

To use it :

User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"

Also, other usage is : When using nested routes

OmniauthCallbacksController is defined under users.

And routed as:

devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

end

Remove duplicates in the list using linq

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

Is there a way to include commas in CSV columns without breaking the formatting?

May not be what is needed here but it's a very old question and the answer may help others. A tip I find useful with importing into Excel with a different separator is to open the file in a text editor and add a first line like:

sep=|

where | is the separator you wish Excel to use. Alternatively you can change the default separator in Windows but a bit long-winded:

Control Panel>Clock & region>Region>Formats>Additional>Numbers>List separator [change from comma to your preferred alternative]. That means Excel will also default to exporting CSVs using the chosen separator.

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

REST API Best practice: How to accept list of parameter values as input

You might want to check out RFC 6570. This URI Template spec shows many examples of how urls can contain parameters.

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

Split string with delimiters in C

Method below will do all the job (memory allocation, counting the length) for you. More information and description can be found here - Implementation of Java String.split() method to split C string

int split (const char *str, char c, char ***arr)
{
    int count = 1;
    int token_len = 1;
    int i = 0;
    char *p;
    char *t;

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
            count++;
        p++;
    }

    *arr = (char**) malloc(sizeof(char*) * count);
    if (*arr == NULL)
        exit(1);

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
        {
            (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
            if ((*arr)[i] == NULL)
                exit(1);

            token_len = 0;
            i++;
        }
        p++;
        token_len++;
    }
    (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
    if ((*arr)[i] == NULL)
        exit(1);

    i = 0;
    p = str;
    t = ((*arr)[i]);
    while (*p != '\0')
    {
        if (*p != c && *p != '\0')
        {
            *t = *p;
            t++;
        }
        else
        {
            *t = '\0';
            i++;
            t = ((*arr)[i]);
        }
        p++;
    }

    return count;
}

How to use it:

int main (int argc, char ** argv)
{
    int i;
    char *s = "Hello, this is a test module for the string splitting.";
    int c = 0;
    char **arr = NULL;

    c = split(s, ' ', &arr);

    printf("found %d tokens.\n", c);

    for (i = 0; i < c; i++)
        printf("string #%d: %s\n", i, arr[i]);

    return 0;
}

Detailed 500 error message, ASP + IIS 7.5

In web.config under

<system.webServer>

replace (or add) the line

<httpErrors errorMode="Detailed"></httpErrors>

with

<httpErrors existingResponse="PassThrough" errorMode="Detailed"></httpErrors>

This is because by default IIS7 intercepts HTTP status codes such as 4xx and 5xx generated by applications further up the pipeline.

Next, enable "Send Errors to Browser" under the "ASP" section, and under "Error Pages / Edit Feature Settings", select "Detailed errors".

Also, give Write permissions on the website folder to the IIS_IUSRS builtin group.

How does the "view" method work in PyTorch?

I figured it out that x.view(-1, 16 * 5 * 5) is equivalent to x.flatten(1), where the parameter 1 indicates the flatten process starts from the 1st dimension(not flattening the 'sample' dimension) As you can see, the latter usage is semantically more clear and easier to use, so I prefer flatten().

What do the terms "CPU bound" and "I/O bound" mean?

I/O Bound process:- If most part of the lifetime of a process is spent in i/o state, then the process is a i/o bound process.example:-calculator,internet explorer

CPU Bound process:- If most part of the process life is spent in cpu,then it is cpu bound process.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Replacing:

$_SERVER["REMOTE_ADDR"];

With:

$_SERVER["HTTP_X_REAL_IP"];

Worked for me.

Getting all types that implement an interface

This worked for me. It loops though the classes and checks to see if they are derrived from myInterface

 foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                 .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
    //do stuff
 }

JavaScript - document.getElementByID with onClick

Sometimes JavaScript is not activated. Try something like:

<!DOCTYPE html>
<html>
  <head>

    <script type="text/javascript"> <!--
      function jActivator() {
        document.getElementById("demo").onclick = function() {myFunction()};
        document.getElementById("demo1").addEventListener("click", myFunction);
        }
      function myFunction( s ) {
        document.getElementById("myresult").innerHTML = s;
        }
    // --> </script>
    <noscript>JavaScript deactivated.</noscript>
    <style type="text/css">
    </style>
  </head>
  <body onload="jActivator()">
    <ul>
      <li id="demo">Click me -&gt; onclick.</li>
      <li id="demo1">Click me -&gt; click event.</li>
      <li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
    </ul>
    <div id="myresult">&nbsp;</div>
  </body>
</html>

If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '

Run bash command on jenkins pipeline

For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:

sh 'chmod +x ./script.sh'
sh './script.sh'

Creating a batch file, for simple javac and java command execution

hey I think that you just copy your compiled class files and copy the jre folder and make the following as the content of the batch file and save all together any windows machine and just double click

@echo
setpath d:\jre
d:
cd myprogfolder
java myprogram

Writing handler for UIAlertAction

Instead of self in your handler, put (alert: UIAlertAction!). This should make your code look like this

    alert.addAction(UIAlertAction(title: "Okay",
                          style: UIAlertActionStyle.Default,
                        handler: {(alert: UIAlertAction!) in println("Foo")}))

this is the proper way to define handlers in Swift.

As Brian pointed out below, there are also easier ways to define these handlers. Using his methods is discussed in the book, look at the section titled Closures

Invoking Java main method with parameters from Eclipse

Another idea:

Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)). So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...

Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

What is the main difference between Inheritance and Polymorphism?

Polymorphism is an effect of inheritance. It can only happen in classes that extend one another. It allows you to call methods of a class without knowing the exact type of the class. Also, polymorphism does happen at run time.

For example, Java polymorphism example:

enter image description here

Inheritance lets derived classes share interfaces and code of their base classes. It happens at compile time.

For example, All Classes in the Java Platform are Descendants of Object (image courtesy Oracle):

enter image description here

To learn more about Java inheritance and Java polymorphism

Logger slf4j advantages of formatting with {} instead of string concatenation

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

POSIX 7

First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

That contains a link to a time.h, which as a header should be where structs are defined:

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

Error - trustAnchors parameter must be non-empty

On Red Hat Linux I got this issue resolved by importing the certificates to /etc/pki/java/cacerts.

Is it possible to set UIView border properties from interface builder?

Similar answer to iHulk's one, but in Swift

Add a file named UIView.swift in your project (or just paste this in any file) :

import UIKit

@IBDesignable extension UIView {
    @IBInspectable var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            guard let color = layer.borderColor else {
                return nil
            }
            return UIColor(cgColor: color)
        }
    }
    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Then this will be available in Interface Builder for every button, imageView, label, etc. in the Utilities Panel > Attributes Inspector :

Attributes Inspector

Note: the border will only appear at runtime.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,

return File(returnFilePath, contentType, fileName);

would give the error in mobile safari, where as

return File(returnFilePath, contentType);

would not.

I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.

Regular expression to match a dot

This expression,

(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)

might also work OK for those specific types of input strings.

Demo

Test

import re

expression = r'(?<=^|\s)[^.\s]+\.[^.\s]+(?=@)'
string = '''
blah blah blah [email protected] blah blah
blah blah blah test.this @gmail.com blah blah
blah blah blah [email protected] blah blah
'''

matches = re.findall(expression, string)

print(matches)

Output

['test.this']

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


JPA - Returning an auto generated id after persist()

The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:

em.persist(abc);
em.flush();
return abc.getId();

or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.

@Override
public ABC addNewABC(ABC abc) {
    abcDao.insertABC(abc);
    return abc;
}

How to ignore user's time zone and force Date() use specific time zone

To account for milliseconds and the user's time zone, use the following:

var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable

What does the "yield" keyword do?

It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as C#'s iterator blocks if you're familiar with those.

The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - as if the generator method was paused. Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

How to get back to most recent version in Git?

You can check out using branch names, for one thing.

I know there are several ways to move the HEAD around, but I'll leave it to a git expert to enumerate them.

I just wanted to suggest gitk --all -- I found it enormously helpful when starting with git.

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

How to ignore the first line of data when processing CSV data?

Borrowed from python cookbook,
A more concise template code might look like this:

import csv
with open('stocks.csv') as f:
    f_csv = csv.reader(f) 
    headers = next(f_csv) 
    for row in f_csv:
        # Process row ...

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

How to play or open *.mp3 or *.wav sound file in c++ program?

Try with simple c++ code in VC++.

#include <windows.h>
#include <iostream>
#pragma comment(lib, "winmm.lib")

int main(int argc, char* argv[])
{
std::cout<<"Sound playing... enjoy....!!!";
PlaySound("C:\\temp\\sound_test.wav", NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP
return 0;
}

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

Class 'ViewController' has no initializers in swift

Replace var appDelegate : AppDelegate? with let appDelegate = UIApplication.sharedApplication().delegate as hinted on the second commented line in viewDidLoad().

The keyword "optional" refers exactly to the use of ?, see this for more details.

Serialize Class containing Dictionary member

I wanted a SerializableDictionary class that used xml attributes for key/value so I've adapted Paul Welter's class.

This produces xml like:

<Dictionary>
  <Item Key="Grass" Value="Green" />
  <Item Key="Snow" Value="White" />
  <Item Key="Sky" Value="Blue" />
</Dictionary>"

Code:

using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace DataTypes {
    [XmlRoot("Dictionary")]
    public class SerializableDictionary<TKey, TValue>
        : Dictionary<TKey, TValue>, IXmlSerializable {
        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema() {
            return null;
        }

        public void ReadXml(XmlReader reader) {
            XDocument doc = null;
            using (XmlReader subtreeReader = reader.ReadSubtree()) {
                doc = XDocument.Load(subtreeReader);
            }
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            foreach (XElement item in doc.Descendants(XName.Get("Item"))) {
                using(XmlReader itemReader =  item.CreateReader()) {
                    var kvp = serializer.Deserialize(itemReader) as SerializableKeyValuePair<TKey, TValue>;
                    this.Add(kvp.Key, kvp.Value);
                }
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer) {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            foreach (TKey key in this.Keys) {
                TValue value = this[key];
                var kvp = new SerializableKeyValuePair<TKey, TValue>(key, value);
                serializer.Serialize(writer, kvp, ns);
            }
        }
        #endregion

        [XmlRoot("Item")]
        public class SerializableKeyValuePair<TKey, TValue> {
            [XmlAttribute("Key")]
            public TKey Key;

            [XmlAttribute("Value")]
            public TValue Value;

            /// <summary>
            /// Default constructor
            /// </summary>
            public SerializableKeyValuePair() { }
        public SerializableKeyValuePair (TKey key, TValue value) {
            Key = key;
            Value = value;
        }
    }
}
}

Unit Tests:

using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DataTypes {
    [TestClass]
    public class SerializableDictionaryTests {
        [TestMethod]
        public void TestStringStringDict() {
            var dict = new SerializableDictionary<string, string>();
            dict.Add("Grass", "Green");
            dict.Add("Snow", "White");
            dict.Add("Sky", "Blue");
            dict.Add("Tomato", "Red");
            dict.Add("Coal", "Black");
            dict.Add("Mud", "Brown");

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(dict.Count, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<string, string>;
                Assert.AreEqual(dict["Grass"], outDict["Grass"]);
                Assert.AreEqual(dict["Snow"], outDict["Snow"]);
                Assert.AreEqual(dict["Sky"], outDict["Sky"]);
            }
        }

        [TestMethod]
        public void TestIntIntDict() {
            var dict = new SerializableDictionary<int, int>();
            dict.Add(4, 7);
            dict.Add(5, 9);
            dict.Add(7, 8);

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(3, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<int, int>;
                Assert.AreEqual(dict[4], outDict[4]);
                Assert.AreEqual(dict[5], outDict[5]);
                Assert.AreEqual(dict[7], outDict[7]);
            }
        }
    }
}

How to find out the number of CPUs using python

Another option if you don't have Python 2.6:

import commands
n = commands.getoutput("grep -c processor /proc/cpuinfo")

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

How to set aliases in the Git Bash for Windows?

To Add a Temporary Alias:

  1. Goto Terminal (I'm using git bash for windows).
  2. Type $ alias gpuom='git push origin master'
  3. To See a List of All the aliases type $ alias hit Enter.

To Add a Permanent Alias:

  1. Goto Terminal (I'm using git bash for windows).
  2. Type $ vim ~/.bashrc and hit Enter (I'm guessing you are familiar with vim).
  3. Add your new aliases (For reference look at the snippet below).
    #My custom aliases  
    alias gpuom='git push origin master' 
    alias gplom='git pull origin master'
    
  4. Save and Exit (Press Esc then type :wq).
  5. To See a List of All the aliases type $ alias hit Enter.

add item in array list of android

You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:

resultArrGame.add(txt.Game.getText().toString());

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I was having the same problem with the fetch command. A quick look at the docs from here tells us this:

If the server you are requesting from doesn't support CORS, you should get an error in the console indicating that the cross-origin request is blocked due to the CORS Access-Control-Allow-Origin header being missing.

You can use no-cors mode to request opaque resources.

fetch('https://bar.com/data.json', {
  mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
  // Do something with response
});

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Environment variable to control java.io.tmpdir?

Use below command on UNIX terminal :

java -XshowSettings

This will display all java properties and system settings. In this look for java.io.tmpdir value.

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

How can I find the method that called the current method?

In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach:

  1. It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace.
  2. It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it.

(NOTE: I am just expanding on the answer provided by Firas Assad.)

SQL query question: SELECT ... NOT IN

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null

Make sure your list parameter does not contain null values.

Here's an explanation:

WHERE field1 NOT IN (1, 2, 3, null)

is the same as:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • That last comparision evaluates to null.
  • That null is OR'd with the rest of the boolean expression, yielding null. (*)
  • null is negated, yielding null.
  • null is not true - the where clause only keeps true rows, so all rows are filtered.

(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Fastest way to determine if record exists

Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's

SELECT distinct 1 products.id FROM products WHERE products.id = ?;

Clear terminal in Python

This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT rows_max distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.

def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
          store_max=[]):
    """clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
    from os import linesep
    if rows_max and rows_max != -1:
        store_max[:] = [rows_max, False]
    elif not store_max or store_max[1] or rows_max == -1 or absolute:
        try:
            from shutil import get_terminal_size
            columns_max, rows_max = get_terminal_size()
        except ImportError:
            columns_max, rows_max = 80, 24
        if absolute is None:
            store_max[:] = [rows_max, True]
    if store_max:
        if rows == -1:
            rows = store_max[0]
        elif isinstance(rows, float):
            rows = round(store_max[0] * rows)
        if rows > store_max[0] - 2:
            rows = store_max[0] - 2
    if absolute is None:
        s = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
    else:
        s = '\033[{}A'.format(absolute + 2) + linesep
        if absolute > rows_max - 2:
            absolute = rows_max - 2
        s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
        rows = absolute
    print(s + '\033[{}A'.format(rows + 1))

Implementation:

clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

Parameters: rows is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *, in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True (default) works better in Interactive mode. calling_line=False works better for text-based, terminal applications. absolute was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max is just for secret, "persistent" storage of rows_max value; don't explicitly use this parameter. (When an argument is not passed for store_max, changing the list contents of store_max changes this parameter's default value. Hence, persistent storage.)

Portability: Sorry, this doesn't work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the shutil.get_terminal_size() function for BEST results) and ANSI recognition. The print(...) function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).

For use in Interactive mode: First copy and paste the copy(...) function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with 'python3'. Enter:

>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...

Now drop the clear.py file into one of the path directories listed so that Python can find it (don't overwrite any existing files). To easily use from now on:

>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

For use in a terminal application: Put the copy(...) function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):

from os import linesep

class TicTacToe:    
    def __init__(self):
        # Clear screen, but not calling line
        try:
            from clear import clear
            self.clear = clear
            self.clear(calling_line=False)
        except ImportError:
            self.clear = False
        self.rows = 0    # Track printed lines to clear

        # ...
        self.moves = [' '] * 9

    def do_print(self, *text, end=linesep):
        text = list(text)
        for i, v in enumerate(text[:]):
            text[i] = str(v)
        text = ' '.join(text)
        print(text, end=end)
        self.rows += text.count(linesep) + 1

    def show_board(self):
        if self.clear and self.rows:
            self.clear(absolute=self.rows)
        self.rows = 0
        self.do_print('Tic Tac Toe')
        self.do_print('''   |   |
 {6} | {7} | {8}
   |   |
-----------
   |   |
 {3} | {4} | {5}
   |   |
-----------
   |   |
 {0} | {1} | {2}
   |   |'''.format(*self.moves))

    def start(self):
        self.show_board()
        ok = input("Press <Enter> to continue...")
        self.moves = ['O', 'X'] * 4 + ['O']
        self.show_board()
        ok = input("Press <Enter> to close.")

if __name__ == "__main__":
    TicTacToe().start()

Explanation: do_print(...) on line 19 is a version of print(...) needed to keep track of how many new lines have been printed (self.rows). Otherwise, you would have to self.rows += 1 all over the place where print(...) is called throughout the entire program. So each time the board is redrawn by calling show_board() the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False) on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows) on line 29 absolutely clears out everything self.rows distance upward, rather than just pushing everything upward relative to the bottom of the terminal.

Ubuntu users with Python 3.3: Put #!/usr/bin/env python3 on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal's current directory is that of the tictactoe.py file, you can also start the file with ./tictactoe.py.

How do I search for files in Visual Studio Code?

If using vscodevim extension, ctrl + p won't work so I saw another answer using:

ctrl + shift + p

which opens the command palette. Hit backspace to remove the '>' and then start typing your filename.

How to check certificate name and alias in keystore files?

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep.

How can I use UserDefaults in Swift?

I would say Anbu's answer perfectly fine but I had to add guard while fetching preferences to make my program doesn't fail

Here is the updated code snip in Swift 5

Storing data in UserDefaults

@IBAction func savePreferenceData(_ sender: Any) {
        print("Storing data..")
        UserDefaults.standard.set("RDC", forKey: "UserName") //String
        UserDefaults.standard.set("TestPass", forKey: "Passowrd")  //String
        UserDefaults.standard.set(21, forKey: "Age")  //Integer

    }

Fetching data from UserDefaults

    @IBAction func fetchPreferenceData(_ sender: Any) {
        print("Fetching data..")

        //added guard
        guard let uName = UserDefaults.standard.string(forKey: "UserName") else { return }
        print("User Name is :"+uName)
        print(UserDefaults.standard.integer(forKey: "Age"))
    }

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

how to programmatically fake a touch event to a UIButton?

It turns out that

[buttonObj sendActionsForControlEvents:UIControlEventTouchUpInside];

got me exactly what I needed, in this case.

EDIT: Don't forget to do this in the main thread, to get results similar to a user-press.


For Swift 3:

buttonObj.sendActions(for: .touchUpInside)

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

How to format JSON in notepad++

I was unable to find JSTool. Please see below url to see how I installed Notepad++

How to view Plugin Manager in Notepad++

I created JSMinNPP folder in C:\Program Files (x86)\Notepad++\plugins and copied JSMinNPP to it.

enter image description here

enter image description here

Validation of radio button group using jQuery validation plugin

use the following rule for validating radio button group selection

myRadioGroupName : {required :true}

myRadioGroupName is the value you have given to name attribute

ImportError: cannot import name

Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app module, call mod_login.mod_login

app.py

from flask import Flask
import mod_login

# ...

do_stuff_with(mod_login.mod_login)

mod_login.py

from app import app

mod_login = something

auto run a bat script in windows 7 at login

To run the batch file when the VM user logs in:

Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.

Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\.

As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:

start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"

But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Adding script tag to React/JSX

According to Alex McMillan's solution, I have the following adaptation.
My own environment: React 16.8+, next v9+

// add a custom component named Script
// hooks/Script.js

import { useEffect } from 'react'

const useScript = (url, async) => {
  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = (typeof async === 'undefined' ? true : async )

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])
}

export default function Script({ src, async=true}) {

  useScript(src, async)

  return null  // Return null is necessary for the moment.
}

// Use the custom compoennt, just import it and substitute the old lower case <script> tag with the custom camel case <Script> tag would suffice.
// index.js

import Script from "../hooks/Script";

<Fragment>
  {/* Google Map */}
  <div ref={el => this.el = el} className="gmap"></div>

  {/* Old html script */}
  {/*<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>*/}

  {/* new custom Script component */}
  <Script src='http://maps.google.com/maps/api/js' async={false} />
</Fragment>

In Javascript, how to conditionally add a member to an object?

This is probably the shortest solution with ES6

console.log({
   ...true && {foo: 'bar'}
})
// Output: {foo:'bar'}
console.log({
   ...false && {foo: 'bar'}
})
// Output: {}

What is the ultimate postal code and zip regex?

If someone is still interested in how to validate zip codes I've found a solution:

Using Google Geocoding API we can check validity of ZIP code having both Country code and a ZIP code itself.

For example I live in Ukraine so I can check like this: https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:80380|country:UA

Or using JS API: https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

Where 80380 is valid ZIP for Ukraine, actually every (#####) is valid.

Google returns ZERO_RESULTS status if nothing found. Or OK and a result if both are correct.

Hope this will be helpful.

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

CMake unable to determine linker language with C++

In my case, implementing a member function of a class in a header file cause this error. Separating interface (in x.h file) and implementation (in x.cpp file) solves the problem.

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

How do you launch the JavaScript debugger in Google Chrome?

Try adding this to your source:

debugger;

It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.

Python + Django page redirect

page_path = define in urls.py

def deletePolls(request):
    pollId = deletePool(request.GET['id'])
    return HttpResponseRedirect("/page_path/")

Can we execute a java program without a main() method?

Since you tagged Java-ee as well - then YES it is possible.

and in core java as well it is possible using static blocks

and check this How can you run a Java program without main method?

Edit:
as already pointed out in other answers - it does not support from Java 7

Best way to check for "empty or null value"

To check for null and empty:

coalesce(string, '') = ''

To check for null, empty and spaces (trim the string)

coalesce(TRIM(string), '') = ''

How can you customize the numbers in an ordered list?

This code makes numbering style same as headers of li content.

<style>
    h4 {font-size: 18px}
    ol.list-h4 {counter-reset: item; padding-left:27px}
    ol.list-h4 > li {display: block}
    ol.list-h4 > li::before {display: block; position:absolute;  left:16px;  top:auto; content: counter(item)"."; counter-increment: item; font-size: 18px}
    ol.list-h4 > li > h4 {padding-top:3px}
</style>

<ol class="list-h4">
    <li>
        <h4>...</h4>
        <p>...</p> 
    </li>
    <li>...</li>
</ol>

What's the difference between RANK() and DENSE_RANK() functions in oracle?

SELECT empno,
       deptno,
       sal,
       RANK() OVER (PARTITION BY deptno ORDER BY sal) "rank"
FROM   emp;

     EMPNO     DEPTNO        SAL       rank
---------- ---------- ---------- ----------
      7934         10       1300          1
      7782         10       2450          2
      7839         10       5000          3
      7369         20        800          1
      7876         20       1100          2
      7566         20       2975          3
      7788         20       3000          4
      7902         20       3000          4
      7900         30        950          1
      7654         30       1250          2
      7521         30       1250          2
      7844         30       1500          4
      7499         30       1600          5
      7698         30       2850          6


SELECT empno,
       deptno,
       sal,
       DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal) "rank"
FROM   emp;

     EMPNO     DEPTNO        SAL       rank
---------- ---------- ---------- ----------
      7934         10       1300          1
      7782         10       2450          2
      7839         10       5000          3
      7369         20        800          1
      7876         20       1100          2
      7566         20       2975          3
      7788         20       3000          4
      7902         20       3000          4
      7900         30        950          1
      7654         30       1250          2
      7521         30       1250          2
      7844         30       1500          3
      7499         30       1600          4
      7698         30       2850          5

How to include a PHP variable inside a MySQL statement

To avoid SQL injection the insert statement with be

$type = 'testing';
$name = 'john';
$description = 'whatever';

$stmt = $con->prepare("INSERT INTO contents (type, reporter, description) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $type , $name, $description);
$stmt->execute();

Where do I find some good examples for DDD?

Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action. While the book is focused on the presentation layer, the application is modeled using DDD.

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Graphviz: How to go from .dot to a graph?

For window user, Please run complete command to convert *.dot file to png:

C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tpng sampleTest.dot > sampletest.png.....

I have found a bug in solgraph that it is utilizing older version of solidity-parser that does not seem to be intelligent enough to capture new enhancement done for solidity programming language itself e.g. emit keyword for Event

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

Error: "setFile(null,false) call failed" when using log4j

To prevent this isue I changed all values in log4j.properties file with directory ${kafka.logs.dir} to my own directory. For example D:/temp/...

Could not find module FindOpenCV.cmake ( Error in configuration process)

I had the same error, I use windows. I add "C:\opencv\build" (opencv folder) to path at the control pannel. So, That's Ok!!

Show loading screen when navigating between routes in Angular 2

UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate guard. I'm degrading to my old method, ie: this answer

UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.

UPDATE1: I wrote this answer in the era of Old-Router, when there used to be only one event route-changed notified via router.subscribe(). I also felt overload of the below approach and tried to do it using only router.subscribe(), and it backfired because there was no way to detect canceled navigation. So I had to revert back to lengthy approach(double work).


If you know your way around in Angular2, this is what you'll need


Boot.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';

bootstrap(MyApp, [SpinnerService]);

Root Component- (MyApp)

import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
  selector: 'my-app',
  directives: [SpinnerComponent],
  template: `
     <spinner-component></spinner-component>
     <router-outlet></router-outlet>
   `
})
export class MyApp { }

Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)

import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
  selector: 'spinner-component',
  'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
  public active: boolean;

  public constructor(spinner: SpinnerService) {
    spinner.status.subscribe((status: boolean) => {
      this.active = status;
    });
  }
}

Spinner-Service (bootstrap this service)

Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';

@Injectable()
export class SpinnerService {
  public status: Subject<boolean> = new Subject();
  private _active: boolean = false;

  public get active(): boolean {
    return this._active;
  }

  public set active(v: boolean) {
    this._active = v;
    this.status.next(v);
  }

  public start(): void {
    this.active = true;
  }

  public stop(): void {
    this.active = false;
  }
}

All Other Routes' Components

(sample):

import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
   template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {

  constructor(public spinner: SpinnerService){} 

  ngOnInit(){
    this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
  }

  ngOnDestroy(){
    this.spinner.start();
  }
}

Unable to start MySQL server

You should start by checking the error log and/or the startup message log when managing the instance using MySQL Workbench. There could be clues as to what is going wrong, which may be different than this scenario.

When I had this issue, it was because I used a space in the service name during installation. While it is technically valid, you should not do that. It seems that the MySQL Installer (and MySQL Notifier) does not put the name in quotes which causes it to use an incorrect service name later on. There are two ways to fix the problem (all commands should be run from an elevated command prompt).

Reinstall the server

The first is to simply reinstall MySQL Server 5.6 using the default, no-space service name MySQL56.

The installer uses the same value for the service name and service display name. The name that I had originally specified was for a display name, when it should have been a simple service name. After installation, if you so choose, the display name can safely be changed to use spaces and other characters by using:

sc config MySQL56 DisplayName= "MySQL 5.6"

Recreate the service

If you don't want to reinstall the server however, you will have to recreate the service. Start by removing the old service:

mysqld --remove "service_name"

Now install the replacement. You can use --install to create a service that starts with the system automatically, or --install-manual to create a service that requires you to start it.

mysqld --install-manual "service_name" --local-service --defaults-file="C:\path\to\mysql\my.ini"

This creates a service that runs as the LocalService account which presents anonymous credentials on the network however. Under most circumstances this is fine, but if you want to use the NetworkService account (which is what the installer creates the service as) you can change it using the Services administrative tool.

How to remove \xa0 from string in Python?

I end up here while googling for the problem with not printable character. I use MySQL UTF-8 general_ci and deal with polish language. For problematic strings I have to procced as follows:

text=text.replace('\xc2\xa0', ' ')

It is just fast workaround and you probablly should try something with right encoding setup.

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

How do I upload a file with the JS fetch API?

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

Find row in datatable with specific id

DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
    // code
}

If it is a typed DataSet:

MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
    // code
}

Printing the last column of a line in a file

maybe this works?

grep A1 file | tail -1 | awk '{print $NF}'

How to extract an assembly from the GAC?

just navigate to C:\Windows find the [assembly] folder right click and select add to archive

wait a little

vola you have an archive file containing all the assemblies in your GAC

Run as java application option disabled in eclipse

Had the same problem. I apparently wrote the Main wrong:

public static void main(String[] args){

I missed the [] and that was the whole problem.

Check and recheck the Main function!

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

QString to char* conversion

Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by "it deosn't seem to work".

Uploading a file in Rails

There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave gem .

I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

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

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

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

Controller's Action Method

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

Jquery GET

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

Person class

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

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

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

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

For more information check Posting JSON Data to MVC Controllers Here

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

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

View

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

Action Method

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

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

Suitable for when you need to Get data from database

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

I hope this will help to you.

Pythonic way to check if a file exists?

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

If you want to avoid this sort of thing, I would suggest something like the following (untested):

import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

How to manually update datatables table with new JSON data

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()