Programs & Examples On #Convenience methods

How to normalize a NumPy array to within a certain range?

You can use the "i" (as in idiv, imul..) version, and it doesn't look half bad:

image /= (image.max()/255.0)

For the other case you can write a function to normalize an n-dimensional array by colums:

def normalize_columns(arr):
    rows, cols = arr.shape
    for col in xrange(cols):
        arr[:,col] /= abs(arr[:,col]).max()

2D cross-platform game engine for Android and iOS?

Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:

I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7

One DbContext per web request... why?

Another issue to watch out for with Entity Framework specifically is when using a combination of creating new entities, lazy loading, and then using those new entities (from the same context). If you don't use IDbSet.Create (vs just new), Lazy loading on that entity doesn't work when its retrieved out of the context it was created in. Example:

 public class Foo {
     public string Id {get; set; }
     public string BarId {get; set; }
     // lazy loaded relationship to bar
     public virtual Bar Bar { get; set;}
 var foo = new Foo {
     Id = "foo id"
     BarId = "some existing bar id"

 // some other code, using the same context
 var foo = dbContext.Set<Foo>().Find("foo id");
 var barProp = foo.Bar.SomeBarProp; // fails with null reference even though we have BarId set.

Set System.Drawing.Color values

You must use Color.FromArgb method to create new color structure

var newColor = Color.FromArgb(0xCC,0xBB,0xAA);

SSIS Convert Between Unicode and Non-Unicode Error

When creating table in SQL Server make your table columns NVARCHAR instead of VARCHAR.

When and Why to use abstract classes/methods?

read the following article

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

javascript date + 7 days

Without declaration

To return timestamp

new Date().setDate(new Date().getDate() + 7)

To return date

new Date(new Date().setDate(new Date().getDate() + 7))

How do I check if an element is hidden in jQuery?

Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).

Print text in Oracle SQL Developer SQL Worksheet window

You could put your text in a select statement such as...

SELECT 'Querying Table1' FROM dual;

How to add key,value pair to dictionary?

May be some time this also will be helpful

import collections
#Write you select statement here and other things to fetch the data.
 if rows:
            JArray = []
            for row in rows:

                JArray2 = collections.OrderedDict()
                JArray2["id"]= str(row['id'])
                JArray2["Name"]= row['catagoryname']

            return json.dumps(JArray)

Example Output:

        "id": 14
        "Name": "someName1"
        "id": 15
        "Name": "someName2"

How to set radio button checked as default in radiogroup?

you should check the radiobutton in the radiogroup like this:


Of course you first have to set an Id to your radiobuttons

EDIT: i forgot, radioButton.getId() works as well, thx Ramesh



works in radiogroup xml

Zoom in on a point (using scale and translate)

Here's an alternate way to do it that uses setTransform() instead of scale() and translate(). Everything is stored in the same object. The canvas is assumed to be at 0,0 on the page, otherwise you'll need to subtract its position from the page coords.

this.zoomIn = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale * zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) * zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) * zoomFactor
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
this.zoomOut = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale / zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) / zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) / zoomFactor
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,

Accompanying code to handle panning:

this.startPan = function (pageX, pageY) {
    this.startTranslation = {
        x: pageX - this.lastTranslation.x,
        y: pageY - this.lastTranslation.y
this.continuePan = function (pageX, pageY) {
    var newTranslation = {x: pageX - this.startTranslation.x,
                          y: pageY - this.startTranslation.y};
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    newTranslation.x, newTranslation.y);
this.endPan = function (pageX, pageY) {
    this.lastTranslation = {
        x: pageX - this.startTranslation.x,
        y: pageY - this.startTranslation.y

To derive the answer yourself, consider that the same page coordinates need to match the same canvas coordinates before and after the zoom. Then you can do some algebra starting from this equation:

(pageCoords - translation) / scale = canvasCoords

Center image in table td in CSS

Another option is the use <th> instead of <td>. <th> defaults to center; <td> defaults to left.

It is more efficient to use if-return-return or if-else-return?

I know the question is tagged python, but it mentions dynamic languages so thought I should mention that in ruby the if statement actually has a return type so you can do something like

def foo
  rv = if (A > B)
  return rv 

Or because it also has implicit return simply

def foo 
  if (A>B)

which gets around the style issue of not having multiple returns quite nicely.

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Visual Studio can't build due to rc.exe

If you really need to use the SDK Windows 10 with Visual Studio 2015, you have to download an older version on sdk-archive. Newer version of the SDK changed the place of the rc executable and MSBuild of Visual Studio 2015 update 3 (latest version) can't locate it. At least the version 10.0.14393.795 of the SDK Windows is still compatible with Visual Studio 2015.

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

Regarding 'main(int argc, char *argv[])'

The comp.lang.c FAQ deals with the question

"What's the correct declaration of main()?"
in Question 11.12a.

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)

is of a type that is invalid for use as a key column in an index

The only solution is to use less data in your Unique Index. Your key can be NVARCHAR(450) at most.

"SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

Read more at MSDN

How to import RecyclerView for Android L-preview

Figured it out.

You'll have to add the following gradle dependency :

compile ''

another issue I had compiling was the compileSdkVersion. Apparently you'll have to compile it against android-L

Your build.gradle file should look something like this:

apply plugin: 'android'
android {
    compileSdkVersion 'android-L'
    buildToolsVersion '19.1.0'
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

How do you test your Request.QueryString[] variables?

I actually have a utility class that uses Generics to "wrap" session, which does all of the "grunt work" for me, I also have something almost identical for working with QueryString values.

This helps remove the code dupe for the (often numerous) checks..

For example:

public class QueryString
    static NameValueCollection QS
            if (HttpContext.Current == null)
                throw new ApplicationException("No HttpContext!");

            return HttpContext.Current.Request.QueryString;

    public static int Int(string key)
        int i; 
        if (!int.TryParse(QS[key], out i))
            i = -1; // Obviously Change as you see fit.
        return i;

    // ... Other types omitted.

// And to Use..
void Test()
    int i = QueryString.Int("test");


This obviously makes use of statics, which some people don't like because of the way it can impact test code.. You can easily refactor into something that works based on instances and any interfaces you require.. I just think the statics example is the lightest.

Hope this helps/gives food for thought.

How to search file text for a pattern and replace it with a given value

Here's a solution for find/replace in all files of a given directory. Basically I took the answer provided by sepp2k and expanded it.

# First set the files to search/replace in
files = Dir.glob("/PATH/*")

# Then set the variables for find/replace
@original_string_or_regex = /REGEX/
@replacement_string = "STRING"

files.each do |file_name|
  text =
  replace = text.gsub!(@original_string_or_regex, @replacement_string), "w") { |file| file.puts replace }

Rotating a view in Android

Joininig @Rudi's and @Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.

setRotation() method preserves buttons functionality.

Code Sample:

Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);

    an.setFillAfter(false);              // DO NOT keep rotation after animation
    an.setFillEnabled(true);             // Make smooth ending of Animation
    an.setAnimationListener(new AnimationListener() {
        public void onAnimationStart(Animation animation) {}

        public void onAnimationRepeat(Animation animation) {}

        public void onAnimationEnd(Animation animation) {
                mainLayout.setRotation(180.0f);      // Make instant rotation when Animation is finished


mainLayout is a (LinearLayout) field

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

When we download the binary of apache-jmeter-x.x.tgz, where x could be any version of apache Jmeter. ApacheJMeter.jar must present inside apache-jmeter-x/bin folder , if it is not present somewhere your package not downloaded properly. Cause could be slow internet, or improper shutdown

Download package again and make sure ApacheJMeter.jar present in apache-jmeter-x/bin folder. Once it is present hit sh

What does %s mean in a python format string?

Here is a good example in Python3.

  >>> a = input("What is your name?")
  What is your name?Peter

  >>> b = input("Where are you from?")
  Where are you from?DE

  >>> print("So you are %s of %s" % (a, b))
  So you are Peter of DE

Failed to resolve:

implementation '' implementation '' implementation '' All to add

Powershell equivalent of bash ampersand (&) for forking/running background processes

As long as the command is an executable or a file that has an associated executable, use Start-Process (available from v2):

Start-Process -NoNewWindow ping

You can also add this as a function in your profile:

function bg() {Start-Process -NoNewWindow @args}

and then the invocation becomes:

bg ping

In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:

  1. Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}"
  2. Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory.
  3. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.

NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.

Node.js console.log() not logging anything

In a node.js server console.log outputs to the terminal window, not to the browser's console window.

How are you running your server? You should see the output directly after you start it.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">


<th style="white-space:nowrap;">


<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT                  -- of pids
FROM Catalog AS c2             -- from catalog
HAVING COUNT(c2.sid) >= 2)

Gradient text color

You can achieve that effect using a combination of CSS linear-gradient and mix-blend-mode.


    Enter your message here... 
    To be or not to be, 
    that is the question...
    maybe, I think, 
    I'm not sure
    wait, you're still reading this?
    Type a good message already!


p {
    width: 300px;
    position: relative;

p::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, red, orange, yellow, green, blue, purple);
    mix-blend-mode: screen;

What this does is add a linear gradient on the paragraph's ::after pseudo-element and make it cover the whole paragraph element. But with mix-blend-mode: screen, the gradient will only show on parts where there is text.

Here's a jsfiddle to show this at work. Just modify the linear-gradient values to achieve what you want.

Retrieving Data from SQL Using pyodbc

Instead of using the pyodbc library, use the pypyodbc library... This worked for me.

import pypyodbc

conn = pypyodbc.connect("DRIVER={SQL Server};"

cursor = conn.cursor()
cursor.execute('SELECT * FROM [table]')

for row in cursor:
    print('row = %r' % (row,))

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
   echo "You did not fill out the required fields.";

vagrant login as root by default

This is useful:

sudo passwd root

for anyone who's been caught out by the need to set a root password in vagrant first

nodejs module.js:340 error: cannot find module

  1. Try npm start in Node.js Command Prompt.
  2. Look at the end of the messages - it gives you the path of log file in "Additional Logging Details ..." something like c:\users\MyUser\npm-debug.log
  3. Open this file in Notepad and find the real address of Node.exe : something like C:\\Program Files\\nodejs\\\\node.exe
  4. Try cd to this path
  5. Call node.exe + <full path to your server file.js>

    Server is listening on port 1337 !

Reset all the items in a form

There is a very effective way to use to clear or reset Windows Form C# controls like TextBox, ComboBox, RadioButton, CheckBox, DateTimePicker etc.

private void btnClear_Click(object sender, EventArgs e)

internal class Utilities
    internal static void ClearAllControls(Control control)
        foreach (Control c in control.Controls)
            if (c is TextBox)
            else if (c is ComboBox)
                ((ComboBox)c).SelectedIndex = -1;
            else if (c is RadioButton)
                ((RadioButton)c).Checked = false;
            else if (c is CheckBox)
                ((CheckBox)c).Checked = false;
            else if (c is DateTimePicker)
                ((DateTimePicker)c).Value = DateTime.Now; // or null 

To accomplish this with overall user experience in c# we can use one statement to clear them. Pretty straight forward so far, above is the code.

Get AVG ignoring Null or Zero values

worked for me:


Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

python: how to get information about a function?

In python: help(my_list.append) for example, will give you the docstring of the function.

>>> my_list = []
>>> help(my_list.append)

    Help on built-in function append:

        L.append(object) -- append object to end

Shortcut for changing font size

In visual studio 2019 you can use,


Ctrl + Shift + . To increase

Ctrl + Shift + , To decrease


Go to Tools > Options... > Environment > Fonts and Colors

AngularJS - value attribute for select

you can use for state in states track by state.code

Where states in the JSON array, state is the variable name for each object in the array.

Hope this helps

window.onload vs $(document).ready()

window.onload: A normal JavaScript event.

document.ready: A specific jQuery event when the entire HTML has been loaded.

Add / Change parameter of URL and redirect to the new URL

though i take the url from an input, it's easy adjustable to the real url.

var value = 0;

    var originalURL = $('#test').val();
    var exists = originalURL.indexOf('&view-all');

    if(exists === -1)
        $('#test').val(originalURL + '&view-all=value' + value++);
        $('#test').val(originalURL.substr(0, exists + 15) + value++);

How to delete selected text in the vi editor

When using a terminal like PuTTY, usually mouse clicks and selections are not transmitted to the remote system. So, vi has no idea that you just selected some text. (There are exceptions to this, but in general mouse actions aren't transmitted.)

To delete multiple lines in vi, use something like 5dd to delete 5 lines.

If you're not using Vim, I would strongly recommend doing so. You can use visual selection, where you press V to start a visual block, move the cursor to the other end, and press d to delete (or any other editing command, such as y to copy).

Simple two column html layout without using tables

If you want to do it the HTML5 way (this particular code works better for things like blogs, where <article> is used multiple times, once for each blog entry teaser; ultimately, the elements themselves don't matter much, it's the styling and element placement that will get you your desired results):

<style type="text/css">
article {
  float: left;
  width: 500px;

aside {
  float: right;
  width: 200px;

#wrap {
  width: 700px;
  margin: 0 auto;

<div id="wrap">
     Main content here
     Sidebar stuff here

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

Why would one mark local variables and method parameters as "final" in Java?

final has three good reasons:

  • instance variables set by constructor only become immutable
  • methods not to be overridden become final, use this with real reasons, not by default
  • local variables or parameters to be used in anonimous classes inside a method need to be final

Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

Best database field type for a URL

Most web servers have a URL length limit (which is why there is an error code for "URI too long"), meaning there is a practical upper size. Find the default length limit for the most popular web servers, and use the largest of them as the field's maximum size; it should be more than enough.

How to ALTER multiple columns at once in SQL Server

As others have answered, you need multiple ALTER TABLE statements.
Try following:

ALTER TABLE tblcommodityOHLC alter column CC_CommodityContractID NUMERIC(18,0);
ALTER TABLE tblcommodityOHLC alter column CM_CommodityID NUMERIC(18,0);

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'

How to parse XML using shellscript?

Try using xpath. You can use it to parse elements out of an xml tree.


I'm assuming you don't want any other session to be able to read the row while this specific query is running...

Wrapping your SELECT in a transaction while using WITH (XLOCK,READPAST) locking hint will get the results you want. Just make sure those other concurrent reads are NOT using WITH (NOLOCK). READPAST allows other sessions to perform the same SELECT but on other rows.

  WHERE RowId = @SomeId


  UPDATE <tablename>
  SET <column>=@somevalue
  WHERE RowId=@SomeId

Is there a JSON equivalent of XQuery/XPath?

Just to add to the choices, there's also XPath. XPath 3.1 handles JSON as well as XML. In XPath 3.1 your required query is ?0?Objects?*[?id=3]

Drop rows containing empty cells from a pandas DataFrame

If you don't care about the columns where the missing files are, considering that the dataframe has the name New and one wants to assign the new dataframe to the same variable, simply run

New = New.drop_duplicates()

If you specifically want to remove the rows for the empty values in the column Tenant this will do the work

New = New[New.Tenant != '']

This may also be used for removing rows with a specific value - just change the string to the value that one wants.

Note: If instead of an empty string one has NaN, then

New = New.dropna(subset=['Tenant'])

What does status=canceled for a resource mean in Chrome Developer Tools?

Another thing to look out for could be the AdBlock extension, or extensions in general.

But "a lot" of people have AdBlock....

To rule out extension(s) open a new tab in incognito making sure that "allow in incognito is off" for the extention(s) you want to test.

JAX-RS / Jersey how to customize error handling?

One obvious solution: take in a String, convert to Date yourself. That way you can define format you want, catch exceptions and either re-throw or customize error being sent. For parsing, SimpleDateFormat should work fine.

I am sure there are ways to hook handlers for data types too, but perhaps little bit of simple code is all you need in this case.

What is the use of the %n format specifier in C?

Those who want to use %n Format Specifier may want to look at this:

Do Not Use the "%n" Format String Specifier


Careless use of "%n" format strings can introduce a vulnerability.


There are many kinds of vulnerability that can be caused by misusing format strings. Most of these are covered elsewhere, but this document covers one specific kind of format string vulnerability that is entirely unique for format strings. Documents in the public are inconsistent in coverage of these vulnerabilities.

In C, use of the "%n" format specification in printf() and sprintf() type functions can change memory values. Inappropriate design/implementation of these formats can lead to a vulnerability generated by changes in memory content. Many format vulnerabilities, particularly those with specifiers other than "%n", lead to traditional failures such as segmentation fault. The "%n" specifier has generated more damaging vulnerabilities. The "%n" vulnerabilities may have secondary impacts, since they can also be a significant consumer of computing and networking resources because large guantities of data may have to be transferred to generate the desired pointer value for the exploit.

Avoid using the "%n" format specifier. Use other means to accomplish your purpose.

Source: link

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias to refer to the host computer's loopback interface. From the emulator's perspective, localhost ( refers to its own loopback interface.More details:

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;

    &:before {
        content: "";

    &:after {
        content: "* * *";

How can I select checkboxes using the Selenium Java WebDriver?

For a partial match, do the following:

getDriver().findElement(By.cssSelector("<tag name>[id*='id pattern to look for']")).click();

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub


I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Which ChromeDriver version is compatible with which Chrome Browser version?

At the time of writing this I have discovered that chromedriver 2.46 or 2.36 works well with Chrome 75.0.3770.100

Documentation here: states align driver and browser alike but I found I had issues even with the most up-to-date driver when using Chrome 75

I am running Selenium 2 on Windows 10 Machine.

How to get the EXIF data from a file using C#

As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:

I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.

Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.

Edit: It's possible to do it without loading the full image following this answer:

selecting rows with id from another table

Try this (subquery):

   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT,, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON = tr.term_id AND tr.taxonomy = "categ"

Delete specific line number(s) from a text file using sed?

and awk as well

awk 'NR!~/^(5|10|25)$/' file

Using filesystem in node.js with async / await

I have this little helping module that exports promisified versions of fs functions

const fs = require("fs");
const {promisify} = require("util")

module.exports = {
  readdir: promisify(fs.readdir),
  readFile: promisify(fs.readFile),
  writeFile: promisify(fs.writeFile)
  // etc...

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Best way to convert strings to symbols in hash

A modification to @igorsales answer

class Object
  def deep_symbolize_keys
    return self.inject({}){|memo,(k,v)| memo[k.to_sym] = v.deep_symbolize_keys; memo} if self.is_a? Hash
    return self.inject([]){|memo,v    | memo           << v.deep_symbolize_keys; memo} if self.is_a? Array
    return self

MySQL: Check if the user exists and drop it

Combining phyzome's answer (which didn't work right away for me) with andreb's comment (which explains why it didn't) I ended up with this seemingly working code that temporarily disables NO_AUTO_CREATE_USER mode if it is active:

set @mode = @@SESSION.sql_mode;
set session sql_mode = replace(replace(@mode, 'NO_AUTO_CREATE_USER', ''), ',,', ',');
grant usage on *.* to 'myuser'@'%';
set session sql_mode = @mode;
drop user 'myuser'@'%';

HorizontalScrollView within ScrollView Touch Handling

Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.

Here is the code for my Scroll View class that contains the HorizontalScrollView:

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);

How do I check if a Socket is currently connected in Java?

  • socket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • socket.getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • socket.getInetAddress().isReachable(int timeout): From isReachable(int timeout)

    Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this SQL Team link on how to use SMO to script objects.

How to add a Try/Catch to SQL Stored Procedure

yep - you can even nest the try catch statements as:

SET @myFixDte = CONVERT(datetime, @myFixDteStr,101)
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,103)
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,104)
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,105)

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

I had same problem. It said could not copy from bin\debug to obj.....

When i build web project i found my dll were all in bin folder and not in bin\debug. During publish vs was looking for files in bin\debug. So i opened web project file in editor and look for instances of bin\debug and i found all the dll were mentioned as bin\debug\mylibrary.dll. I removed all \debug from the path and published again. This time vs was able to find all the dll in bin folder and publish succeeded.

I have no idea how this path got changed in web project file.

I spent more than 5 hours debugging this and finally found solution on my own.

This is the right answer.

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

There's a subset of Google Analytics js library called ga-lite that you can cache however you want.

The library uses Google Analytics' public REST API to send the user tracking data to Google. You can read more from the blog post about ga-lite.

Disclaimer: I am the author of this library. I struggled with this specific problem and the best result I found was to implement this solution.

Any way of using frames in HTML5?

I know your class is over, but in professional coding, let this be a lesson:

  • "Deprecated" means "avoid use; it's going to be removed in the future"
  • Deprecated things still work - just don't expect support or future-proofing
  • If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
    • If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
    • Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
    • When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
    • Deploy your solution as quickly as you can (there will be bugs)
    • Gain rep for preventing excessive downtime.

npm install vs. update - what's the difference?

npm update: install and update with latest node modules which are in package.json

npm install: install node modules which are defined in package.json(without update)

How to convert std::string to LPCSTR?

The conversion is simple:

std::string str; LPCSTR lpcstr = str.c_str();

Uncaught SyntaxError: Unexpected token < On Chrome

header("Location: route_to_main_page");

I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.

Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.


urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY

BASE_URL = "{security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"

def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': '',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})

 if __name__ == '__main__':

Besides this is relatively modular and ready to use snippet.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

How can I write text on a HTML5 canvas element?

Canvas text support is actually pretty good - you can control font, size, color, horizontal alignment, vertical alignment, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms to rotate, stretch and even invert text.

How do you use subprocess.check_output() in Python?

Since Python 3.5, is recommended over subprocess.check_output():

>>>['cat','/tmp/text.txt'], stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'

Since Python 3.7, instead of the above, you can use capture_output=true parameter to capture stdout and stderr:

>>>['cat','/tmp/text.txt'], capture_output=True).stdout
b'First line\nSecond line\n'

Also, you may want to use universal_newlines=True or its equivalent since Python 3.7 text=True to work with text instead of binary:

>>> stdout =['cat', '/tmp/text.txt'], capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line

See documentation for more information.

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

How to put text over images in html?

The <img> element is empty — it doesn't have an end tag.

If the image is a background image, use CSS. If it is a content image, then set position: relative on a container, then absolutely position the image and/or text within it.

How to write new line character to a file in Java

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("").toLowerCase();
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
        eol = "\n";
        eol = "\r\n";

    return eol;

Where eol is the newline

Test if element is present using Selenium WebDriver?

This should do it:

try {
} catch (NoSuchElementException e) {
    //do what you need here if you were expecting
    //the element wouldn't exist

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

You can achieve a fade effect (instead of sticking with the default slide) using css only. Add these to your stylesheet

.carousel .item {
    -webkit-transition: opacity 3s; 
    -moz-transition: opacity 3s; 
    -ms-transition: opacity 3s; 
    -o-transition: opacity 3s; 
    transition: opacity 3s;
.carousel .active.left {
.carousel .next {

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on =
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How to show soft-keyboard when edittext is focused

I have had some recent luck in some simple cases with the code below. I haven't finished all testing but....

EditText input = (EditText) findViewById(;
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));

And presto the keyboard shows up.

Difference between Static methods and Instance methods

Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call. Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.

In static methods => there is no such thing as 'this'. Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).

Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.

How to style input and submit button with CSS?

Here's a starting point


input[type=text] {
    border:2px solid #ccc; 
    -webkit-border-radius: 5px;
    border-radius: 5px;

input[type=text]:focus {

input[type=submit] {
    padding:5px 15px; 
    border:0 none;
    -webkit-border-radius: 5px;
    border-radius: 5px; 

How to find array / dictionary value using key?

It's as simple as this :


Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

How do I create a master branch in a bare Git repository?

A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status, etc.

If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:

# initialize your bare repo
$ git init --bare test-repo.git

# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
$ cd test-clone

# make an initial commit in the clone
$ touch
$ git add . 
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644

# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
 * [new branch]      master -> master

What is so bad about singletons?

This is what I think is missing from the answers so far:

If you need one instance of this object per process address space (and you are as confident as you can be that this requirement will not change), you should make it a singleton.

Otherwise, it's not a singleton.

This is a very odd requirement, hardly ever of interest to the user. Processes and address space isolation are an implementation detail. They only impact on the user when they want to stop your application using kill or Task Manager.

Apart from building a caching system, there aren't that many reasons why you'd be so certain that there should only be on instance of something per process. How about a logging system? Might be better for that to be per-thread or more fine-grained so you can trace the origin of messages more automatically. How about the application's main window? It depends; maybe you'll want all the user's documents to be managed by the same process for some reason, in which case there would be multiple "main windows" in that process.

Java - creating a new thread

You need to do two things:

  • Start the thread
  • Wait for the thread to finish (die) before proceeding



If you don't start() it, nothing will happen - creating a Thread doesn't execute it.

If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.

How to loop through an array containing objects and access their properties

myArray[j.x] is logically incorrect.

Use (myArray[j].x); instead

for (var j = 0; j < myArray.length; j++){

Lost connection to MySQL server during query?

The same as @imxylz, but I had to use mycursor.execute('set GLOBAL max_allowed_packet=67108864') as I got a read-only error without using the GLOBAL parameter.



how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Can I send a ctrl-C (SIGINT) to an application on Windows?

I have done some research around this topic, which turned out to be more popular than I anticipated. KindDragon's reply was one of the pivotal points.

I wrote a longer blog post on the topic and created a working demo program, which demonstrates using this type of system to close a command line application in a couple of nice fashions. That post also lists external links that I used in my research.

In short, those demo programs do the following:

  • Start a program with a visible window using .Net, hide with pinvoke, run for 6 seconds, show with pinvoke, stop with .Net.
  • Start a program without a window using .Net, run for 6 seconds, stop by attaching console and issuing ConsoleCtrlEvent

Edit: The amended solution from KindDragon for those who are interested in the code here and now. If you plan to start other programs after stopping the first one, you should re-enable Ctrl-C handling, otherwise the next process will inherit the parent's disabled state and will not respond to Ctrl-C.

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(uint dwProcessId);

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool FreeConsole();

static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

delegate bool ConsoleCtrlDelegate(CtrlTypes CtrlType);

// Enumerated type for the control messages sent to the handler routine
enum CtrlTypes : uint

[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

public void StopProgram(Process proc)
  //This does not require the console window to be visible.
  if (AttachConsole((uint)proc.Id))
    // Disable Ctrl-C handling for our program
    SetConsoleCtrlHandler(null, true); 
    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

    //Moved this command up on suggestion from Timothy Jannace (see comments below)

    // Must wait here. If we don't and re-enable Ctrl-C
    // handling below too fast, we might terminate ourselves.

    //Re-enable Ctrl-C handling or any subsequently started
    //programs will inherit the disabled state.
    SetConsoleCtrlHandler(null, false); 

Also, plan for a contingency solution if AttachConsole() or the sent signal should fail, for instance sleeping then this:

if (!proc.HasExited)
  catch (InvalidOperationException e){}

Line Break in HTML Select Option?

If you just want a line break in the dropdown list use this:

<option label="" value="" disabled=""> </option>

How to cancel an $http request in AngularJS?

Cancelation of requests issued with $http is not supported with the current version of AngularJS. There is a pull request opened to add this capability but this PR wasn't reviewed yet so it is not clear if its going to make it into AngularJS core.

Check whether specific radio button is checked

You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).

You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.

If you're going to use IDs, just try:

return $('#test2').attr('checked');

Webview load html from assets directory

Download source code from here (Open html file from assets android)


<RelativeLayout xmlns:android=""


package com.deepshikha.htmlfromassets;
 import android.os.Bundle;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

WebView webview;
 ProgressDialog progressDialog;

 protected void onCreate(Bundle savedInstanceState) {

private void init(){
 webview = (WebView)findViewById(;

progressDialog = new ProgressDialog(MainActivity.this);

webview.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
 try {
 } catch (Exception e) {

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);


var answer = str.RegexStartsWith("mailto","ftp","joe");
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

Remove Last Comma from a string

The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:

let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '

Regular expression to match any character being repeated more than 10 times

In Python you can use (.)\1{9,}

  • (.) makes group from one char (any char)
  • \1{9,} matches nine or more characters from 1st group


txt = """1. aaaaaaaaaaaaaaa
2. bb
3. cccccccccccccccccccc
4. dd
5. eeeeeeeeeeee"""
rx = re.compile(r'(.)\1{9,}')
lines = txt.split('\n')
for line in lines:
    rxx =
    if rxx:
        print line


1. aaaaaaaaaaaaaaa
3. cccccccccccccccccccc
5. eeeeeeeeeeee

Linux command to list all available commands and aliases

Use "which searchstr". Returns either the path of the binary or the alias setup if it's an alias

Edit: If you're looking for a list of aliases, you can use:

alias -p | cut -d= -f1 | cut -d' ' -f2

Add that in to whichever PATH searching answer you like. Assumes you're using bash..

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful



Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying


It worked for me. Thanks

Difference between two lists

here is my solution:

    List<String> list1 = new List<String>();

    List<String> list2 = new List<String>();

    List<String> exceptValue = new List<String>();

foreach(String L1 in List1) 
foreach(String L2 in List2) 

Use Expect in a Bash script to provide a password to an SSH command

Also make sure to use

send -- "$PWD\r"

instead, as passwords starting with a dash (-) will fail otherwise.

The above won't interpret a string starting with a dash as an option to the send command.

How do you create a UIImage View Programmatically - Swift

This answer is update to Swift 3.

This is how you can add an image view programmatically where you can control the constraints.

Class ViewController: UIViewController {

    let someImageView: UIImageView = {
       let theImageView = UIImageView()
       theImageView.image = UIImage(named: "yourImage.png")
       theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
       return theImageView

    override func viewDidLoad() {

       view.addSubview(someImageView) //This add it the view controller without constraints
       someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints

    // do not forget the `.isActive = true` after every constraint
    func someImageViewConstraints() {
        someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true


JavaScript: IIF like statement

'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';

How to convert XML to JSON in Python?

I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:

        <name>Koen Bok</name>
        <name>Plutor Heidepeen</name>

Would become

{'persons': [
    {'name': 'Koen Bok', 'age': 26},
    {'name': 'Plutor Heidepeen', 'age': 33}]

But what would this be:

    <person name="Koen Bok">
        <locations name="defaults">
            <location long=123 lat=384 />

See what I mean?

Edit: just found this article:

jQuery + client-side template = "Syntax error, unrecognized expression"

I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...['$templateCache', function($templateCache) {
    var url = "survey-input.html";
    content = angular.element(document.getElementById(url)).html()
    $templateCache.put(url, content);

How to send HTML email using linux command line

I was struggling with similar problem (with mail) in one of my git's post_receive hooks and finally I found out, that sendmail actually works better for that kind of things, especially if you know a bit of how e-mails are constructed (and it seems like you know). I know this answer comes very late, but maybe it will be of some use to others too. I made use of heredoc operator and use of the feature, that it expands variables, so it can also run inlined scripts. Just check this out (bash script):

    '[email protected]'
    '[email protected]'
#   '[email protected]'
sender='[email protected]';
subject='Oh, who really cares, seriously...';
sendmail -t <<-MAIL
    From: ${sender}
    `for r in "${recipients[@]}"; do echo "To: ${r}"; done;`
    Subject: ${subject}
    Content-Type: text/html; charset=UTF-8

    <html><head><meta charset="UTF-8"/></head>
    <body><p>Ladies and gents, here comes the report!</p>
    <pre>`mysql -u ***** -p***** -H -e "SELECT * FROM users LIMIT 20"`</pre>

Note of backticks in the MAIL part to generate some output and remember, that <<- operator strips only tabs (not spaces) from the beginning of lines, so in that case copy-paste will not work (you need to replace indentation with proper tabs). Or use << operator and make no indentation at all. Hope this will help someone. Of course you can use backticks outside o MAIL part and save the output into some variable, that you can later use in the MAIL part — matter of taste and readability. And I know, #!/bin/bash does not always work on every system.

How to import a bak file into SQL Server Express

Restoring a Database from Backup

sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
            DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK

Uploading multiple files using formData()

I found this work for me!

var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
  fd.append('item[]', $('input[type=file]')[index].files[0]);

  type: 'POST',
  url: 'your/path/', 
  data: fd,
  dataType: 'json',
  contentType: false,
  processData: false,
  cache: false,
  success: function (response) {
  error: function(err){
}).done(function() {
  // do something....
return false;

How can I add the sqlite3 module to Python?

I have python 2.7.3 and this solved my problem:

pip install pysqlite

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Using :after to clear floating elements

The text 'dasda' will never not be within a tag, right? Semantically and to be valid HTML it as to be, just add the clear class to that:

How is CountDownLatch used in Java Multithreading?

CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.

Pseudo code can be:

// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:


Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

How can I resolve the error: "The command [...] exited with code 1"?

Right click project -> Properties -> Build Events

Remove the text in Post-build event command line text block

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Test if you can request from other apps (like safari). If not might be something on your computer. In my case I had this problem with Avast Antivirus, which was blocking my simulators request (don't ask me why).

How to detect if URL has changed after hash in JavaScript

use this code

window.onhashchange = function() { 

with jQuery

$(window).bind('hashchange', function() {

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;

How to programmatically round corners and set random background colors

Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
 } else {

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( );

Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius because ShapeDrawable DOES NOT provide any such method.

Best way to stress test a website

My suggestion is for you to do some automated tests first. Use selenium for it.

Then deploy selenium grid to test in multiple computers at the same time.

Although Selenium as an automated test tool will run quite fast, making a mini stress test. If you put the same automation running on a couple of computers on your network at the same time you'll be able to see how it behaves.

If you want to record response timings, they have a cool api you can use to write some scripts to run your automations.

Edit: Selenium is quite easy to use, and it does asserts to page contents if you want to test the contents. It also copies your movement through the page if you wish (this would be my suggestion) just navigate the page a lot, and then save it for automation. Avoid putting asserts so selenium might run faster.

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

Razor-based view doesn't see referenced assemblies

None of these do work for me. Even "adding assembly referecene to system.web/compilation/assemblies section of the root web.config file". So the two ways remains for me: 1) to add a public wrap class for my assembly that Razor code can access to this assembly through this wrap; 2) just add assembly logic to a public class in the same assembly where the Razor's code is located.

Singular matrix issue with Numpy

Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

numpy.linalg.svd numpy.linalg.qr

Setup a Git server with msysgit on Windows

I just wanted to add my experiences with the PATH setup that Steve and timc mentions above: I got permission problems using shell tools (like mv and cp) having Git's shell executables first in the path.

Appending them after the existing PATH instead this solved my problems. Example:

GITPATH='/cygdrive/c/Program Files (x86)/Git/bin' GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core' PATH=${PATH}:${GITPATH}:${GITCOREPATH}

I guess CopSSH doesn't go along well with all of msysgit's shell executables...

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind

I hope it helps!!

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

grep –irl word1 * | grep –il word2 `cat -` | grep –il word3 `cat -`
  • -i makes search case insensitive
  • -r makes file search recursive through folders
  • -l pipes the list of files with the word found
  • cat - causes the next grep to look through the files passed to it list.

JavaScript/regex: Remove text between parentheses

I found this version most suitable for all cases. It doesn't remove all whitespaces.

For example "a (test) b" -> "a b"

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.


$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle

if ($proc.ExitCode -ne 0) {
    Write-Warning "$_ exited with status code $($proc.ExitCode)"

Escaping quotes and double quotes

Using the backtick (`) works fine for me if I put them in the following places:

$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""

$cmd returns as:

\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"

Is that what you were looking for?

The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.

The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:

"\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'""

The opening and closing symbols must be on their own line as shown above.


select * from 
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

Convert seconds to Hour:Minute:Second

Here is a one liner that handles negative seconds and more than 1 day worth of seconds.

sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

For Example:

$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

outputs: -26:03:04

IIS: Where can I find the IIS logs?

Try the Windows event log, there can be some useful information


I had the same problem in bash and i'm doing something like this:

mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');"

which works fine:-) But

mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');set @last_insert_id = LAST_INSERT_ID();"
mysql -D "dbname" -e "insert into table2 (id_tab1) values (@last_insert_id);"

don't work. Because after the first command, the shell will be logged out from mysql and logged in again for the second command, and then the variable @last_insert_id isn't set anymore. My solution is:

lastinsertid=$(mysql -B -N -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');select LAST_INSERT_ID();")
mysql -D "dbname" -e "insert into table2 (id_tab1) values (${lastinsertid});"

Maybe someone is searching for a solution an bash :-)

What's the best way to parse command line arguments?

Use optparse which comes with the standard library. For example:

#!/usr/bin/env python
import optparse

def main():
  p = optparse.OptionParser()
  p.add_option('--person', '-p', default="world")
  options, arguments = p.parse_args()
  print 'Hello %s' % options.person

if __name__ == '__main__':

Source: Using Python to create UNIX command line tools

However as of Python 2.7 optparse is deprecated, see: Why use argparse rather than optparse?

sql ORDER BY multiple values in specific order?

For someone who is new to ORDER BY with CASE this may be useful

         WHEN GRADE = 'B' THEN 1
         ELSE 2 END

How can I simulate a click to an anchor tag?

Quoted from

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.

Non–Gecko DOMs may behave differently.

Unfortunately it sounds like you have already discovered the best solution to your problem.

As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.

How can I get javascript to read from a .json file?

Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.

window.portalData = [_x000D_
    "kpi" : "NDAR",_x000D_
    "data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
     "kpi" : "NTI",_x000D_
     "data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
     "kpi" : "BS",_x000D_
     "data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
     "kpi" : "SISS",_x000D_
     "data" :  [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
 "kpi" : "MID",_x000D_
 "data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_

You can then do the following in your HTML

<script src="server_data.js"> </script>

function getServerData(kpiCode)
    var elem = $(window.portalData).filter(function(idx){
        return window.portalData[idx].kpi == kpiCode;

    return elem[0].data;

var defData = getServerData('NDAR');

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

i also face same problem.i found solution for that.

bcrypt required C++, python and node-pre-gyp.

sudo apt-get install g++
sudo apt-get install -y build-essential python
npm install node-pre-gyp

for more details check :

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;

Best way to find the intersection of multiple sets?

Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

Guido might dislike reduce, but I'm kind of fond of it :)

How to split a long array into smaller arrays, with JavaScript

Here is a simple one liner

var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)_x000D_
                                                    : (r.push([e]), r), []),_x000D_
        arr = Array.from({length: 31}).map((_,i) => i+1);_x000D_

How to query SOLR for empty fields?

According to SolrQuerySyntax, you can use q=-id:[* TO *].

Find the 2nd largest element in an array with minimum number of comparisons

I know this is an old question, but here is my attempt at solving it, making use of the Tournament Algorithm. It is similar to the solution used by @sdcvvc , but I am using two-dimensional array to store elements.

To make things work, there are two assumptions:
1) number of elements in the array is the power of 2
2) there are no duplicates in the array

The whole process consists of two steps:
1. building a 2D array by comparing two by two elements. First row in the 2D array is gonna be the entire input array. Next row contains results of the comparisons of the previous row. We continue comparisons on the newly built array and keep building the 2D array until an array of only one element (the largest one) is reached.
2. we have a 2D-array where last row contains only one element: the largest one. We continue going from the bottom to the top, in each array finding the element that was "beaten" by the largest and comparing it to the current "second largest" value. To find the element beaten by the largest, and to avoid O(n) comparisons, we must store the index of the largest element in the previous row. That way we can easily check the adjacent elements. At any level (above root level),the adjacent elements are obtained as:

leftAdjacent = rootIndex*2
rightAdjacent = rootIndex*2+1,

where rootIndex is index of the largest(root) element at the previous level.

I know the question asks for C++, but here is my attempt at solving it in Java. (I've used lists instead of arrays, to avoid messy changing of the array size and/or unnecessary array size calculations)

public static Integer findSecondLargest(List<Integer> list) {
        if (list == null) {
            return null;
        if (list.size() == 1) {
            return list.get(0);
        List<List<Integer>> structure = buildUpStructure(list);
        return secondLargest(structure);


    public static List<List<Integer>> buildUpStructure(List<Integer> list) {
        List<List<Integer>> newList = new ArrayList<List<Integer>>();
        List<Integer> tmpList = new ArrayList<Integer>(list);
        int n = list.size();
        while (n>1) {
            tmpList = new ArrayList<Integer>();
            for (int i = 0; i<n; i=i+2) {
                Integer i1 = list.get(i);
                Integer i2 = list.get(i+1);
                tmpList.add(Math.max(i1, i2));
            n/= 2;
            list = tmpList;
        return newList;

    public static Integer secondLargest(List<List<Integer>> structure) {
        int n = structure.size();
        int rootIndex = 0;
        Integer largest = structure.get(n-1).get(rootIndex);
        List<Integer> tmpList = structure.get(n-2);
        Integer secondLargest = Integer.MIN_VALUE;
        Integer leftAdjacent = -1;
        Integer rightAdjacent = -1;
        for (int i = n-2; i>=0; i--) {
            tmpList = structure.get(i);
            leftAdjacent = tmpList.get(rootIndex);
            rightAdjacent = tmpList.get(rootIndex+1); 
            if (leftAdjacent.equals(largest)) {
                if (rightAdjacent > secondLargest) {
                    secondLargest = rightAdjacent;
            if (rightAdjacent.equals(largest)) {
                if (leftAdjacent > secondLargest) {
                    secondLargest = leftAdjacent;

        return secondLargest;

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

PHP parse/syntax errors; and how to solve them

Unexpected T_VARIABLE

An "unexpected T_VARIABLE" means that there's a literal $variable name, which doesn't fit into the current expression/statement structure.

purposefully abstract/inexact operator+$variable diagram

  1. Missing semicolon

    It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:

     $var = 1 + 2;     # parse error in line +2
  2. String concatenation

    A frequent mishap are string concatenations with forgotten . operator:

     print "Here comes the value: "  $value;

    Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.

    String interpolation is a scripting language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable . concatenation being faster. It's not.

  3. Missing expression operators

    Of course the same issue can arise in other expressions, for instance arithmetic operations:

     print 4 + 7 $var;

    PHP can't guess here if the variable should have been added, subtracted or compared etc.

  4. Lists

    Same for syntax lists, like in array populations, where the parser also indicates an expected comma , for example:

     $var = array("1" => $val, $val2, $val3 $val4);

    Or functions parameter lists:

     function myfunc($param1, $param2 $param3, $param4)

    Equivalently do you see this with list or global statements, or when lacking a ; semicolon in a for loop.

  5. Class declarations

    This parser error also occurs in class declarations. You can only assign static constants, not expressions. Thus the parser complains about variables as assigned data:

     class xyz {      ?
         var $value = $_GET["input"];

    Unmatched } closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body.

  6. Variables after identifiers

    You can also never have a variable follow an identifier directly:


    Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with $this->{"myFunc$VAR"}(); for example.

    Take in mind that using variable variables should be the exception. Newcomers often try to use them too casually, even when arrays would be simpler and more appropriate.

  7. Missing parentheses after language constructs

    Hasty typing may lead to forgotten opening or closing parenthesis for if and for and foreach statements:

     foreach $array as $key) {

    Solution: add the missing opening ( between statement and variable.

     if ($var = pdo_query($sql) {
          $result = …

    The curly { brace does not open the code block, without closing the if expression with the ) closing parenthesis first.

  8. Else does not expect conditions

    else ($var >= 0)

    Solution: Remove the conditions from else or use elseif.

  9. Need brackets for closure

    function() use $var {}

    Solution: Add brackets around $var.

  10. Invisible whitespace

    As mentioned in the reference answer on "Invisible stray Unicode" (such as a non-breaking space), you might also see this error for unsuspecting code like:

    $var = new PDO(...);

    It's rather prevalent in the start of files and for copy-and-pasted code. Check with a hexeditor, if your code does not visually appear to contain a syntax issue.

See also

Convert Datetime column from UTC to local time in select statement

This function will convert a UTC time to EST time with DST adjustment. You can change your designed time zone name in this function, or get it from registry:

Create Function fnConvertUTCTimetoESTTime(
    @UTCTime as datetime
returns datetime
    return convert(datetime, convert(varchar(23), @UTCTime AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time', 121), 121)

select dbo.fnConvertUTCTimetoESTTime ('2020-3-8 5:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 6:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 7:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 8:00:00.000')

--returns 0:00am, 1:00am, 3:00am, 4:00am

select dbo.fnConvertUTCTimetoESTTime ('2020-11-1 4:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 5:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 6:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 7:00:00.000')

--returns 0:00am, 1:00am, 1:00am, 2:00am

Note you can not just return "@UTCTime AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time'" as the result because this result is actually a UTC time in EST format (when you compare this "fake" EST time or include it in an order clause it will be converted back to a UTC time).

Select DISTINCT individual columns in django?

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}


>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

Can I use jQuery with Node.js?

At the time of writing there also is the maintained Cheerio.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here:

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

a {_x000D_
    background-color: #FF0;_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
<a>Navigation Link</a>

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(``, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(``, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            .then(response => console.log(response.text()))
            .catch(err => {

PHP Code

This is the server-side code in upload.php.

    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);

How do you remove an array element in a foreach loop?

As has already been mentioned, you’d want to do a foreach with the key, and unset using the key – but note that mutating an array during iteration is in general a bad idea, though I’m not sure on PHP’s rules on this offhand.

String to list in Python

Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Finding longest string in array

function allLongestStrings(array) {
    const newArr=[];
    let temp =    Math.max(...( => el.length)));    
     array.forEach(item => {
        if(temp == item.length){
    return newArr;

Flash CS4 refuses to let go

What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.

Java: Calling a super method which calls an overridden method

The keyword super doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1() by calling super, that doesn't influence any other method call that you might make in the future.

That means there is no direct way to call SuperClass.method2() from SuperClass.method1() without going though SubClass.method2() unless you're working with an actual instance of SuperClass.

You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)).

[EDIT] There still seems to be some confusion. Let me try a different explanation.

When you invoke foo(), you actually invoke Java simply lets you omit the this. In the example in the question, the type of this is SubClass.

So when Java executes the code in SuperClass.method1(), it eventually arrives at this.method2();

Using super doesn't change the instance pointed to by this. So the call goes to SubClass.method2() since this is of type SubClass.

Maybe it's easier to understand when you imagine that Java passes this as a hidden first parameter:

public class SuperClass
    public void method1(SuperClass this)
        System.out.println("superclass method1");
        this.method2(this); // <--- this == mSubClass

    public void method2(SuperClass this)
        System.out.println("superclass method2");


public class SubClass extends SuperClass
    public void method1(SubClass this)
        System.out.println("subclass method1");

    public void method2(SubClass this)
        System.out.println("subclass method2");

public class Demo 
    public static void main(String[] args) 
        SubClass mSubClass = new SubClass();

If you follow the call stack, you can see that this never changes, it's always the instance created in main().

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

I had this problem with only one service with constructor based dependency injection with 2019.2.4 version of IntelliJ. I found it helpful to change the name of the service (shift + f6) and then discard the changes from the git level.

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

Hello here is a simple solution,

Just go to File -> Convert to a C/C++ Autotools Project Select your project files appropriately.

Inclusions will be added to your project file

Call asynchronous method in constructor?

You could put the async calls in a separate method and call that method in the constructor. Although, this may lead to a situation where some variable values not being available at the time you expect them.

 public NewTravelPageVM(){

 async void  GetVenues(){
   var locator = CrossGeolocator.Current;
   var position = await locator.GetPositionAsync();
   Venues = await Venue.GetVenues(position.Latitude, position.Longitude);

Hide separator line on one UITableViewCell

In your UITableViewCell subclass, override layoutSubviews and hide the _UITableViewCellSeparatorView. Works under iOS 10.

override func layoutSubviews() {

    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true

What is the problem with shadowing names defined in outer scopes?

There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda, but miss one of the places it is used in the function's body... Now data refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError if you didn't have a global name data.

Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

What should I use to open a url instead of urlopen in urllib3

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

How to create a remote Git repository from a local one?

There is an interesting difference between the two popular solutions above:

  1. If you create the bare repository like this:

    cd     /outside_of_any_repo
    mkdir  my_remote.git
    cd     my_remote.git
    git init --bare

and then

cd  /your_path/original_repo
git remote add origin /outside_of_any_repo/my_remote.git
git push --set-upstream origin master

Then git sets up the configuration in 'original_repo' with this relationship:

original_repo origin --> /outside_of_any_repo/my_remote.git/

with the latter as the upstream remote. And the upstream remote doesn't have any other remotes in its configuration.

  1. However, if you do it the other way around:

    (from in directory original_repo)
    cd ..
    git clone --bare original_repo  /outside_of_any_repo/my_remote.git

then 'my_remote.git' winds up with its configuration having 'origin' pointing back to 'original_repo' as a remote, with a remote.origin.url equating to local directory path, which might not be appropriate if it is going to be moved to a server.

While that "remote" reference is easy to get rid of later if it isn't appropriate, 'original_repo' still has to be set up to point to 'my_remote.git' as an up-stream remote (or to wherever it is going to be shared from). So technically, you can arrive at the same result with a few more steps with approach #2. But #1 seems a more direct approach to creating a "central bare shared repo" originating from a local one, appropriate for moving to a server, with fewer steps involved. I think it depends on the role you want the remote repo to play. (And yes, this is in conflict with the documentation here.)

Caveat: I learned the above (at this writing in early August 2019) by doing a test on my local system with a real repo, and then doing a file-by-file comparison between the results. But! I am still learning, so there could be a more correct way. But my tests have helped me conclude that #1 is my currently-preferred method.

Why number 9 in kill -9 command in unix?

Both are same as kill -sigkill processID, kill -9 processID. Its basically for forced termination of the process.

What is a void pointer in C++?

Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

General Syntax:

void* pointer_variable;

void *pVoid; // pVoid is a void pointer

A void pointer can point to objects of any data type:

int nValue;
float fValue;

struct Something
    int nValue;
    float fValue;

Something sValue;

void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid

However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

int nValue = 5;
void *pVoid = &nValue;

// can not dereference pVoid because it is a void pointer

int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Source: link

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

this.setState((state =>{_x000D_

How to read json file into java with simple JSON library

The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.

As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...

  JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");

    String city = (String) person.get("city");

    String job = (String) person.get("job");

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)

For reference, see "Example 1" on the json-simple decoding example page.

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

In my case, there was no string on which i was calling appendChild, the object i was passing on appendChild argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0]) instead of divel.appendChild(childel) and it worked. Hope it help someone.

How to redirect from one URL to another URL?

window.location.href = "URL2"

inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.

Ant task to run an Ant target only if a file exists?

Since Ant 1.8.0 there's apparently also resourceexists


Tests a resource for existance. since Ant 1.8.0

The actual resource to test is specified as a nested element.

An example:

  <file file="${file}"/>

I was about rework the example from the above good answer to this question, and then I found this

As of Ant 1.8.0, you may instead use property expansion; a value of true (or on or yes) will enable the item, while false (or off or no) will disable it. Other values are still assumed to be property names and so the item is enabled only if the named property is defined.

Compared to the older style, this gives you additional flexibility, because you can override the condition from the command line or parent scripts:

<target name="-check-use-file" unless="file.exists">
    <available property="file.exists" file="some-file"/>
<target name="use-file" depends="-check-use-file" if="${file.exists}">
    <!-- do something requiring that file... -->
<target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>

from the ant manual at

Hopefully this example is of use to some. They're not using resourceexists, but presumably you could?.....

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Change Activity's theme programmatically

user1462299's response works great, but if you include fragments, they will use the original activities theme. To apply the theme to all fragments as well you can override the getTheme() method of the Context instead:

public Resources.Theme getTheme() {
    Resources.Theme theme = super.getTheme();
        theme.applyStyle(, true);
    // you could also use a switch if you have many themes that could apply
    return theme;

You do not need to call setTheme() in the onCreate() Method anymore. You are overriding every request to get the current theme within this context this way.

Center a position:fixed element

This one worked the best for me:

    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

How to get the last N records in mongodb?

If you use MongoDB compass, you can use sort filed to filter,

enter image description here

How to generate javadoc comments in Android Studio

  • Another way to add java docs comment is press : Ctrl + Shift + A >> show a popup >> type : Add javadocs >> Enter .

  • Ctrl + Shirt + A: Command look-up (autocomplete command name)

enter image description here

How to add default value for html <textarea>?

You can use placeholder Attribute, which doesn't add a default value but might be what you are looking out for :

<textarea placeholder="this text will show in the textarea"></textarea>

Check it out here - enter image description here

Important Note ( As suggested by Jon Brave in the comments ) :

Placeholder Attribute does not set the value of a textarea. Rather "The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value" [and it disappears as soon as user clicks into the textarea]. It will never act as "the default value" for the control. If you want that, you must put the desired text inside the Here is the actual default value, as per other answers here

Set space between divs

For folks searching for solution to set spacing between N divs, here is another approach using pseudo selectors:

div:not(:last-child) {
  margin-right: 40px;

You can also combine child pseudo selectors:

div:not(:first-child):not(:last-child) {
  margin-left: 20px;
  margin-right: 20px;

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */

/* iPhone 4 - 5s ----------- */
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */

/* iPhone 6 ----------- */
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */

/* iPhone 6+ ----------- */
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */


At this point, I would definitely consider using em values instead of pixels. For more information, check this post:

When saving, how can you check if a field has changed?

Essentially, you want to override the __init__ method of models.Model so that you keep a copy of the original value. This makes it so that you don't have to do another DB lookup (which is always a good thing).

class Person(models.Model):
    name = models.CharField()

    __original_name = None

    def __init__(self, *args, **kwargs):
        super(Person, self).__init__(*args, **kwargs)
        self.__original_name =

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        if != self.__original_name:
            # name changed - do something here

        super(Person, self).save(force_insert, force_update, *args, **kwargs)
        self.__original_name =

SQL Server, division returns zero

Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);