Programs & Examples On #Script debugging

How to search all loaded scripts in Chrome Developer Tools?

In the latest Chrome as of 10/26/2018, the top-rated answer no longer works, here's how it's done: enter image description here

enter image description here

Using css transform property in jQuery

I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

How to switch back to 'master' with git?

You need to checkout the branch:

git checkout master

See the Git cheat sheets for more information.

Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

Retrieving the last record in each group - MySQL

MySQL 8.0 now supports windowing functions, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries:

WITH ranked_messages AS (
  SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn
  FROM messages AS m
)
SELECT * FROM ranked_messages WHERE rn = 1;

Below is the original answer I wrote for this question in 2009:


I write the solution this way:

SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
 ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL;

Regarding performance, one solution or the other can be better, depending on the nature of your data. So you should test both queries and use the one that is better at performance given your database.

For example, I have a copy of the StackOverflow August data dump. I'll use that for benchmarking. There are 1,114,357 rows in the Posts table. This is running on MySQL 5.0.75 on my Macbook Pro 2.40GHz.

I'll write a query to find the most recent post for a given user ID (mine).

First using the technique shown by @Eric with the GROUP BY in a subquery:

SELECT p1.postid
FROM Posts p1
INNER JOIN (SELECT pi.owneruserid, MAX(pi.postid) AS maxpostid
            FROM Posts pi GROUP BY pi.owneruserid) p2
  ON (p1.postid = p2.maxpostid)
WHERE p1.owneruserid = 20860;

1 row in set (1 min 17.89 sec)

Even the EXPLAIN analysis takes over 16 seconds:

+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
| id | select_type | table      | type   | possible_keys              | key         | key_len | ref          | rows    | Extra       |
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
|  1 | PRIMARY     | <derived2> | ALL    | NULL                       | NULL        | NULL    | NULL         |   76756 |             | 
|  1 | PRIMARY     | p1         | eq_ref | PRIMARY,PostId,OwnerUserId | PRIMARY     | 8       | p2.maxpostid |       1 | Using where | 
|  2 | DERIVED     | pi         | index  | NULL                       | OwnerUserId | 8       | NULL         | 1151268 | Using index | 
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
3 rows in set (16.09 sec)

Now produce the same query result using my technique with LEFT JOIN:

SELECT p1.postid
FROM Posts p1 LEFT JOIN posts p2
  ON (p1.owneruserid = p2.owneruserid AND p1.postid < p2.postid)
WHERE p2.postid IS NULL AND p1.owneruserid = 20860;

1 row in set (0.28 sec)

The EXPLAIN analysis shows that both tables are able to use their indexes:

+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
| id | select_type | table | type | possible_keys              | key         | key_len | ref   | rows | Extra                                |
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
|  1 | SIMPLE      | p1    | ref  | OwnerUserId                | OwnerUserId | 8       | const | 1384 | Using index                          | 
|  1 | SIMPLE      | p2    | ref  | PRIMARY,PostId,OwnerUserId | OwnerUserId | 8       | const | 1384 | Using where; Using index; Not exists | 
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
2 rows in set (0.00 sec)

Here's the DDL for my Posts table:

CREATE TABLE `posts` (
  `PostId` bigint(20) unsigned NOT NULL auto_increment,
  `PostTypeId` bigint(20) unsigned NOT NULL,
  `AcceptedAnswerId` bigint(20) unsigned default NULL,
  `ParentId` bigint(20) unsigned default NULL,
  `CreationDate` datetime NOT NULL,
  `Score` int(11) NOT NULL default '0',
  `ViewCount` int(11) NOT NULL default '0',
  `Body` text NOT NULL,
  `OwnerUserId` bigint(20) unsigned NOT NULL,
  `OwnerDisplayName` varchar(40) default NULL,
  `LastEditorUserId` bigint(20) unsigned default NULL,
  `LastEditDate` datetime default NULL,
  `LastActivityDate` datetime default NULL,
  `Title` varchar(250) NOT NULL default '',
  `Tags` varchar(150) NOT NULL default '',
  `AnswerCount` int(11) NOT NULL default '0',
  `CommentCount` int(11) NOT NULL default '0',
  `FavoriteCount` int(11) NOT NULL default '0',
  `ClosedDate` datetime default NULL,
  PRIMARY KEY  (`PostId`),
  UNIQUE KEY `PostId` (`PostId`),
  KEY `PostTypeId` (`PostTypeId`),
  KEY `AcceptedAnswerId` (`AcceptedAnswerId`),
  KEY `OwnerUserId` (`OwnerUserId`),
  KEY `LastEditorUserId` (`LastEditorUserId`),
  KEY `ParentId` (`ParentId`),
  CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`PostTypeId`) REFERENCES `posttypes` (`PostTypeId`)
) ENGINE=InnoDB;

How to customize the background/border colors of a grouped table view cell?

First of all thanks for this code. I have made some drawing changes in this function to remove corner problem of drawing.

-(void)drawRect:(CGRect)rect 
{
    // Drawing code

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [fillColor CGColor]);
    CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
    CGContextSetLineWidth(c, 2);

    if (position == CustomCellBackgroundViewPositionTop) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny + 1;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, maxy);
        CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, maxy);

        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);        
        return;
    } else if (position == CustomCellBackgroundViewPositionBottom) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy - 1;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, miny);
        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    } else if (position == CustomCellBackgroundViewPositionMiddle) {
        CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddLineToPoint(c, maxx, miny);
        CGContextAddLineToPoint(c, maxx, maxy);
        CGContextAddLineToPoint(c, minx, maxy);

        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    }
}

Validate phone number with JavaScript

If you are looking for 10 and only 10 digits, ignore everything but the digits-

   return value.match(/\d/g).length===10;

how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white to the HTML element. I overwrote that and everything was easy to handle from there.

How to filter files when using scp to copy dir recursively?

Since you can scp you should be ok to ssh,
either script the following or login and execute...

# After reaching the server of interest
cd /usr/some/unknown/number/of/sub/folders
tar cfj pack.tar.bz2 $(find . -type f -name *.class)

return back (logout) to local server and scp,

# from the local machine
cd /usr/project/backup/some/unknown/number/of/sub/folders
scp you@server:/usr/some/unknown/number/of/sub/folders/pack.tar.bz2 .
tar xfj pack.tar.bz2

If you find the $(find ...) is too long for your tar change to,

find . -type f -name *.class | xargs tar cfj pack.tar.bz2

Finally, since you are keeping it in /usr/project/backup/,
why bother extraction? Just keep the tar.bz2, with maybe a date+time stamp.

How do I get the object if it exists, or None if it does not exist?

you could use exists with a filter:

Content.objects.filter(name="baby").exists()
#returns False or True depending on if there is anything in the QS

just an alternative for if you only want to know if it exists

how to sync windows time from a ntp time server in command

Use net time net time \\timesrv /set /yes

after your comment try this one in evelated prompt :

w32tm /config /update /manualpeerlist:yourtimerserver

Kubernetes how to make Deployment to update image

You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always". And use kubectl delete pod pod_name. A new container will be created and the latest image automatically downloaded, then the old container terminated.

Example:

spec:
  terminationGracePeriodSeconds: 30
  containers:
  - name: my_container
    image: my_image:latest
    imagePullPolicy: "Always"

I'm currently using Jenkins for automated builds and image tagging and it looks something like this:

kubectl --user="kube-user" --server="https://kubemaster.example.com"  --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT"

Another trick is to intially run:

kubectl set image deployment/my-deployment mycontainer=myimage:latest

and then:

kubectl set image deployment/my-deployment mycontainer=myimage

It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always" set.

Update:

another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds. You can do this using kubectl edit deployment your_deployment or kubectl apply -f your_deployment.yaml or using a patch like this:

kubectl patch deployment your_deployment -p \
  '{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}'

Just make sure you always change the number value.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I had the same problem and resulted that was an "every day" error in the rails controller. I don't know why, but on production, puma runs the error again and again causing the message:

upstream timed out (110: Connection timed out) while reading response header from upstream

Probably because Nginx tries to get the data from puma again and again.The funny thing is that the error caused the timeout message even if I'm calling a different action in the controller, so, a single typo blocks all the app.

Check your log/puma.stderr.log file to see if that is the situation.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

ARM compilation error, VFP registers used by executable, not object file

This answer may appear at the surface to be unrelated, but there is an indirect cause of this error message.

First, the "Uses VFP register..." error message is directly caused from mixing mfloat-abi=soft and mfloat-abi=hard options within your build. This setting must be consistent for all objects that are to be linked. This fact is well covered in the other answers to this question.

The indirect cause of this error may be due to the Eclipse editor getting confused by a self-inflicted error in the project's ".cproject" file. The Eclipse editor frequently reswizzles file links and sometimes it breaks itself when you make changes to your directory structures or file locations. This can also affect the path settings to your gcc compiler - and only for a subset of your project's files. While I'm not yet sure of exactly what causes this failure, replacing the .cproject file with a backup copy corrected this problem for me. In my case I noticed .java.null.pointer errors after adding an include directory path and started receiving the "VFP register error" messages out of the blue. In the build log I noticed that a different path to the gcc compiler was being used for some of my sources that were local to the workspace, but not all of them!? The two gcc compilers were using different float settings for unknown reasons - hence the VFP register error.

I compared the .cproject settings with a older copy and observed differences in entries for the sources causing the trouble - even though the overriding of project settings was disabled. By replacing the .cproject file with the old version the problem went away, and I'm leaving this answer as a reminder of what happened.

index.php not loading by default

Apache needs to be configured to recognize index.php as an index file.

The simplest way to accomplish this..

  1. Create a .htaccess file in your web root.

  2. Add the line...

DirectoryIndex index.php

Here is a resource regarding the matter...
http://www.twsc.biz/twsc_hosting_htaccess.php

Edit: I'm assuming apache is configured to allow .htaccess files. If it isn't, you'll have to modify the setting in apache's configuration file (httpd.conf)

Populate unique values into a VBA array from Excel

This VBA function returns an array of distinct values when passed either a range or a 2D array source

It defaults to processing the first column of the source, but you can optionally choose another column.

I wrote a LinkedIn article about it.

Function DistinctVals(a, Optional col = 1)
    Dim i&, v: v = a
    With CreateObject("Scripting.Dictionary")
        For i = 1 To UBound(v): .Item(v(i, col)) = 1: Next
        DistinctVals = Application.Transpose(.Keys)
    End With
End Function

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

MySQL: Fastest way to count number of rows

A count(*) statement with a where condition on the primary key returned the row count much faster for me avoiding full table scan.

SELECT COUNT(*) FROM ... WHERE <PRIMARY_KEY> IS NOT NULL;

This was much faster for me than

SELECT COUNT(*) FROM ...

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

CSS background image URL failing to load

Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:

background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");

Alternatively, you can try to use file:/// protocol prefix.

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

The number of method references in a .dex file cannot exceed 64k API 17

In android/app/build.gradle

android {

compileSdkVersion 23

 buildToolsVersion '23.0.0'

    defaultConfig {
        applicationId "com.dkm.example"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }

Put this inside your defaultConfig:

multiDexEnabled true 

it works for me

How to completely remove Python from a Windows machine?

Run ASSOC and FTYPE to see what your py files are associated to. (These commands are internal to cmd.exe so if you use a different command processor ymmv.)

C:> assoc .py
.py=Python.File

C:> ftype Python.File
Python.File="C:\Python26.w64\python.exe" "%1" %*

C:> assoc .pyw
.pyw=Python.NoConFile

C:> ftype Python.NoConFile
Python.NoConFile="C:\Python26.w64\pythonw.exe" "%1" %*

(I have both 32- and 64-bit installs of Python, hence my local directory name.)

How to make a input field readonly with JavaScript?

Here you have example how to set the readonly attribute:

_x000D_
_x000D_
<form action="demo_form.asp">_x000D_
  Country: <input type="text" name="country" value="Norway" readonly><br>_x000D_
  <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Static method in a generic class?

When you specify a generic type for your class, JVM know about it only having an instance of your class, not definition. Each definition has only parametrized type.

Generics work like templates in C++, so you should first instantiate your class, then use the function with the type being specified.

High-precision clock in Python

The original question specifically asked for Unix but multiple answers have touched on Windows, and as a result there is misleading information on windows. The default timer resolution on windows is 15.6ms you can verify here.

Using a slightly modified script from cod3monk3y I can show that windows timer resolution is ~15milliseconds by default. I'm using a tool available here to modify the resolution.

Script:

import time

# measure the smallest time delta by spinning until the time changes
def measure():
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    return t1-t0

samples = [measure() for i in range(30)]

for s in samples:
    print(f'time delta: {s:.4f} seconds') 

enter image description here

enter image description here

These results were gathered on windows 10 pro 64-bit running python 3.7 64-bit.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

ORA-01861: literal does not match format string

The error means that you tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.

One of these formats is incorrect:

TO_CHAR(t.alarm_datetime, 'YYYY-MM-DD HH24:MI:SS')
TO_DATE(alarm_datetime, 'DD.MM.YYYY HH24:MI:SS')

How to get line count of a large file cheaply in Python?

I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (opcount); a simple iteration over the lines in the file (simplecount); readline with a memory-mapped filed (mmap) (mapcount); and the buffer read solution offered by Mykola Kharechko (bufcount).

I ran each function five times, and calculated the average run-time for a 1.2 million-line text file.

Windows XP, Python 2.5, 2GB RAM, 2 GHz AMD processor

Here are my results:

mapcount : 0.465599966049
simplecount : 0.756399965286
bufcount : 0.546800041199
opcount : 0.718600034714

Edit: numbers for Python 2.6:

mapcount : 0.471799945831
simplecount : 0.634400033951
bufcount : 0.468800067902
opcount : 0.602999973297

So the buffer read strategy seems to be the fastest for Windows/Python 2.6

Here is the code:

from __future__ import with_statement
import time
import mmap
import random
from collections import defaultdict

def mapcount(filename):
    f = open(filename, "r+")
    buf = mmap.mmap(f.fileno(), 0)
    lines = 0
    readline = buf.readline
    while readline():
        lines += 1
    return lines

def simplecount(filename):
    lines = 0
    for line in open(filename):
        lines += 1
    return lines

def bufcount(filename):
    f = open(filename)                  
    lines = 0
    buf_size = 1024 * 1024
    read_f = f.read # loop optimization

    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)

    return lines

def opcount(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1


counts = defaultdict(list)

for i in range(5):
    for func in [mapcount, simplecount, bufcount, opcount]:
        start_time = time.time()
        assert func("big_file.txt") == 1209138
        counts[func].append(time.time() - start_time)

for key, vals in counts.items():
    print key.__name__, ":", sum(vals) / float(len(vals))

Why shouldn't I use "Hungarian Notation"?

Hungarian notation only makes sense in languages without user-defined types. In a modern functional or OO-language, you would encode information about the "kind" of value into the datatype or class rather than into the variable name.

Several answers reference Joels article. Note however that his example is in VBScript, which didn't support user-defined classes (for a long time at least). In a language with user-defined types you would solve the same problem by creating a HtmlEncodedString-type and then let the Write method accept only that. In a statically typed language, the compiler will catch any encoding-errors, in a dynamically typed you would get a runtime exception - but in any case you are protected against writing unencoded strings. Hungarian notations just turns the programmer into a human type-checker, with is the kind of job that is typically better handled by software.

Joel distinguishes between "systems hungarian" and "apps hungarian", where "systems hungarian" encodes the built-in types like int, float and so on, and "apps hungarian" encodes "kinds", which is higher-level meta-info about variable beyound the machine type, In a OO or modern functional language you can create user-defined types, so there is no distinction between type and "kind" in this sense - both can be represented by the type system - and "apps" hungarian is just as redundant as "systems" hungarian.

So to answer your question: Systems hungarian would only be useful in a unsafe, weakly typed language where e.g. assigning a float value to an int variable will crash the system. Hungarian notation was specifically invented in the sixties for use in BCPL, a pretty low-level language which didn't do any type checking at all. I dont think any language in general use today have this problem, but the notation lived on as a kind of cargo cult programming.

Apps hungarian will make sense if you are working with a language without user defined types, like legacy VBScript or early versions of VB. Perhaps also early versions of Perl and PHP. Again, using it in a modern languge is pure cargo cult.

In any other language, hungarian is just ugly, redundant and fragile. It repeats information already known from the type system, and you should not repeat yourself. Use a descriptive name for the variable that describes the intent of this specific instance of the type. Use the type system to encode invariants and meta info about "kinds" or "classes" of variables - ie. types.

The general point of Joels article - to have wrong code look wrong - is a very good principle. However an even better protection against bugs is to - when at all possible - have wrong code to be detected automatically by the compiler.

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

How to declare a global variable in a .js file

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

Why use Gradle instead of Ant or Maven?

We use Gradle and chose it over Maven and Ant. Ant gave us total flexibility, and Ivy gives better dependency management than Maven, but there isn't great support for multi-project builds. You end up doing a lot of coding to support multi-project builds. Also having some build-by-convention is nice and makes build scripts more concise. With Maven, it takes build by convention too far, and customizing your build process becomes a hack. Also, Maven promotes every project publishing an artifact. Sometimes you have a project split up into subprojects but you want all of the subprojects to be built and versioned together. Not really something Maven is designed for.

With Gradle you can have the flexibility of Ant and build by convention of Maven. For example, it is trivial to extend the conventional build lifecycle with your own task. And you aren't forced to use a convention if you don't want to. Groovy is much nicer to code than XML. In Gradle, you can define dependencies between projects on the local file system without the need to publish artifacts for each to a repository. Finally, Gradle uses Ivy, so it has excellent dependency management. The only real downside for me thus far is the lack of mature Eclipse integration, but the options for Maven aren't really much better.

Beamer: How to show images as step-by-step images

I found a solution to my problem, by using the visble-command.

EDITED:

\visible<2->{
   \textbf{Some text}
   \begin{figure}[ht]
       \includegraphics[width=5cm]{./path/to/image}
    \end{figure}
 }

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

The real behavior of a sticky element is:

  • First it is relative for a while
  • then it is fixed for a while
  • finally, it disappears from the view

A stickily positioned element is treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor.

This example will help you understand:

code https://codepen.io/darylljann/pen/PpjwPM

C - determine if a number is prime

Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.

By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.

public bool IsPrimeNumber(int val) {
    // Using Sieve of Eratosthenes.
    if (val < 2)
    {
        return false;
    }

    // Reserve place for val + 1 and set with true.
    var mark = new bool[val + 1];
    for(var i = 2; i <= val; i++)
    {
        mark[i] = true;
    }

    // Iterate from 2 ... sqrt(val).
    for (var i = 2; i <= Math.Sqrt(val); i++)
    {
        if (mark[i])
        {
            // Cross out every i-th number in the places after i (all the multiples of i).
            for (var j = (i * i); j <= val; j += i)
            {
                mark[j] = false;
            }
        }
    }

    return mark[val];
}

IsPrimeNumber(1000000000) takes 21s 758ms.

NOTE: Value might vary depend on hardware specifications.

How do you modify a CSS style in the code behind file for divs in ASP.NET?

If you're newing up an element with initializer syntax, you can do something like this:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Attributes = { ["style"] = "min-width: 35px;" }
    },
  }
};

Or if using the CssStyleCollection specifically:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};

In Python, how to display current time in readable format

By using this code, you'll get your live time zone.

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Test whether string is a valid integer

Wow... there are so many good solutions here!! Of all the solutions above, I agree with @nortally that using the -eq one liner is the coolest.

I am running GNU bash, version 4.1.5 (Debian). I have also checked this on ksh (SunSO 5.10).

Here is my version of checking if $1 is an integer or not:

if [ "$1" -eq "$1" ] 2>/dev/null
then
    echo "$1 is an integer !!"
else
    echo "ERROR: first parameter must be an integer."
    echo $USAGE
    exit 1
fi

This approach also accounts for negative numbers, which some of the other solutions will have a faulty negative result, and it will allow a prefix of "+" (e.g. +30) which obviously is an integer.

Results:

$ int_check.sh 123
123 is an integer !!

$ int_check.sh 123+
ERROR: first parameter must be an integer.

$ int_check.sh -123
-123 is an integer !!

$ int_check.sh +30
+30 is an integer !!

$ int_check.sh -123c
ERROR: first parameter must be an integer.

$ int_check.sh 123c
ERROR: first parameter must be an integer.

$ int_check.sh c123
ERROR: first parameter must be an integer.

The solution provided by Ignacio Vazquez-Abrams was also very neat (if you like regex) after it was explained. However, it does not handle positive numbers with the + prefix, but it can easily be fixed as below:

[[ $var =~ ^[-+]?[0-9]+$ ]]

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

just remove:

Alias /phpmyadmin "C:/xampp2/phpMyAdmin/"
<Directory "C:/xampp2/phpMyAdmin">
    AllowOverride AuthConfig
    Require all granted
</Directory>

and remove phpmyadmin from:

<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|server-status|server-info))">

Angular Directive refresh on parameter change

I hope this will help reloading/refreshing directive on value from parent scope

<html>

        <head>
            <!-- version 1.4.5 -->
            <script src="angular.js"></script>
        </head>

        <body ng-app="app" ng-controller="Ctrl">

            <my-test reload-on="update"></my-test><br>
            <button ng-click="update = update+1;">update {{update}}</button>
        </body>
        <script>
            var app = angular.module('app', [])
            app.controller('Ctrl', function($scope) {

                $scope.update = 0;
            });
            app.directive('myTest', function() {
                return {
                    restrict: 'AE',
                    scope: {
                        reloadOn: '='
                    },
                    controller: function($scope) {
                        $scope.$watch('reloadOn', function(newVal, oldVal) {
                            //  all directive code here
                            console.log("Reloaded successfully......" + $scope.reloadOn);
                        });
                    },
                    template: '<span>  {{reloadOn}} </span>'
                }
            });
        </script>


   </html>

How to comment out a block of Python code in Vim

one way manually

:set number
:10,12s/^/#

How do I import CSV file into a MySQL table?

How to import csv files to sql tables

Example file: Overseas_trade_index data CSV File

Steps:

  1. Need to create table for overseas_trade_index.

  2. Need to create columns related to csv file.

    SQL Query:

    ( id int not null primary key auto_increment,
    series_reference varchar (60),
    period varchar (60),
    data_value decimal(60,0),
    status varchar (60),
    units varchar (60),
    magnitude int(60),
    subject text(60),
    group text(60),
    series_title_1 varchar (60),
    series_title_2 varchar (60),
    series_title_3 varchar (60),
    series_title_4 varchar (60),
    series_title_5 varchar (60),
     );
    
  3. Need to connect mysql database in terminal.

    =>show databases;
    =>use database;
    =>show tables;
    
  4. Please enter this command to import the csv data to mysql tables.

    load data infile '/home/desktop/Documents/overseas.csv' into table trade_index fields terminated by ',' lines terminated by '\n' (series_reference,period,data_value,status,units,magnitude,subject,series_title1,series_title_2,series_title_3,series_title_4,series_title_5);
    
  5. Find this overseas trade index data on sqldatabase:

    select * from trade_index;
    

Gradle: Execution failed for task ':processDebugManifest'

In a general way, to see what is the error, you can see the merged Manifest File in Android studio

Go on your manifest file

enter image description here

Click on the bottom tab "Merged Manifest"

enter image description here

On the right screen, in "Other Manifest Files", check for any error due to graddle :

enter image description here

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Try to migrate your database. For instance, if you are using Heroku to host your project and with Django, then try heroku run python manage.py migrate command; the error should go away.

Finding CN of users in Active Directory

Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:

cn=admin,cn=users,DC=domain,DC=company,DC=com

Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin). If so, you should get the full DN back in that query.

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

How to insert a newline in front of a pattern?

On my mac, the following inserts a single 'n' instead of newline:

sed 's/regexp/\n&/g'

This replaces with newline:

sed "s/regexp/\\`echo -e '\n\r'`/g"

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

What is the difference between `new Object()` and object literal notation?

Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

Here is an example of creating an object using constructor function (see code explanation at the bottom):

function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

Person.prototype.fullname = function() {
    console.log(this.firstname + ' ' + this.lastname);
}

var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');

zubaer.fullname();
john.fullname();

Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

var zubaer = {
    firstname: 'Zubaer',
    lastname: 'Ahammed',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

var john= {
    firstname: 'John',
    lastname: 'Doe',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

zubaer.fullname();
john.fullname();

At last, if you now ask why should I use constructor function approach instead of object literal approach:

*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

I hope this makes sense.

How to load up CSS files using Javascript?

If you want to know (or wait) until the style itself has loaded this works:

// this will work in IE 10, 11 and Safari/Chrome/Firefox/Edge
// add ES6 poly-fill for the Promise, if needed (or rewrite to use a callback)

let fetchStyle = function(url) {
  return new Promise((resolve, reject) => {
    let link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.onload = function() { resolve(); console.log('style has loaded'); };
    link.href = url;

    let headScript = document.querySelector('script');
    headScript.parentNode.insertBefore(link, headScript);
  });
};

How to locate the php.ini file (xampp)

step1 :open xampp control panel

step 2: then click apache module config button.

step 3. after that you able to see some config file list.

step 4: then click the php.ini file.it will be open into default editor.

image was given blow for refernce. enter image description here

How do you install an APK file in the Android emulator?

if use more than one emulator at firs use this command

adb devices

and then chose amulatur and install application

adb -s "EMULATOR NAME" install "FILE PATH"
adb -s emulator-5556 install C:\Users\criss\youwave\WhatsApp.apk

Install specific branch from github using Npm

I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:

"dependencies": {
  "<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}

Live Video Streaming with PHP

PHP/AJAX/MySQL will not be enough for creating the live video streaming application There is a similar thread here. It primarily suggests using Flex or Silverlight.

need to add a class to an element

You probably need something like:

result.className = 'red'; 

In pure JavaScript you should use className to deal with classes. jQuery has an abstraction called addClass for it.

CSS @font-face not working in ie

For IE > 9 you can use the following solution:

@font-face {
    font-family: OpenSansRegular;
    src: url('OpenSansRegular.ttf'), url('OpenSansRegular.eot');
}

Structure padding and packing

Rules for padding:

  1. Every member of the struct should be at an address divisible by its size. Padding is inserted between elements or at the end of the struct to make sure this rule is met. This is done for easier and more efficient Bus access by the hardware.
  2. Padding at the end of the struct is decided based on the size of the largest member of the struct.

Why Rule 2: Consider the following struct,

Struct 1

If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:

Struct1 array

Therefore, size of struct = 8 bytes

Assume we were to create another struct as below:

Struct 2

If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.

A. If we add 3 bytes at the end and align it for int and not Long:

Struct2 array aligned to int

B. If we add 7 bytes at the end and align it for Long:

Struct2 array aligned to Long

The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes

Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.

adding to window.onload event?

If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready() don't overwrite each other, but rather execute in turn:

$(document).ready(func1)
...
$(document).ready(func2)

If you are not using jQuery, you could use addEventListener, as demonstrated by Karaxuna, plus attachEvent for IE<9.

Note that onload is not equivalent to $(document).ready() - the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded event on the document, which corresponds to the jQuery ready event, but IE<9 does not.

if(window.addEventListener){
  window.addEventListener('load', func1)
}else{
  window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
  window.addEventListener('load', func2)
}else{
  window.attachEvent('onload', func2)
}

If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload as an example, but other options are available for onload):

var oldOnload1=window.onload;
window.onload=function(){
  oldOnload1 && oldOnload1();
  func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
  oldOnload2 && oldOnload2();
  func2();
}

or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:

window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func1();
  }
})(window.onload)
...
window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func2();
  }
})(window.onload)

CSS: How to align vertically a "label" and "input" inside a "div"?

This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label

label{
     display: block; 
     height: 35px; 
     line-height: 35px; 
     border: 1px solid #000; 
}

input{margin-top:15px; height:20px}

<label for="name">Name: <input type="text" id="name" /></label>

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

Resize image proportionally with CSS?

Try this:

div.container {
    max-width: 200px;//real picture size
    max-height: 100px;
}

/* resize images */
div.container img {
    width: 100%;
    height: auto;
}

cursor.fetchall() vs list(cursor) in Python

list(cursor) works because a cursor is an iterable; you can also use cursor in a loop:

for row in cursor:
    # ...

A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall() has to return the full list instead.

There is little point in using list(cursor) over cursor.fetchall(); the end effect is then indeed the same, but you wasted an opportunity to stream results instead.

Re-doing a reverted merge in Git

Let's assume you have such history

---o---o---o---M---W---x-------x-------*
              /                      
      ---A---B

Where A, B failed commits and W - is revert of M

So before I start fixing found problems I do cherry-pick of W commit to my branch

git cherry-pick -x W

Then I revert W commit on my branch

git revert W 

After I can continue fixing.

The final history could look like:

---o---o---o---M---W---x-------x-------*
              /                       /     
      ---A---B---W---W`----------C---D

When I send a PR it will clearly shows that PR is undo revert and adds some new commits.

JavaScript checking for null vs. undefined and difference between == and ===

Ad 1. null is not an identifier for a property of the global object, like undefined can be

_x000D_
_x000D_
let x;      // undefined_x000D_
let y=null; // null_x000D_
let z=3;    // has value_x000D_
// 'w'      // is undeclared_x000D_
_x000D_
if(!x) console.log('x is null or undefined');_x000D_
if(!y) console.log('y is null or undefined');_x000D_
if(!z) console.log('z is null or undefined');_x000D_
_x000D_
try { if(w) 0 } catch(e) { console.log('w is undeclared') }_x000D_
// typeof not throw exception for undelared variabels_x000D_
if(typeof w === 'undefined') console.log('w is undefined');
_x000D_
_x000D_
_x000D_

Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

How to find the last field using 'cut'

If you have a file named filelist.txt that is a list paths such as the following: c:/dir1/dir2/file1.h c:/dir1/dir2/dir3/file2.h

then you can do this: rev filelist.txt | cut -d"/" -f1 | rev

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

How to add a button dynamically in Android?

Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");


LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
 myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(DynamicLayout.this,
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

Textarea that can do syntax highlighting on the fly?

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

_x000D_
_x000D_
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');


var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');
  }

  return text;
}

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);
  $highlights.html(highlightedText);
}

function handleScroll() {
  var scrollTop = $textarea.scrollTop();
  $backdrop.scrollTop(scrollTop);

  var scrollLeft = $textarea.scrollLeft();
  $backdrop.scrollLeft(scrollLeft);
}

function fixIOS() {
  $highlights.css({
    'padding-left': '+=3px',
    'padding-right': '+=3px'
  });
}

function bindEvents() {
  $textarea.on({
    'input': handleInput,
    'scroll': handleScroll
  });
}

if (isIOS) {
  fixIOS();
}

bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;
}

.container,
.backdrop,
textarea {
  width: 460px;
  height: 180px;
}

.highlights,
textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;
}

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;
}

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;
}

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;
}

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;
}

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  </div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
_x000D_
_x000D_

Original Pen: https://codepen.io/lonekorean/pen/gaLEMR

Default interface methods are only supported starting with Android N

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


android {
compileSdkVersion 30
buildToolsVersion "30.0.0"

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
    applicationId "com.example.architecture"
    minSdkVersion 16
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
   }
}
dependencies {

implementation 'androidx.room:room-runtime:2.2.5'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"

implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
implementation "androidx.cardview:cardview:1.0.0"
}

Add the configuration in your app module's build.gradle

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Creating an R dataframe row-by-row

If you have vectors destined to become rows, concatenate them using c(), pass them to a matrix row-by-row, and convert that matrix to a dataframe.

For example, rows

dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)

can be converted to a data frame thus:

dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))

Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).

This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?

How to solve maven 2.6 resource plugin dependency?

If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).

To fix this you can either

  • Clear (parts of) your .m2 repo
  • Run maven with -U to force an update

Prevent overwriting a file using cmd if exist

I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...

CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"

two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...

start \\filer\repo\lab\"software"\"myapp"\setup.exe

the start code here, can be set up like that, but the correct syntax is

start "\\filter\repo\lab\software\myapp\" setup.exe

This will run: setup.exe, located in: \filter\repo\lab...etc.\

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

How to trigger a build only if changes happen on particular set of files

Basically, you need two jobs. One to check whether files changed and one to do the actual build:

Job #1

This should be triggered on changes in your Git repository. It then tests whether the path you specify ("src" here) has changes and then uses Jenkins' CLI to trigger a second job.

export JENKINS_CLI="java -jar /var/run/jenkins/war/WEB-INF/jenkins-cli.jar"
export JENKINS_URL=http://localhost:8080/
export GIT_REVISION=`git rev-parse HEAD`
export STATUSFILE=$WORKSPACE/status_$BUILD_ID.txt

# Figure out, whether "src" has changed in the last commit
git diff-tree --name-only HEAD | grep src

# Exit with success if it didn't
$? || exit 0

# Trigger second job
$JENKINS_CLI build job2 -p GIT_REVISION=$GIT_REVISION -s

Job #2

Configure this job to take a parameter GIT_REVISION like so, to make sure you're building exactly the revision the first job chose to build.

Parameterized build string parameter Parameterized build Git checkout

How to get a List<string> collection of values from app.config in WPF?

You could have them semi-colon delimited in a single value, e.g.

App.config

<add key="paths" value="C:\test1;C:\test2;C:\test3" />

C#

var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));

How to increase heap size of an android application?

You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.

The only way to have as large a limit as possible is to do memory intensive tasks via the NDK, as the NDK does not impose memory limits like the SDK.

Alternatively, you could only load the part of the model that is currently in view, and load the rest as you need it, while removing the unused parts from memory. However, this may not be possible, depending on your app.

Pandas - How to flatten a hierarchical index in columns

Following @jxstanford and @tvt173, I wrote a quick function which should do the trick, regardless of string/int column names:

def flatten_cols(df):
    df.columns = [
        '_'.join(tuple(map(str, t))).rstrip('_') 
        for t in df.columns.values
        ]
    return df

Scripting SQL Server permissions

Yes, you can use a script like this to generate another script

SET NOCOUNT ON;
DECLARE @NewRole varchar(100), @SourceRole varchar(100);

-- Change as needed
SELECT @SourceRole = 'Giver', @NewRole = 'Taker';

SELECT
    state_desc + ' ' + permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + @NewRole
FROM
    sys.database_permissions
WHERE
    grantee_principal_id = DATABASE_PRINCIPAL_ID(@SourceRole) AND
    -- 0 = DB,  1 = object/column, 3 = schema. 1 is normally enough
    class <= 3

This is taken from my answer here

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

How to show a GUI message box from a bash script in linux?

The zenity application appears to be what you are looking for.

To take input from zenity, you can specify a variable and have the output of zenity --entry saved to it. It looks something like this:

my_variable=$(zenity --entry)

If you look at the value in my_variable now, it will be whatever was typed in the zenity pop up entry dialog.

If you want to give some sort of prompt as to what the user (or you) should enter in the dialog, add the --text switch with the label that you want. It looks something like this:

my_variable=$(zenity --entry --text="What's my variable:")

Zenity has lot of other nice options that are for specific tasks, so you might want to check those out as well with zenity --help. One example is the --calendar option that let's you select a date from a graphical calendar.

my_date=$(zenity --calendar)

Which gives a nicely formatted date based on what the user clicked on:

echo ${my_date}

gives:

08/05/2009

There are also options for slider selectors, errors, lists and so on.

Hope this helps.

How to run VBScript from command line without Cscript/Wscript

When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by

assoc | grep -i vbs
.vbs=VBSFile

ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.

As

cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]

Options:
 //B         Batch mode: Suppresses script errors and prompts from displaying
 //D         Enable Active Debugging
 //E:engine  Use engine for executing script
 //H:CScript Changes the default script host to CScript.exe
 //H:WScript Changes the default script host to WScript.exe (default)
 //I         Interactive mode (default, opposite of //B)
 //Job:xxxx  Execute a WSF job
 //Logo      Display logo (default)
 //Nologo    Prevent logo display: No banner will be shown at execution time
 //S         Save current command line options for this user
 //T:nn      Time out in seconds:  Maximum time a script is permitted to run
 //X         Execute script in debugger
 //U         Use Unicode for redirected I/O from the console

shows, you can use //E and //S to permanently switch your default host to cscript.exe.

If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable

set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1

contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.

Update wrt comment:

If you 'don't want to specify the full path of my vbscript everytime' you may:

  1. put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
  2. put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS

In both cases I would type out the extension to avoid (nasty) surprises.

commons httpclient - Adding query string parameters to GET/POST request

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

Here is a more flexible solution. Crude but can be refined.

public static void main(String[] args) {

    String host = "localhost";
    String port = "9093";

    String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
    String[] wholeString = param.split("\\?");
    String theQueryString = wholeString.length > 1 ? wholeString[1] : "";

    String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";

    GetMethod method = new GetMethod(SolrUrl );

    if (theQueryString.equalsIgnoreCase("")) {
        method.setQueryString(new NameValuePair[]{
        });
    } else {
        String[] paramKeyValuesArray = theQueryString.split("&");
        List<String> list = Arrays.asList(paramKeyValuesArray);
        List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
        for (String s : list) {
            String[] nvPair = s.split("=");
            String theKey = nvPair[0];
            String theValue = nvPair[1];
            NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
            nvPairList.add(nameValuePair);
        }
        NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
        nvPairList.toArray(nvPairArray);
        method.setQueryString(nvPairArray);       // Encoding is taken care of here by setQueryString

    }
}

How can I get list of values from dict?

You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

java Arrays.sort 2d array

To sort in descending order you can flip the two parameters

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (b, a) -> Integer.compare(a[0], b[0]));

Output:

13, 5
12, 100
12, 85
1, 5

Submit form without page reloading

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

Converting List<String> to String[] in Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

Fast Bitmap Blur For Android SDK

Nicolas POMEPUY advice. I think this link will be helpful: Blur effect for Android design

Sample project at github

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private static Bitmap fastblur16(Bitmap source, int radius, Context ctx) {    
    Bitmap bitmap = source.copy(source.getConfig(), true);    
    RenderScript rs = RenderScript.create(ctx);
    Allocation input = Allocation.createFromBitmap(rs, source, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    Allocation output = Allocation.createTyped(rs, input.getType());
    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setRadius(radius);
    script.setInput(input);
    script.forEach(output);
    output.copyTo(bitmap);
    return bitmap;
}

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

change PATH permanently on Ubuntu

Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Replace last occurrence of a string in a string

A short version:

$NewString = substr_replace($String,$Replacement,strrpos($String,$Replace),strlen($Replace));

What is String pool in Java?

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

.NET NewtonSoft JSON deserialize map to a different property name

Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).

public class PropertyFilterResolver : DefaultContractResolver
{
  const string _Err = "A type can be either in the include list or the ignore list.";
  Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null) return this;

    if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IgnorePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null)
      return this;

    if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IncludePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
  {
    var properties = base.CreateProperties(type, memberSerialization);

    var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
    if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
      return properties;

    Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
    return properties.Where(predicate).ToArray();
  }

  string GetPropertyName<TSource, TProperty>(
  Expression<Func<TSource, TProperty>> propertyLambda)
  {
    if (!(propertyLambda.Body is MemberExpression member))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");

    if (!(member.Member is PropertyInfo propInfo))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");

    var type = typeof(TSource);
    if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
      throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");

    return propInfo.Name;
  }
}

Usage:

var resolver = new PropertyFilterResolver()
  .SetIncludedProperties<User>(
    u => u.Id, 
    u => u.UnitId)
  .SetIgnoredProperties<Person>(
    r => r.Responders)
  .SetIncludedProperties<Blog>(
    b => b.Id)
  .Ignore(nameof(IChangeTracking.IsChanged)); //see gist

What is the difference between Jupyter Notebook and JupyterLab?

(I am using JupyterLab with Julia)

First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.

Major features that are great is

  • the drag and drop of cells so that you can easily rearrange the code
  • collapsing cells with a single mouse click and a small mark to remind of their placement

What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.

(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)

Build android release apk on Phonegap 3.x CLI

Building PhoneGap Android app for deployment to the Google Play Store

These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova is placed, replace it with phonegap or ionic, for your particular scenario.

Once you are done with the development and are ready to deploy, follow these steps:

  1. Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).

  2. Head over to the /path/to/your/project/, which we would refer to as the Project Root.

  3. While at the project root, remove the "Console" plugin from your set of plugins.

    The command is: cordova plugin rm cordova-plugin-console

  4. While still at the project root, use the cordova build command to create an APK for release distribution.

    The command is: cordova build --release android

  5. The above process creates a file called android-release-unsigned.apk in the folder ProjectRoot/platforms/android/build/outputs/apk/

  6. Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually

    At the end of this step the APK which you get can be uploaded to the Play Store.

Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.

Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.

Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.

Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?

The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/. If you head over to the folder you would find a bunch of other folders like docs, platform-tools, build-tools, tools, add-ons...

Open the build-tools folder. cd build-tools. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.

On macOS or Linux you may have to use ./zipalign rather than simply typing in zipalign as the documentation mentions. On Windows, zipalign is good enough.

How to declare a variable in SQL Server and use it in the same Stored Procedure

What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

I can see the following issues with that SP, which may or may not relate to your problem:

  • You have an extraneous ) after @BrandName in your SELECT (at the end)
  • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

CREATE PROCEDURE AddBrand
   @BrandName nvarchar(50),
   @CategoryID int
AS
BEGIN
   DECLARE @BrandID int

   SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName

   INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END

You would then call this like this:

EXEC AddBrand 'Gucci', 23

...assuming the brand name was 'Gucci' and category ID was 23.

Catching an exception while using a Python 'with' statement

The best "Pythonic" way to do this, exploiting the with statement, is listed as Example #6 in PEP 343, which gives the background of the statement.

@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError, err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()

Used as follows:

with opened_w_error("/etc/passwd", "a") as (f, err):
    if err:
        print "IOError:", err
    else:
        f.write("guido::0:0::/:/bin/sh\n")

Create an ArrayList with multiple object types?

I am also newish to Java and just figured this out. You should create your own class which stores the string and integer, and then make a list of these objects. For instance (I am sure this code is imperfect, but better than arrayList):

class Stuff {
    private String label;
    private Integer value;

    // Constructor or setter
    public void Stuff(String label, Integer value) {
        if (label == null || value == null) {
            return;
        }
        this.label = label;
        this.value = value;
    }

    // getters

    public String getLabel() {
        return this.label;
    }

    public Integer getValue() {
        return this.value;
    }
}

Then in your code:

private ArrayList<Stuff> items = new ArrayList<Stuff>();
items.add(new Stuff(label, value));

for (Stuff item: items) {
     doSomething(item.getLabel()); // returns String
     doSomething(item.getValue()); // returns Integer
}

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

INNER JOIN same table

Perhaps this should be the select (if I understand the question correctly)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

Is it possible to cast a Stream in Java 8?

This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object> to a Stream<Client>?

No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object> is not a super type of List<String>, so you can't just cast a List<Object> to a List<String>.

Similar is the issue here. You can't cast Stream<Object> to Stream<Client>. Of course you can cast it indirectly like this:

Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;

but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream it is at runtime. Everything is just Stream.

BTW, what's wrong with your approach? Looks fine to me.

How do I keep the screen on in my App?

You can simply use setKeepScreenOn() from the View class.

Angular2 multiple router-outlet in the same template

yes you can, but you need to use aux routing. you will need to give a name to your router-outlet:

<router-outlet name="auxPathName"></router-outlet>

and setup your route config:

@RouteConfig([
  {path:'/', name: 'RetularPath', component: OneComponent, useAsDefault: true},
  {aux:'/auxRoute', name: 'AuxPath', component: SecondComponent}
])

Check out this example, and also this video.


Update for RC.5 Aux routes has changed a bit: in your router outlet use a name:

<router-outlet name="aux">

In your router config:

{path: '/auxRouter', component: secondComponentComponent, outlet: 'aux'}

Get URL of ASP.Net Page in code-behind

I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] "no-reply@" + BaseSiteUrl Works fine on any site.

// get a sites base urll ex: example.com
public static string BaseSiteUrl
{
    get
    {
        HttpContext context = HttpContext.Current;
        string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
        return baseUrl;
    }

}

If you want to use it in codebehind get rid of context.

Encrypt Password in Configuration Files?

I think that the best approach is to ensure that your config file (containing your password) is only accessible to a specific user account. For example, you might have an application specific user appuser to which only trusted people have the password (and to which they su to).

That way, there's no annoying cryptography overhead and you still have a password which is secure.

EDIT: I am assuming that you are not exporting your application configuration outside of a trusted environment (which I'm not sure would make any sense, given the question)

How do I turn off the mysql password validation?

For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html

Then you should edit your mysqld.cnf file, for instance :

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Then, add in the [mysqld] part, the following :

plugin-load-add=validate_password.so
validate_password_policy=LOW

Basically, if you edit your default, it will looks like :

[mysqld]
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW

Then, you can restart:

systemctl restart mysql

If you forget the plugin-load-add=validate_password.so part, you will it an error at restart.

Enjoy !

updating table rows in postgres using subquery

You're after the UPDATE FROM syntax.

UPDATE 
  table T1  
SET 
  column1 = T2.column1 
FROM 
  table T2 
  INNER JOIN table T3 USING (column2) 
WHERE 
  T1.column2 = T2.column2;

References

how to have two headings on the same line in html

The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.

The HTML Part:

<h1 class="text-left-right">
    <span class="left-text">Heading Goes Here</span>
    <span class="byline">Byline here</span>
</h1>

And the CSS:

.text-left-right {
    text-align: right;
    position: relative;
}
.left-text {
    left: 0;
    position: absolute;
}
.byline {
    font-size: 16px;
    color: rgba(140, 140, 140, 1);
}

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

What is external linkage and internal linkage?

When you write an implementation file (.cpp, .cxx, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #included in it.

Internal linkage refers to everything only in scope of a translation unit.

External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).

Fixed GridView Header with horizontal and vertical scrolling in asp.net

<script type="text/javascript">
        $(document).ready(function () {
            var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
            $(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
            $('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
                // Here Set Width of each th from gridview to new table(clone table) th 
                $("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
            });
            $("#GHead1").append(gridHeader);
            $('#GHead1').css('position', 'top');
            $('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);

        });
    </script>

<div class="row">
                                                        <div class="col-lg-12" style="width: auto;">
                                                            <div id="GHead1"></div>
                                                            <div id="divGridViewScroll1" style="height: 600px; overflow: auto">
                                                                <div class="table-responsive">
                                                                    <asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
                                                                        BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">

                                                                        <Columns>
                                                                        </Columns>
                                                                        <HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
                                                                        <RowStyle Font-Names="Calibri" ForeColor="#000000" />
                                                                    </asp:GridView>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>

Connecting to MySQL from Android with JDBC

try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8

Scroll to the top of the page using JavaScript?

Shortest

location='#'

This solution is improvement of pollirrata answer and have some drawback: no smooth scroll and change page location, but is shortest

What is the reason behind "non-static method cannot be referenced from a static context"?

if a method is not static, that "tells" the compiler that the method requires access to instance-level data in the class, (like a non-static field). This data would not be available unless an instance of the class has been created. So the compiler throws an error if you try to call the method from a static method.. If in fact the method does NOT reference any non-static member of the class, make the method static.

In Resharper, for example, just creating a non-static method that does NOT reference any static member of the class generates a warning message "This method can be made static"

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

Printing everything except the first field with awk

Another and easy way using cat command

cat filename | awk '{print $2,$3,$4,$5,$6,$1}' > newfilename

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

On my Mac r is installed in /usr/local/bin/r, add line below in .bash_profile solved the same problem:

alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"

Java 8 Lambda filter by Lists

Predicate<Client> hasSameNameAsOneUser = 
    c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));

return clients.stream()
              .filter(hasSameNameAsOneUser)
              .collect(Collectors.toList());

But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:

Set<String> acceptableNames = 
    users.stream()
         .map(User::getName)
         .collect(Collectors.toSet());

return clients.stream()
              .filter(c -> acceptableNames.contains(c.getName()))
              .collect(Collectors.toList());

Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.

iOS Detection of Screenshot?

Swift 4+

NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
           //you can do anything you want here. 
        }

by using this observer you can find out when user takes a screenshot, but you can not prevent him.

mysql delete under safe mode

Googling around, the popular answer seems to be "just turn off safe mode":

SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;

If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.

So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.

Quoting from the MySQL manual, Restrictions on Subqueries:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.

That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:

DELETE FROM instructor WHERE id IN (
  SELECT temp.id FROM (
    SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
  ) AS temp
);

SQLFiddle demo.

How to submit a form with JavaScript by clicking a link?

HTML & CSS - No Javascript Solution

Make your button appear like a Bootstrap link

HTML:

<form>
    <button class="btn-link">Submit</button>
</form>

CSS:

.btn-link {

    background: none;
    border: none;
    padding: 0px;
    color: #3097D1;
    font: inherit;

}

.btn-link:hover {

    color: #216a94;
    text-decoration: underline;

}

RecyclerView - Get view at particular position

You can make ArrayList of ViewHolder :

 ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
 ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();

and, all store ViewHolder(s) in the list like :

 @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        final String str = arrayList.get(position);

        myViewHolders.add(position,holder);
}

and add/remove other ViewHolder in the ArrayList as per your requirement.

How do I move a file from one location to another in Java?

Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

Read more about Files

How to check if AlarmManager already has an alarm set?

I have 2 alarms. I am using intent with extras instead of action to identify the events:

Intent i = new Intent(context, AppReciever.class);
i.putExtra("timer", "timer1");

the thing is that with diff extras the intent (and the alarm) wont be unique. So to able to identify which alarm is active or not, I had to define diff requestCode-s:

boolean alarmUp = (PendingIntent.getBroadcast(context, MyApp.TIMER_1, i, 
                    PendingIntent.FLAG_NO_CREATE) != null);

and here is how alarm was created:

public static final int TIMER_1 = 1;
public static final int TIMER_2 = 2;

PendingIntent pending = PendingIntent.getBroadcast(context, TIMER_1, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);
pending = PendingIntent.getBroadcast(context, TIMER_2, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);

“Unable to find manifest signing certificate in the certificate store” - even when add new key

I've finally found the solution and really hope this helps someone else too.

  1. Edit the .csproj file for the project in question.
  2. Delete the following lines of code:

    <PropertyGroup>
       <ManifestCertificateThumbprint>...........</ManifestCertificateThumbprint>
    </PropertyGroup>
    <PropertyGroup>
       <ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
    </PropertyGroup>
    <PropertyGroup>
       <GenerateManifests>true</GenerateManifests>
    </PropertyGroup>
    <PropertyGroup>
       <SignManifests>false</SignManifests>
    </PropertyGroup>
    

Converting int to bytes in Python 3

From bytes docs:

Accordingly, constructor arguments are interpreted as for bytearray().

Then, from bytearray docs:

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is an integer, the array will have that size and will be initialized with null bytes.

Note, that differs from 2.x (where x >= 6) behavior, where bytes is simply str:

>>> bytes is str
True

PEP 3112:

The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different.

How to view the contents of an Android APK file?

There is also zzos. (Full disclosure: I wrote it). It only decompiles the actual resources, not the dex part (baksmali, which I did not write, does an excellent job of handling that part).

Zzos is much less known than apktool, but there are some APKs that are better handled by it (and vice versa - more on that later). Mostly, APKs containing custom resource types (not modifiers) were not handled by apktool the last time I checked, and are handled by zzos. There are also some cases with escaping that zzos handles better.

On the negative side of things, zzos (current version) requires a few support tools to install. It is written in perl (as opposed to APKTool, which is written in Java), and uses aapt for the actual decompilation. It also does not decompile attrib resources yet (which APKTool does).

The meaning of the name is "aapt", Android's resource compiler, shifted down one letter.

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

Change output format for MySQL command line results to CSV

If you are using mysql client you can set up the resultFormat per session e.g.

mysql -h localhost -u root --resutl-format=json

or

mysql -h localhost -u root --vertical

Check out the full list of arguments here.

How can I enable cURL for an installed Ubuntu LAMP stack?

You don't have to give version numbers. Just run:

sudo apt-get install php-curl

It worked for me. Don't forgot to restart the server:

sudo service apache2 restart

Checking if a worksheet-based checkbox is checked

It seems that in VBA macro code for an ActiveX checkbox control you use

If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

and for a Form checkbox control you use

If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

How can I avoid running ActiveRecord callbacks?

# for rails 3
  if !ActiveRecord::Base.private_method_defined? :update_without_callbacks
    def update_without_callbacks
      attributes_with_values = arel_attributes_values(false, false, attribute_names)
      return false if attributes_with_values.empty?
      self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
    end
  end

AngularJS disable partial caching on dev machine

If you are using UI router then you can use a decorator and update $templateFactory service and append a query string parameter to templateUrl, and the browser will always load the new template from the server.

function configureTemplateFactory($provide) {
    // Set a suffix outside the decorator function 
    var cacheBust = Date.now().toString();

    function templateFactoryDecorator($delegate) {
        var fromUrl = angular.bind($delegate, $delegate.fromUrl);
        $delegate.fromUrl = function (url, params) {
            if (url !== null && angular.isDefined(url) && angular.isString(url)) {
                url += (url.indexOf("?") === -1 ? "?" : "&");
                url += "v=" + cacheBust;
            }

            return fromUrl(url, params);
        };

        return $delegate;
    }

    $provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}

app.config(['$provide', configureTemplateFactory]);

I am sure you can achieve the same result by decorating the "when" method in $routeProvider.

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Resize font-size according to div size

The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.

See this:Demo

For more details:Main tutorial

what is the use of fflush(stdin) in c programming

it clears stdin buffer before reading. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

Note: This is Linux-specific, using fflush() on input streams is undefined by the standard, however, most implementations behave the same as in Linux.

Angular File Upload

Very easy and fastest method is using ng2-file-upload.

Install ng2-file-upload via npm. npm i ng2-file-upload --save

At first import module in your module.

import { FileUploadModule } from 'ng2-file-upload';

Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]

Markup:

<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>

In your commponent ts:

import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });

It`is simplest usage of this. To know all power of this see demo

Failed to load the JNI shared Library (JDK)

Make sure your eclipse.ini file includes the following lines.

-vm
C:\path\to\64bit\java\bin\javaw.exe

My eclipse.ini for example:

-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.2.R36x_v20101222
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-vm
C:\Program Files\Java\jdk1.6.0_32\bin\javaw.exe
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

Use OS and Eclipse both 64 bit or both 32 bit keep same and config eclipse.ini.

Your eclipse.ini file can be found in your eclipse folder.

SQL Server Express CREATE DATABASE permission denied in database 'master'

What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:

$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

JAVA_HOME and PATH are set but java -version still shows the old one

check available Java versions on your Linux system by using update-alternatives command:

 $ sudo update-alternatives --display java

Now that there are suitable candidates to change to, you can switch the default Java version among available Java JREs by running the following command:

 $ sudo update-alternatives --config java

When prompted, select the Java version you would like to use.1 or 2 or 3 or etc..

Now you can verify the default Java version changed as follows.

 $ java -version

Add a border outside of a UIView (instead of inside)

Increase the width and height of view's frame with border width before adding the border:

float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
 self.layer.borderColor = [UIColor yellowColor].CGColor;
 self.layer.borderWidth = 2.0f;

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

All you have to do it insert you exact db details and restart your mysql server

How to Run Terminal as Administrator on Mac Pro

sudo dscl . -create /Users/joeadmin
sudo dscl . -create /Users/joeadmin UserShell /bin/bash
sudo dscl . -create /Users/joeadmin RealName "Joe Admin" 
sudo dscl . -create /Users/joeadmin UniqueID "510"
sudo dscl . -create /Users/joeadmin PrimaryGroupID 20
sudo dscl . -create /Users/joeadmin NFSHomeDirectory /Users/joeadmin
sudo dscl . -passwd /Users/joeadmin password 
sudo dscl . -append /Groups/admin GroupMembership joeadmin

press enter after every sentence

Then do a:

sudo reboot

Change joeadmin to whatever you want, but it has to be the same all the way through. You can also put a password of your choice after password.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

How to add a column in TSQL after a specific column?

Even if the question is old, a more accurate answer about Management Studio would be required.

You can create the column manually or with Management Studio. But Management Studio will require to recreate the table and will result in a time out if you have too much data in it already, avoid unless the table is light.

To change the order of the columns you simply need to move them around in Management Studio. This should not require (Exceptions most likely exists) that Management Studio to recreate the table since it most likely change the ordination of the columns in the table definitions.

I've done it this way on numerous occasion with tables that I could not add columns with the GUI because of the data in them. Then moved the columns around with the GUI of Management Studio and simply saved them.

You will go from an assured time out to a few seconds of waiting.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You need to define a class for the bullets you want to hide. For examples

.no-bullets {
    list-style-type: none;
}

Then apply it to the list you want hidden bullets:

<ul class="no-bullets">

All other lists (without a specific class) will show the bulltets as usual.

How to replace negative numbers in Pandas Data Frame by zero

Another clean option that I have found useful is pandas.DataFrame.mask which will "replace values where the condition is true."

Create the DataFrame:

In [2]: import pandas as pd

In [3]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [4]: df
Out[4]: 
   a  b
0  0 -3
1 -1  2
2  2  1

Replace negative numbers with 0:

In [5]: df.mask(df < 0, 0)
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

Or, replace negative numbers with NaN, which I frequently need:

In [7]: df.mask(df < 0)
Out[7]: 
     a    b
0  0.0  NaN
1  NaN  2.0
2  2.0  1.0

C++ int float casting

Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.

You'll want to cast the expressions to floats first before dividing, e.g.

float m = (float)(a.y - b.y) / (float)(a.x - b.x);

Converting A String To Hexadecimal In Java

All answers based on String.getBytes() involve encoding your string according to a Charset. You don't necessarily get the hex value of the 2-byte characters that make up your string. If what you actually want is the equivalent of a hex viewer, then you need to access the chars directly. Here's the function that I use in my code for debugging Unicode issues:

static String stringToHex(String string) {
  StringBuilder buf = new StringBuilder(200);
  for (char ch: string.toCharArray()) {
    if (buf.length() > 0)
      buf.append(' ');
    buf.append(String.format("%04x", (int) ch));
  }
  return buf.toString();
}

Then, stringToHex("testing123") will give you:

0074 0065 0073 0074 0069 006e 0067 0031 0032 0033

Returning the product of a list

import operator
reduce(operator.mul, list, 1)

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

DROP IF EXISTS VS DROP?

It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use

DROP TABLE IF EXISTS dbo.Table

For SQL Server <2016 what I do is the following for a permanent table

IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
  DROP TABLE dbo.Table; 

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
  DROP TABLE #T; 

Python one-line "for" expression

The keyword you're looking for is list comprehensions:

>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]

How to run html file on localhost?

On macOS:

Open Terminal (or iTerm) install Homebrew then run brew install live-server and run live-server.

You also can install Python 3 and run python3 -m http.server PORT.

On Windows:

If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.

Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get).

On Linux:

Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get).

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

Authentication issue when debugging in VS2013 - iis express

It appears that the right answer is provided by user3149240 above. However, As Neil Watson pointed out, the applicationhost.config file is at play here.

The changes can actually be made in the VS Property pane or in the file albeit in a different spot. Near the bottom of the applicationhost.config file is a set of location elements. Each app for IIS Express seems to have one of these. Changing the settings in the UI updates this section of the file. So, you can either change the settings through the UI or modify this file.

Here is an example with anonymous auth off and Windows auth on:

<location path="MyApp">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

This is equivalent in the VS UI to:

Anonymous Authentication: Disabled
Windows Authentication: Enabled

How to reset Android Studio

Windows Users: Look for C:->Users->YourUserName->.AndroidStudio or .AndroidStudioBeta folder. Delete that.

Mac Users: Delete these using the terminal (usage: rm -rf folderpath): ~/Library/Preferences/AndroidStudioBeta ~/Library/Application Support/AndroidStudioBeta ~/Library/Caches/AndroidStudioBeta ~/Library/Logs/AndroidStudioBeta

Linus Users: Delete these using the terminal (usage: rm -r folderpath): ~/.AndroidStudioBeta/config or ~/.AndroidStudio/config

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

In case you are using Eclipse you might try http4e

Validate form field only on submit or user input

Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

$scope.formName.elementName.$$element.change();

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};

c) and one more way for that

    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };

Is calling destructor manually always a sign of bad design?

I have never come across a situation where one needs to call a destructor manually. I seem to remember even Stroustrup claims it is bad practice.

css with background image without repeating the image

This is all you need:

background-repeat: no-repeat;

Send private messages to friends

Sending private message through api is now possible.

Fire this event for sending message(initialization of facebook object should be done before).

to:user id of facebook

function facebook_send_message(to) {
    FB.ui({
        app_id:'xxxxxxxx',
        method: 'send',
        name: "sdfds jj jjjsdj j j ",
        link: 'https://apps.facebook.com/xxxxxxxaxsa',
        to:to,
        description:'sdf sdf sfddsfdd s d  fsf s '

    });
}

Properties

  • app_id
    Your application's identifier. Required, but automatically specified by most SDKs.

  • redirect_uri
    The URL to redirect to after the user clicks the Send or Cancel buttons on the dialog. Required, but automatically specified by most SDKs.

  • display
    The display mode in which to render the dialog. This is automatically specified by most SDKs.

  • to
    A user ID or username to which to send the message. Once the dialog comes up, the user can specify additional users, Facebook groups, and email addresses to which to send the message. Sending content to a Facebook group will post it to the group's wall.

  • link
    (required) The link to send in the message.

  • picture
    By default a picture will be taken from the link specified. The URL of a picture to include in the message. The picture will be shown next to the link.

  • name By default a title will be taken from the link specified. The name of the link, i.e. the text to display that the user will click on.

  • description
    By default a description will be taken from the link specified. Descriptive text to show below the link.

See more here

@VishwaKumar:

For sending message with custom text, you have to add 'message' parameter to FB.ui, but I think this feature is deprecated. You can't pre-fill the message anymore. Though try once.

FB.ui({
  method: 'send',
  to: '1234',
  message: 'A request especially for one person.',
  data: 'tracking information for the user'
});

See this link: http://fbdevwiki.com/wiki/FB.ui

How to convert string to integer in PowerShell

Use:

$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} | 
  % {$newName = [string]([int]$($_[0]) + 1)}
  New-Item $newName -ItemType Directory

How to Create a circular progressbar in Android which rotates on it?

@Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml code to this:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="270"
    android:toDegrees="270">
    <shape
        android:innerRadiusRatio="2.5"
        android:shape="ring"
        android:thickness="1dp"
        android:useLevel="true"> <!-- Just add this line -->
        <gradient
            android:angle="0"
            android:endColor="#007DD6"
            android:startColor="#007DD6"
            android:type="sweep"
            android:useLevel="false" />
    </shape>
</rotate>

Create Table from JSON Data with angularjs and ng-repeat

Angular 2 or 4:

There's no more ng-repeat, it's *ngFor now in recent Angular versions!

<table style="padding: 20px; width: 60%;">
    <tr>
      <th  align="left">id</th>
      <th  align="left">status</th>
      <th  align="left">name</th>
    </tr>
    <tr *ngFor="let item of myJSONArray">
      <td>{{item.id}}</td>
      <td>{{item.status}}</td>
      <td>{{item.name}}</td>
    </tr>
</table>

Used this simple JSON:

[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]

jQuery DIV click, with anchors

$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });

Center an item with position: relative

Much simpler:

position: relative; 
left: 50%;
transform: translateX(-50%);

You are now centered in your parent element. You can do that vertically too.

What is a predicate in c#?

Predicate<T> is a functional construct providing a convenient way of basically testing if something is true of a given T object.

For example suppose I have a class:

class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

Now let's say I have a List<Person> people and I want to know if there's anyone named Oscar in the list.

Without using a Predicate<Person> (or Linq, or any of that fancy stuff), I could always accomplish this by doing the following:

Person oscar = null;
foreach (Person person in people) {
    if (person.Name == "Oscar") {
        oscar = person;
        break;
    }
}

if (oscar != null) {
    // Oscar exists!
}

This is fine, but then let's say I want to check if there's a person named "Ruth"? Or a person whose age is 17?

Using a Predicate<Person>, I can find these things using a LOT less code:

Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };

Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);

Notice I said a lot less code, not a lot faster. A common misconception developers have is that if something takes one line, it must perform better than something that takes ten lines. But behind the scenes, the Find method, which takes a Predicate<T>, is just enumerating after all. The same is true for a lot of Linq's functionality.

So let's take a look at the specific code in your question:

Predicate<int> pre = delegate(int a){ return a % 2 == 0; };

Here we have a Predicate<int> pre that takes an int a and returns a % 2 == 0. This is essentially testing for an even number. What that means is:

pre(1) == false;
pre(2) == true;

And so on. This also means, if you have a List<int> ints and you want to find the first even number, you can just do this:

int firstEven = ints.Find(pre);

Of course, as with any other type that you can use in code, it's a good idea to give your variables descriptive names; so I would advise changing the above pre to something like evenFinder or isEven -- something along those lines. Then the above code is a lot clearer:

int firstEven = ints.Find(evenFinder);

Swing/Java: How to use the getText and setText string properly

in your action performed method, call:

label1.setText(nameField.getText());

This way, when the button is clicked, label will be updated to the nameField text.

Run multiple python scripts concurrently

I do this in node.js (on Windows 10) by opening 2 separate cmd instances and running each program in each instance.

This has the advantage that writing to the console is easily visible for each script.

I see that in python can do the same: 2 shells.

You can run multiple instances of IDLE/Python shell at the same time. So open IDLE and run the server code and then open up IDLE again, which will start a separate instance and then run your client code.

How to update each dependency in package.json to the latest version?

  1. Use npm outdated to discover dependencies that are out of date.

  2. Use npm update to perform safe dependency upgrades.

  3. Use npm install @latest to upgrade to the latest major version of a package.

  4. Use npx npm-check-updates -u and npm install to upgrade all dependencies to their latest major versions.

Get visible items in RecyclerView

You can find the first and last visible children of the recycle view and check if the view you're looking for is in the range:

var visibleChild: View = rv.getChildAt(0)
val firstChild: Int = rv.getChildAdapterPosition(visibleChild)
visibleChild = rv.getChildAt(rv.childCount - 1)
val lastChild: Int = rv.getChildAdapterPosition(visibleChild)
println("first visible child is: $firstChild")
println("last visible child is: $lastChild")

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got this error resolved by doing 2 things in chrome browser:

  1. Pressed Ctrl + Shift + Delete and cleared all browsing data from beginning.
  2. Go to Chrome's : Settings ->Advanced Settings -> Open proxy settings -> Internet Properties then Go to the Content window and click on the Clear SSL State Button.

This site has this information and other options as well : https://www.thesslstore.com/blog/fix-err-ssl-protocol-error/

How does origin/HEAD get set?

Note first that your question shows a bit of misunderstanding. origin/HEAD represents the default branch on the remote, i.e. the HEAD that's in that remote repository you're calling origin. When you switch branches in your repo, you're not affecting that. The same is true for remote branches; you might have master and origin/master in your repo, where origin/master represents a local copy of the master branch in the remote repository.

origin's HEAD will only change if you or someone else actually changes it in the remote repository, which should basically never happen - you want the default branch a public repo to stay constant, on the stable branch (probably master). origin/HEAD is a local ref representing a local copy of the HEAD in the remote repository. (Its full name is refs/remotes/origin/HEAD.)

I think the above answers what you actually wanted to know, but to go ahead and answer the question you explicitly asked... origin/HEAD is set automatically when you clone a repository, and that's about it. Bizarrely, that it's not set by commands like git remote update - I believe the only way it will change is if you manually change it. (By change I mean point to a different branch; obviously the commit it points to changes if that branch changes, which might happen on fetch/pull/remote update.)


Edit: The problem discussed below was corrected in Git 1.8.4.3; see this update.


There is a tiny caveat, though. HEAD is a symbolic ref, pointing to a branch instead of directly to a commit, but the git remote transfer protocols only report commits for refs. So Git knows the SHA1 of the commit pointed to by HEAD and all other refs; it then has to deduce the value of HEAD by finding a branch that points to the same commit. This means that if two branches happen to point there, it's ambiguous. (I believe it picks master if possible, then falls back to first alphabetically.) You'll see this reported in the output of git remote show origin:

$ git remote show origin
* remote origin
  Fetch URL: ...
  Push  URL: ...
  HEAD branch (remote HEAD is ambiguous, may be one of the following):
    foo
    master

Oddly, although the notion of HEAD printed this way will change if things change on the remote (e.g. if foo is removed), it doesn't actually update refs/remotes/origin/HEAD. This can lead to really odd situations. Say that in the above example origin/HEAD actually pointed to foo, and origin's foo branch was then removed. We can then do this:

$ git remote show origin
...
HEAD branch: master
$ git symbolic-ref refs/remotes/origin/HEAD
refs/remotes/origin/foo
$ git remote update --prune origin
Fetching origin
 x [deleted]         (none)     -> origin/foo
   (refs/remotes/origin/HEAD has become dangling)

So even though remote show knows HEAD is master, it doesn't update anything. The stale foo branch is correctly pruned, and HEAD becomes dangling (pointing to a nonexistent branch), and it still doesn't update it to point to master. If you want to fix this, use git remote set-head origin -a, which automatically determines origin's HEAD as above, and then actually sets origin/HEAD to point to the appropriate remote branch.

Creating a system overlay window (always on top)

Well try my code, atleast it gives you a string as overlay, you can very well replace it with a button or an image. You wont believe this is my first ever android app LOL. Anyways if you are more experienced with android apps than me, please try

  • changing parameters 2 and 3 in "new WindowManager.LayoutParams"
  • try some different event approach

Make selected block of text uppercase

The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above).

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

[
 {
    "key": "ctrl+shift+u",
    "command": "editor.action.transformToUppercase",
    "when": "editorTextFocus"
 },
 {
    "key": "ctrl+shift+l",
    "command": "editor.action.transformToLowercase",
    "when": "editorTextFocus"
 }
]

Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.

These commands are built into VS Code, and no extensions are required to make them work.

How do I get first name and last name as whole name in a MYSQL query?

You can use a query to get the same:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

To avoid above we can use the IsNull keyword to get the same.

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.