Programs & Examples On #Richedit control

Accessing @attribute from SimpleXML

If you're looking for a list of these attributes though, XPath will be your friend

print_r($xml->xpath('@token'));

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

JavaScriptSerializer - JSON serialization of enum as string

A slightly more future-proof option

Facing the same question, we determined that we needed a custom version of StringEnumConverter to make sure that our enum values could expand over time without breaking catastrophically on the deserializing side (see background below). Using the SafeEnumConverter below allows deserialization to finish even if the payload contains a value for the enum that does not have a named definition, closer to how int-to-enum conversion would work.

Usage:

[SafeEnumConverter]
public enum Colors
{
    Red,
    Green,
    Blue,
    Unsupported = -1
}

or

[SafeEnumConverter((int) Colors.Blue)]
public enum Colors
{
    Red,
    Green,
    Blue
}

Source:

public class SafeEnumConverter : StringEnumConverter
{
    private readonly int _defaultValue;

    public SafeEnumConverter()
    {
        // if you've been careful to *always* create enums with `0` reserved
        // as an unknown/default value (which you should), you could use 0 here. 
        _defaultValue = -1;
    }

    public SafeEnumConverter(int defaultValue)
    {
        _defaultValue = defaultValue;
    }

    /// <summary>
    /// Reads the provided JSON and attempts to convert using StringEnumConverter. If that fails set the value to the default value.
    /// </summary>
    /// <returns>The deserialized value of the enum if it exists or the default value if it does not.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        try
        {
            return base.ReadJson(reader, objectType, existingValue, serializer);
        }
        catch
        {
            return Enum.Parse(objectType, $"{_defaultValue}");
        }
    }

    public override bool CanConvert(Type objectType)
    {
        return base.CanConvert(objectType) && objectType.GetTypeInfo().IsEnum;
    }
}

Background

When we looked at using the StringEnumConverter, the problem we had is that we also needed passivity for cases when a new enum value was added, but not every client was immediately aware of the new value. In these cases, the StringEnumConverter packaged with Newtonsoft JSON throws a JsonSerializationException similar to "Error converting value SomeString to type EnumType" and then the whole deserialization process fails. This was a deal breaker for us, because even if the client planned on ignoring/discarding the property value that it didn't understand, it still needed to be capable of deserializing the rest of the payload!

Simulate limited bandwidth from within Chrome?

As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

RabbitMQ / AMQP: single queue, multiple consumers for same message?

I think you should check sending your messages using the fan-out exchanger. That way you willl receiving the same message for differents consumers, under the table RabbitMQ is creating differents queues for each one of this new consumers/subscribers.

This is the link for see the tutorial example in javascript https://www.rabbitmq.com/tutorials/tutorial-one-javascript.html

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

It's hard to tell for sure because you haven't included many details, but I think what is going on is that there are <% ... %> code blocks inside your Page.Header (which is referring to <head runat="server"> - possibly in a master page). Therefore, when you try to add an item to the Controls collection of that control, you get the error message in the title of this question.

If I'm right, then the workaround is to wrap a <asp:placeholder runat="server"> tag around the <% ... %> code block. This makes the code block a child of the Placeholder control, instead of being a direct child of the Page.Header control, but it doesn't change the rendered output at all. Now that the code block is not a direct child of Page.Header you can add things to the header's controls collection without error.

Again, there is a code block somewhere or you wouldn't be seeing this error. If it's not in your aspx page, then the first place I would look is the file referenced by the MasterPageFile attribute at the top of your aspx.

Close popup window

In my case, I just needed to close my pop-up and redirect the user to his profile page when he clicks "ok" after reading some message I tried with a few hacks, including setTimeout + self.close(), but with IE, this was closing the whole tab...

Solution : I replaced my link with a simple submit button.
<button type="submit" onclick="window.location.href='profile.html';">buttonText</button>. Nothing more.

This may sound stupid, but I didn't think to such a simple solution, since my pop-up did not have any form.

I hope it will help some front-end noobs like me !

How to remove stop words using nltk or python

Although the question is a bit old, here is a new library, which is worth mentioning, that can do extra tasks.

In some cases, you don't want only to remove stop words. Rather, you would want to find the stopwords in the text data and store it in a list so that you can find the noise in the data and make it more interactive.

The library is called 'textfeatures'. You can use it as follows:

! pip install textfeatures
import textfeatures as tf
import pandas as pd

For example, suppose you have the following set of strings:

texts = [
    "blue car and blue window",
    "black crow in the window",
    "i see my reflection in the window"]

df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df

Now, call the stopwords() function and pass the parameters you want:

tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns

The result is going to be:

    text                                 stopwords
0   blue car and blue window             [and]
1   black crow in the window             [in, the]
2   i see my reflection in the window    [i, my, in, the]

As you can see, the last column has the stop words included in that docoument (record).

Having the output of a console application in Visual Studio instead of the console

regarding System.Diagnostics.Debug producing a lot of "junk" in the Output window: You can turn that off by right clicking in the output window. E.g. there's an item "Module Load Messages" which you want to disable and an item "Program Output" which you want to keep.

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:

The HTML:

<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;
}

To see how the project turns out, here is a JSFiddle for the above code: http://jsfiddle.net/SplashHero/qmccsc06/1/

numpy: most efficient frequency counts for unique values in an array

Most of simple problems get complicated because simple functionality like order() in R that gives a statistical result in both and descending order is missing in various python libraries. But if we devise our thinking that all such statistical ordering and parameters in python are easily found in pandas, we can can result sooner than looking in 100 different places. Also, development of R and pandas go hand-in-hand because they were created for same purpose. To solve this problem I use following code that gets me by anywhere:

unique, counts = np.unique(x, return_counts=True)
d = {'unique':unique, 'counts':count}  # pass the list to a dictionary
df = pd.DataFrame(d) #dictionary object can be easily passed to make a dataframe
df.sort_values(by = 'count', ascending=False, inplace = True)
df = df.reset_index(drop=True) #optional only if you want to use it further

error: invalid type argument of ‘unary *’ (have ‘int’)

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

#include <stdio.h>                                                              
int main(){
    int b=10;
    int *a;
    a=&b;
    int **c;
    c=&a;
    printf("%d",(**c));   //successfully prints 10
    return 0;
}

Looping through all the properties of object php

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

How do I get cURL to not show the progress bar?

Not sure why it's doing that. Try -s with the -o option to set the output file instead of >.

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

How to format a float in javascript?

If you want the string without round you can use this RegEx (maybe is not the most efficient way... but is really easy)

(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'

Using .text() to retrieve only text not nested in child tags

I presume this would be a fine solution also - if you want to get contents of all text nodes that are direct children of selected element.

$(selector).contents().filter(function(){ return this.nodeType == 3; }).text();

Note: jQuery documentation uses similar code to explain contents function: https://api.jquery.com/contents/

P.S. There's also a bit uglier way to do that, but this shows more in depth how things work, and allows for custom separator between text nodes (maybe you want a line break there)

$(selector).contents().filter(function(){ return this.nodeType == 3; }).map(function() { return this.nodeValue; }).toArray().join("");

Cannot connect to MySQL 4.1+ using old authentication

If you do not have control of the server

I just had this issue, and was able to work around it.

First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.

Run these queries:

SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');

In your PHP script, change your mysql_connect function to include the client flag 1:

define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);

This allowed me to connect successfully.

Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!

Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:

<?php const DB = [ 'host' => '...', # localhost may not work on some hosting 
    'user' => '...',
    'pwd' => '...', ]; 

if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
    die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
    die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
    die($query);
}

echo "Excellent, mysqli will now work"; 
?>

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

To evaporate the warning, you can use libxml_use_internal_errors(true)

// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');

// set error level
$internalErrors = libxml_use_internal_errors(true);

// load HTML
$document->loadHTML($html);

// Restore error level
libxml_use_internal_errors($internalErrors);

Select rows from a data frame based on values in a vector

Have a look at ?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

You could also use ?is.element:

dt[is.element(dt$fct, vc),]

What is Domain Driven Design?

I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans

NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

Function or sub to add new row and data to table

Is this what you are looking for?

Option Explicit

Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
    Dim lLastRow As Long
    Dim iHeader As Integer

    With ActiveSheet.ListObjects(strTableName)
        'find the last row of the list
        lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
        'shift from an extra row if list has header
        If .Sort.Header = xlYes Then
            iHeader = 1
        Else
            iHeader = 0
        End If
    End With
    'add the data a row after the end of the list
    ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub

It handles both cases whether you have header or not.

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Update multiple values in a single statement

Try this:

 Update MasterTbl Set
    TotalX = Sum(D.X),    
    TotalY = Sum(D.Y),    
    TotalZ = Sum(D.Z)
 From MasterTbl M Join DetailTbl D
    On D.MasterID = M.MasterID

Depending on which database you are using, if that doesn't work, then try this (this is non-standard SQL but legal in SQL Server):

 Update M Set
    TotalX = Sum(D.X),    
    TotalY = Sum(D.Y),    
    TotalZ = Sum(D.Z)
 From MasterTbl M Join DetailTbl D
     On D.MasterID = M.MasterID

Check if inputs are empty using jQuery

A clean CSS-only solution this would be:

input[type="radio"]:read-only {
        pointer-events: none;
}

Can one do a for each loop in java in reverse order?

All answers above only fulfill the requirement, either by wrapping another method or calling some foreign code outside;

Here is the solution copied from the Thinking in Java 4th edition, chapter 11.13.1 AdapterMethodIdiom;

Here is the code:

// The "Adapter Method" idiom allows you to use foreach
// with additional kinds of Iterables.
package holding;
import java.util.*;

@SuppressWarnings("serial")
class ReversibleArrayList<T> extends ArrayList<T> {
  public ReversibleArrayList(Collection<T> c) { super(c); }
  public Iterable<T> reversed() {
    return new Iterable<T>() {
      public Iterator<T> iterator() {
        return new Iterator<T>() {
          int current = size() - 1; //why this.size() or super.size() wrong?
          public boolean hasNext() { return current > -1; }
          public T next() { return get(current--); }
          public void remove() { // Not implemented
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }
}   

public class AdapterMethodIdiom {
  public static void main(String[] args) {
    ReversibleArrayList<String> ral =
      new ReversibleArrayList<String>(
        Arrays.asList("To be or not to be".split(" ")));
    // Grabs the ordinary iterator via iterator():
    for(String s : ral)
      System.out.print(s + " ");
    System.out.println();
    // Hand it the Iterable of your choice
    for(String s : ral.reversed())
      System.out.print(s + " ");
  }
} /* Output:
To be or not to be
be to not or be To
*///:~

What is the best way to compare floats for almost-equality in Python?

In terms of absolute error, you can just check

if abs(a - b) <= error:
    print("Almost equal")

Some information of why float act weird in Python https://youtu.be/v4HhvoNLILk?t=1129

You can also use math.isclose for relative errors

How do I create directory if it doesn't exist to create a file?

var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

var file = new FileInfo(filePath);

file.Directory.Create(); If the directory already exists, this method does nothing.

var sw = new StreamWriter(filePath, true);

sw.WriteLine(Enter your message here);

sw.Close();

Use .htaccess to redirect HTTP to HTTPs

Redirect from http to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

This will work for sure!

Why is Thread.Sleep so harmful

SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete.

SCENARIO 2 - timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?).

So if while+Thread.Sleep works, why complicate things? Only syntax lawyers would, be practical!

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....

Declare an empty two-dimensional array in Javascript?

ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))       

_x000D_
_x000D_
let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
);
_x000D_
_x000D_
_x000D_

Why does Node.js' fs.readFile() return a buffer instead of string?

This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):

Why does Node.js' fs.readFile() return a buffer instead of string?

Because files aren't always text

Even if you as the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.

Because reading text files is tricky

Even if Node knew it were to read a text file, it still would have no idea which character encoding is used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.

There are ways to guess the character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.

Buffers to the rescue!

So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.

And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

semaphore implementation

The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:

  • POSIX IPC API, which is a standard API
  • System V API, which is coming from the old Unix world, but practically available almost all Unix systems

Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.

To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.

These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:

  • it builds on semaphore sets, so once you created an object with semget() that is a set of semaphores rather then a single one
  • the System V API allows you to do atomic operations on these sets. so you can modify or wait for multiple semaphores in a set
  • the SysV API allows you to wait for a semaphore to reach a threshold rather than only being non-zero. waiting for a non-zero threshold is also supported, but my previous sentence implies that
  • the semaphore resources are pretty limited on every unixes. you can check these with the 'ipcs' command
  • there is an undo feature of the System V semaphores, so you can make sure that abnormal program termination doesn't leave your semaphores in an undesired state

C# Convert a Base64 -> byte[]

This may be helpful

byte[] bytes = System.Convert.FromBase64String(stringInBase64);

Value of type 'T' cannot be converted to

Change this line:

if (typeof(T) == typeof(string))

For this line:

if (t.GetType() == typeof(string))

Checking if a number is an Integer in Java

// in C language.. but the algo is same

#include <stdio.h>

int main(){
  float x = 77.6;

  if(x-(int) x>0)
    printf("True! it is float.");
  else
    printf("False! not float.");        

  return 0;
}

Error in <my code> : object of type 'closure' is not subsettable

I had this issue was trying to remove a ui element inside an event reactive:

myReactives <- eventReactive(input$execute, {
    ... # Some other long running function here
    removeUI(selector = "#placeholder2")
})

I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

How to install SignTool.exe for Windows 10

You need to install the Windows 10 SDK.

  1. Visual Studio 2015 Update 1 contains it already, but it is not installed by default. You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change".

Visual Studio 2015 setup will start. Select "Modify".

In Visual Studio components list find "Universal Windows App Development Tools", open the list of sub-items and select "Windows 10 SDK (10.0.10240)".

Windows 10 SDK in VS 2015 Update 1 Setup

  1. Of cause you can install Windows 10 SDK directly from Microsoft: https://go.microsoft.com/fwlink/?LinkID=698771

As josant already wrote - when the installation finishes you will find the SignTool.exe in the folders:

  • x86 -> c:\Program Files (x86)\Windows Kits\10\bin\x86
  • x64 -> c:\Program Files (x86)\Windows Kits\10\bin\x64\

How to wait for a process to terminate to execute another process in batch file

I liked the "START /W" answer, though for my situation I found something even more basic. My processes were console applications. And in my ignorance I thought I would need something special in BAT syntax to make sure that the 1st one completed before the 2nd one started. However BAT appears to make a distinction between console apps and windows apps, and it executes them a little differently. The OP shows that window apps will get launched as an asynchronous call from BAT. But for console apps, that are invoked synchronously, inside the same command window as the BAT itself is running in.

For me it was actually better not to use "START /W", because everything could run inside one command window. The annoying thing about "START /W" is that it will spawn a new command window to execute your console application in.

How should I read a file line-by-line in Python?

f = open('test.txt','r')
for line in f.xreadlines():
    print line
f.close()

Matplotlib color according to class labels

Assuming that you have your data in a 2d array, this should work:

import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()

You can also set a cmap attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter line with:

pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)

A list of color maps can be found here

Function is not defined - uncaught referenceerror

Please check whether you have provided js references correctly. JQuery files first and then your custom files. Since you are using '$' in your js methods.

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

How to check whether an array is empty using PHP?

I ran the benchmark included at the end of the post. To compare the methods:

  • count($arr) == 0 : count
  • empty($arr) : empty
  • $arr == [] : comp
  • (bool) $arr : cast

and got the following results

Contents  \method |    count     |    empty     |     comp     |     cast     |
------------------|--------------|--------------|--------------|--------------|
            Empty |/* 1.213138 */|/* 1.070011 */|/* 1.628529 */|   1.051795   |
          Uniform |/* 1.206680 */|   1.047339   |/* 1.498836 */|/* 1.052737 */|
          Integer |/* 1.209668 */|/* 1.079858 */|/* 1.486134 */|   1.051138   |
           String |/* 1.242137 */|   1.049148   |/* 1.630259 */|/* 1.056610 */|
            Mixed |/* 1.229072 */|/* 1.068569 */|/* 1.473339 */|   1.064111   |
      Associative |/* 1.206311 */|   1.053642   |/* 1.480637 */|/* 1.137740 */|
------------------|--------------|--------------|--------------|--------------|
            Total |/* 7.307005 */|   6.368568   |/* 9.197733 */|/* 6.414131 */|

The difference between empty and casting to a boolean are insignificant. I've run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.

#!/usr/bin/php
<?php

//    012345678
$nt = 90000000;

$arr0 = [];
$arr1 = [];
$arr2 = [];
$arr3 = [];
$arr4 = [];
$arr5 = [];

for ($i = 0; $i < 500000; $i++) {
    $arr1[] = 0;
    $arr2[] = $i;
    $arr3[] = md5($i);
    $arr4[] = $i % 2 ? $i : md5($i);
    $arr5[md5($i)] = $i;
}

$t00 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr0) == 0;
}
$t01 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr0);
}
$t02 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr0 == [];
}
$t03 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr0;
}
$t04 = microtime(true);

$t10 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr1) == 0;
}
$t11 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr1);
}
$t12 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr1 == [];
}
$t13 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr1;
}
$t14 = microtime(true);

/* ------------------------------ */

$t20 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr2) == 0;
}
$t21 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr2);
}
$t22 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr2 == [];
}
$t23 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr2;
}
$t24 = microtime(true);

/* ------------------------------ */

$t30 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr3) == 0;
}
$t31 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr3);
}
$t32 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr3 == [];
}
$t33 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr3;
}
$t34 = microtime(true);

/* ------------------------------ */

$t40 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr4) == 0;
}
$t41 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr4);
}
$t42 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr4 == [];
}
$t43 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr4;
}
$t44 = microtime(true);

/* ----------------------------------- */

$t50 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr5) == 0;
}
$t51 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr5);
}
$t52 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr5 == [];
}
$t53 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr5;
}
$t54 = microtime(true);

/* ----------------------------------- */

$t60 = $t00 + $t10 + $t20 + $t30 + $t40 + $t50;
$t61 = $t01 + $t11 + $t21 + $t31 + $t41 + $t51;
$t62 = $t02 + $t12 + $t22 + $t32 + $t42 + $t52;
$t63 = $t03 + $t13 + $t23 + $t33 + $t43 + $t53;
$t64 = $t04 + $t14 + $t24 + $t34 + $t44 + $t54;

/* ----------------------------------- */

$ts0[1] = number_format(round($t01 - $t00, 6), 6);
$ts0[2] = number_format(round($t02 - $t01, 6), 6);
$ts0[3] = number_format(round($t03 - $t02, 6), 6);
$ts0[4] = number_format(round($t04 - $t03, 6), 6);

$min_idx = array_keys($ts0, min($ts0))[0];
foreach ($ts0 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts0[$idx] = "   $val   ";
    } else {
        $ts0[$idx] = "/* $val */";
    }

}

$ts1[1] = number_format(round($t11 - $t10, 6), 6);
$ts1[2] = number_format(round($t12 - $t11, 6), 6);
$ts1[3] = number_format(round($t13 - $t12, 6), 6);
$ts1[4] = number_format(round($t14 - $t13, 6), 6);

$min_idx = array_keys($ts1, min($ts1))[0];
foreach ($ts1 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts1[$idx] = "   $val   ";
    } else {
        $ts1[$idx] = "/* $val */";
    }

}

$ts2[1] = number_format(round($t21 - $t20, 6), 6);
$ts2[2] = number_format(round($t22 - $t21, 6), 6);
$ts2[3] = number_format(round($t23 - $t22, 6), 6);
$ts2[4] = number_format(round($t24 - $t23, 6), 6);

$min_idx = array_keys($ts2, min($ts2))[0];
foreach ($ts2 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts2[$idx] = "   $val   ";
    } else {
        $ts2[$idx] = "/* $val */";
    }

}

$ts3[1] = number_format(round($t31 - $t30, 6), 6);
$ts3[2] = number_format(round($t32 - $t31, 6), 6);
$ts3[3] = number_format(round($t33 - $t32, 6), 6);
$ts3[4] = number_format(round($t34 - $t33, 6), 6);

$min_idx = array_keys($ts3, min($ts3))[0];
foreach ($ts3 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts3[$idx] = "   $val   ";
    } else {
        $ts3[$idx] = "/* $val */";
    }

}

$ts4[1] = number_format(round($t41 - $t40, 6), 6);
$ts4[2] = number_format(round($t42 - $t41, 6), 6);
$ts4[3] = number_format(round($t43 - $t42, 6), 6);
$ts4[4] = number_format(round($t44 - $t43, 6), 6);

$min_idx = array_keys($ts4, min($ts4))[0];
foreach ($ts4 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts4[$idx] = "   $val   ";
    } else {
        $ts4[$idx] = "/* $val */";
    }

}

$ts5[1] = number_format(round($t51 - $t50, 6), 6);
$ts5[2] = number_format(round($t52 - $t51, 6), 6);
$ts5[3] = number_format(round($t53 - $t52, 6), 6);
$ts5[4] = number_format(round($t54 - $t53, 6), 6);

$min_idx = array_keys($ts5, min($ts5))[0];
foreach ($ts5 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts5[$idx] = "   $val   ";
    } else {
        $ts5[$idx] = "/* $val */";
    }

}

$ts6[1] = number_format(round($t61 - $t60, 6), 6);
$ts6[2] = number_format(round($t62 - $t61, 6), 6);
$ts6[3] = number_format(round($t63 - $t62, 6), 6);
$ts6[4] = number_format(round($t64 - $t63, 6), 6);

$min_idx = array_keys($ts6, min($ts6))[0];
foreach ($ts6 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts6[$idx] = "   $val   ";
    } else {
        $ts6[$idx] = "/* $val */";
    }

}

echo "             |    count     |    empty     |     comp     |     cast     |\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Empty |";
echo $ts0[1] . '|';
echo $ts0[2] . '|';
echo $ts0[3] . '|';
echo $ts0[4] . "|\n";

echo "     Uniform |";
echo $ts1[1] . '|';
echo $ts1[2] . '|';
echo $ts1[3] . '|';
echo $ts1[4] . "|\n";

echo "     Integer |";
echo $ts2[1] . '|';
echo $ts2[2] . '|';
echo $ts2[3] . '|';
echo $ts2[4] . "|\n";

echo "      String |";
echo $ts3[1] . '|';
echo $ts3[2] . '|';
echo $ts3[3] . '|';
echo $ts3[4] . "|\n";

echo "       Mixed |";
echo $ts4[1] . '|';
echo $ts4[2] . '|';
echo $ts4[3] . '|';
echo $ts4[4] . "|\n";

echo " Associative |";
echo $ts5[1] . '|';
echo $ts5[2] . '|';
echo $ts5[3] . '|';
echo $ts5[4] . "|\n";

echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Total |";
echo $ts6[1] . '|';
echo $ts6[2] . '|';
echo $ts6[3] . '|';
echo $ts6[4] . "|\n";

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Order a MySQL table by two columns

Default sorting is ascending, you need to add the keyword DESC to both your orders:

ORDER BY article_rating DESC, article_time DESC

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

Python [Errno 98] Address already in use

If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):

SocketServer.TCPServer.allow_reuse_address = True

(via SocketServer.ThreadingTCPServer - Cannot bind to address after program restart )

This causes the init (constructor) to:

 if self.allow_reuse_address:
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

TSQL DATETIME ISO 8601

You technically have two options when speaking of ISO dates.

In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd or y-m-d. Which are both valid ISO formats.

Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

Because of this, your safest bet is to persist/filter based on the always netural ymd format.

The code:

select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)

adb uninstall failed

If you have problems uninstalling through adb, I can recommend the following tool:

https://github.com/patrickfav/uber-adb-tools

you can use wildcards and supports multiple devices, also has some better error handling than the vanilla ADB (but uses it in background of course). Will work on your platform.

console showcase

Full disclaimer: I am the developer

Why do I have to "git push --set-upstream origin <branch>"?

The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:

git push -u origin <your-local-branch-name>

So if your local branch name is coffee

git push -u origin coffee

Oracle listener not running and won't start

I managed to resolve the issue that caused the configuration to fail on a docker container running the Hortonworks HDP 2.6 Sandbox.

If the initial configuration fails the listener will be running and will have to be killed first:

ps -aux | grep tnslsnr
kill {process id identified above}

Then next step is then to fix the shared memory issue which makes the configuration process fail.

Oracle XE requires 1 Gb of shared memory and fails otherwise (I didn't try 512 mb) according to https://blogs.oracle.com/oraclewebcentersuite/implement-oracle-database-xe-as-docker-containers.

vi /etc/fstab

change/add the line to:

tmpfs    /dev/shm     tmpfs   defaults,size=1024m 0 0

Then reload the configuration by:

mount -a

Keep in mind that the next time you restart the docker container you might have to do 'mount -a'.

What's the meaning of System.out.println in Java?

System is a class in java.lang package. And out is a PrintStream object. Nice explanation @ http://lazy-geeks.blogspot.in/2015/01/what-is-systemoutprintln.html

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

Can you control how an SVG's stroke-width is drawn?

You can use CSS to style the order of stroke and fills. That is, stroke first and then fill second, and get the desired effect.

MDN on paint-order: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order

CSS code:

paint-order: stroke;

jquery to change style attribute of a div class

Style is an attribute so css won't work for it.U can use attr

Change:

$('.handle').css({'style':'left: 300px'});

T0:

$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon

IE Enable/Disable Proxy Settings via Registry

The problem is that IE won't reset the proxy settings until it either

  1. closes, or
  2. has its configuration refreshed.

Below is the code that I've used to get this working:

function Refresh-System
{
  $signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@

$INTERNET_OPTION_SETTINGS_CHANGED   = 39
$INTERNET_OPTION_REFRESH            = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
return $a -and $b
}

Word-wrap in an HTML table

Turns out there's no good way of doing this. The closest I came is adding "overflow:hidden;" to the div around the table and losing the text. The real solution seems to be to ditch table though. Using divs and relative positioning I was able to achieve the same effect, minus the legacy of <table>

2015 UPDATE: This is for those like me who want this answer. After 6 years, this works, thanks to all the contributors.

* { // this works for all but td
  word-wrap:break-word;
}

table { // this somehow makes it work for td
  table-layout:fixed;
  width:100%;
}

How do Python functions handle the types of the parameters that you pass in?

In Python everything has a type. A Python function will do anything it is asked to do if the type of arguments support it.

Example: foo will add everything that can be __add__ed ;) without worrying much about its type. So that means, to avoid failure, you should provide only those things that support addition.

def foo(a,b):
    return a + b

class Bar(object):
    pass

class Zoo(object):
    def __add__(self, other):
        return 'zoom'

if __name__=='__main__':
    print foo(1, 2)
    print foo('james', 'bond')
    print foo(Zoo(), Zoo())
    print foo(Bar(), Bar()) # Should fail

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

Android button font size

<resource>
<style name="button">
<item name="android:textSize">15dp</item>
</style>
<resource>

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

How to use classes from .jar files?

You need to add the jar file in the classpath. To compile your java class:

javac -cp .;jwitter.jar MyClass.java

To run your code (provided that MyClass contains a main method):

java -cp .;jwitter.jar MyClass

You can have the jar file anywhere. The above work if the jar file is in the same directory as your java file.

Is there a splice method for strings?

Louis's spliceSlice method fails when add value is 0 or other falsy values, here is a fix:

function spliceSlice(str, index, count, add) {
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }
  const hasAdd = typeof add !== 'undefined';
  return str.slice(0, index) + (hasAdd ? add : '') + str.slice(index + count);
}

jQuery same click event for multiple elements

We can code like following also, I have used blur event here.

$("#proprice, #proqty").blur(function(){
      var price=$("#proprice").val();
      var qty=$("#proqty").val();
      if(price != '' || qty != '')
      {
          $("#totalprice").val(qty*price);
      }
  });

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

What version of Java is running in Eclipse?

If you want to check if your -vm eclipse.ini option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=....

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

Excel VBA Run-time error '13' Type mismatch

This error occurs when the input variable type is wrong. You probably have written a formula in Cells(4 + i, 57) that instead of =0, the formula = "" have used. So when running this error is displayed. Because empty string is not equal to zero.

enter image description here

Which comes first in a 2D array, rows or columns?

Instinctively one thinks geometrically: horizontal (X) axis and then vertical (Y) axis. This is not, however, the case with a 2D array, rows come first and then columns.

Consider the following analogy: in geometry one walks to the ladder (X axis) and climbs it (Y axis). Conversely, in Java one descends the ladder (rows) and walks away (columns).

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

appending list but error 'NoneType' object has no attribute 'append'

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

Full Page <iframe>

This is cross-browser and fully responsive:

<iframe
  src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
  style="
    position: fixed;
    top: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 999999;
    height: 100%;
  ">
</iframe>

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

Its in the comments of the answers but nobody has posted this as the actual solution.

You just need to add a using statement at the top:

using Microsoft.AspNet.Identity;

Get unique values from a list in python

A Python list:

>>> a = ['a', 'b', 'c', 'd', 'b']

To get unique items, just transform it into a set (which you can transform back again into a list if required):

>>> b = set(a)
>>> print(b)
{'b', 'c', 'd', 'a'}

Start script missing error when running npm start

should avoid using unstable npm version.

I observed one thing that is npm version based issue, npm version 4.6.1 is the stable one but 5.x is unstable because package.json will be configured perfectly while creating with default template if it's a stable version and so we manually don't need to add that scripts.

I got the below issue on the npm 5 so I downgraded to npm 4.6.1 then its worked for me,


ERROR: npm 5 is not supported yet


It looks like you're using npm 5 which was recently released.

Create React Native App doesn't work with npm 5 yet, unfortunately. We recommend using npm 4 or yarn until some bugs are resolved.

You can follow the known issues with npm 5 at: https://github.com/npm/npm/issues/16991


Devas-MacBook-Air:SampleTestApp deva$ npm start npm ERR! missing script: start

Installing specific package versions with pip

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use --no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Navigate to the emulator folder located within Android SDK folder / emulator

cd ${ANDROID_HOME}/emulator

Then type these command to open emulator without android studio:

$ ./emulator -list-avds
$ ./emulator -avd Nexus_5X_API_28_x86

Nexus_5X_API_28_x86 is My AVD you need to give your AVD name

Javascript - Open a given URL in a new tab by clicking a button

I just used target="_blank" under form tag and it worked fine with FF and Chrome where it opens in a new tag but with IE it opens in a new window.

Ineligible Devices section appeared in Xcode 6.x.x

I simply restarted my Mac and my iPhone 6 and the problem was solved. I never had to change my deployment target.

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

How can I split a delimited string into an array in PHP?

If that string comes from a csv file, I would use fgetcsv() (or str_getcsv() if you have PHP V5.3). That will allow you to parse quoted values correctly. If it is not a csv, explode() should be the best choice.

Limit characters displayed in span

You can do this with jQuery :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  _x000D_
  $('.claimedRight').each(function (f) {_x000D_
_x000D_
      var newstr = $(this).text().substring(0,20);_x000D_
      $(this).text(newstr);_x000D_
_x000D_
    });_x000D_
})
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title></title>_x000D_
    <script         src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the first test string. _x000D_
    </span><br>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the second test string. _x000D_
    </span>_x000D_
    _x000D_
    _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Finding length of char array

sizeof returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7] which is 7 * sizeof(char). Since sizeof(char) = 1, the result is 7.

Expanding this to another example:

int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));

would yield 5 * sizeof(int), so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int) might differ)

To return to your problem:

It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.

By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.

All standard functions build upon this definition, so if you call strlen to retrieve the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.

Another thing you might need to know that only because you don't fill the remaining elements of your char[7] with a value, they actually do contain random undefined values.

Hope that helped.

What causes a Python segmentation fault?

I was experiencing this segmentation fault after upgrading dlib on RPI. I tracebacked the stack as suggested by Shiplu Mokaddim above and it settled on an OpenBLAS library.

Since OpenBLAS is also multi-threaded, using it in a muilt-threaded application will exponentially multiply threads until segmentation fault. For multi-threaded applications, set OpenBlas to single thread mode.

In python virtual environment, tell OpenBLAS to only use a single thread by editing:

    $ workon <myenv>
    $ nano .virtualenv/<myenv>/bin/postactivate

and add:

    export OPENBLAS_NUM_THREADS=1 
    export OPENBLAS_MAIN_FREE=1

After reboot I was able to run all my image recognition apps on rpi3b which were previously crashing it.

reference: https://github.com/ageitgey/face_recognition/issues/294

Restore a deleted file in the Visual Studio Code Recycle Bin

If you just deleted the file, know that VSCode 1.52 (Dec. 2020) will support:

Undo file operations in Explorer

Explorer now supports Undo and Redo for all file operations: delete, rename, copy, move, new file and new folder.

Make sure the focus is in the Explorer and trigger the Undo or Redo commands and your last file operation will be undone or redone respectively.
Keep in mind that we have separate undo stacks for the editor and the explorer and we choose which one to undo based on focus.

Explorer Undo -- https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_52/explorer-undo.gif

How can I show figures separately in matplotlib?

As of November 2020, in order to show one figure at a time, the following works:

import matplotlib.pyplot as plt

f1, ax1 = plt.subplots()
ax1.plot(range(0,10))
f1.show()
input("Close the figure and press a key to continue")
f2, ax2 = plt.subplots()
ax2.plot(range(10,20))
f2.show()
input("Close the figure and press a key to continue")

The call to input() prevents the figure from opening and closing immediately.

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

Get only the Date part of DateTime in mssql

This may also help:

SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
                                        -- Oct  2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008                  
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02           
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) --  hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        -- Oct  2 2008 11:02:44:013AM   
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
                                        --  02 Oct 2008 11:02:07:577     
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) --  yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
                                        --  2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          -- mon yyyy

The Source

Run parallel multiple commands at once in the same terminal

Based on comment of @alessandro-pezzato. Run multiples commands by using & between the commands.

Example:

$ sleep 3 & sleep 5 & sleep 2 &

It's will execute the commands in background.

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

python : list index out of range error while iteratively popping elements

You are reducing the length of your list l as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.

It looks like what you want to do is:

l = [x for x in l if x != 0]

which will return a copy of l without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x, since non-zero numbers evaluate to True.

There is no such thing as a loop termination condition of i < len(l), in the way you've written the code, because len(l) is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:

i = 0
while i < len(l):
   if l[i] == 0:
       l.pop(i)
   else:
       i += 1

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Just to add,

const foo = function(){ return "foo" } //this doesn't add a semicolon here.
(function (){
    console.log("aa");
})()

see this, using immediately invoked function expression(IIFE)

What's the best way to cancel event propagation between nested ng-click calls?

If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.

Simulate low network connectivity for Android

I'm surprised nobody mentioned this. You can tether via Bluetooth, and separate them by ten+ meters(or less with obstacles). You've got a real bad connection. No microwave, no elevator, no software needed.

Best way to implement keyboard shortcuts in a Windows Forms application?

On your Main form

  1. Set KeyPreview to True
  2. Add KeyDown event handler with the following code

    private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.N)
        {
            SearchForm searchForm = new SearchForm();
            searchForm.Show();
        }
    }
    

Repeat a string in JavaScript a number of times

In ES2015/ES6 you can use "*".repeat(n)

So just add this to your projects, and your are good to go.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };

Replace String in all files in Eclipse

Tonny Madsen said it right, but sometimes this is too simplistic.

What if you want to be more selective in your replacements since not all replacements are correct for what you're trying to do?

Here's how to get more granularity to do the replacements only in certain folders, files, or instances:

First, do like he said:

  • Click Search --> File... OR press Ctrl + H and choose the "File Search" tab.
  • Enter text, file pattern and choose your Workspace or Working Set.

Then:

  • Click Search
  • When your results come up, make some folder, file, or instance selections by Ctrl + clicking on the ones you'd like to select. Ex: here's my selection. I've chosen 3 instances, 1 file, and 1 folder:

enter image description here

  • Now, right-click on your selection and go to --> Replace Selected.... Here's a screenshot of that:

enter image description here

  • Enter what you'd like to replace it "With". In my case you can see it says it is "Replacing 190 matches in 4 files". Now click OK.

enter image description here

Voilà!

References:

PHP Array to CSV

Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php

Best HTML5 markup for sidebar

Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:

<aside class="sidebar">
    <article id="widget_1" class="widget">...</article>
    <article id="widget_2" class="widget">...</article>
    <article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->

I think it's clear that <aside> is the appropriate element as long as it's outside the main <article> element.

Now, I'm thinking that <article> is also appropriate for each widget in the aside. In the words of the W3C:

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

c++ bool question

false == 0 and true = !false

i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

Some examples to clarify:

if(0)          // false
if(1)          // true
if(2)          // true
if(0 == false) // true
if(0 == true)  // false
if(1 == false) // false
if(1 == true)  // true
if(2 == false) // false
if(2 == true)  // false
cout << false  // 0
cout << true   // 1

true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

How to quickly and conveniently disable all console.log statements in my code?

I wrote this:

//Make a copy of the old console.
var oldConsole = Object.assign({}, console);

//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
    if (bool) {
        //Rewrites the disable function with the original one.
        console[this.name] = oldConsole[this.name];
        //Make sure the setEnable will be callable from original one.
        console[this.name].setEnabled = setEnabled;
    } else {
        //Rewrites the original.
        var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
        //Defines the name, to remember.
        Object.defineProperty(fn, "name", {value: this.name});
        //replace the original with the empty one.
        console[this.name] = fn;
        //set the enable function
        console[this.name].setEnabled = setEnabled

    }
}

Unfortunately it doesn't work on use strict mode.

So using console.fn.setEnabled = setEnabled and then console.fn.setEnabled(false) where fn could be almost any console function. For your case would be:

console.log.setEnabled = setEnabled;
console.log.setEnabled(false);

I wrote this too:

var FLAGS = {};
    FLAGS.DEBUG = true;
    FLAGS.INFO = false;
    FLAGS.LOG = false;
    //Adding dir, table, or other would put the setEnabled on the respective console functions.

function makeThemSwitchable(opt) {
    var keysArr = Object.keys(opt);
    //its better use this type of for.
    for (var x = 0; x < keysArr.length; x++) {
        var key = keysArr[x];
        var lowerKey = key.toLowerCase();
        //Only if the key exists
        if (console[lowerKey]) {
            //define the function
            console[lowerKey].setEnabled = setEnabled;
            //Make it enabled/disabled by key.
            console[lowerKey].setEnabled(opt[key]);
        }
    }
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);

so then you just need to put in the FLAGS the default value (before execute the above code), like FLAGS.LOG = false and the log function would be disabled by default, and still you could enabled it calling console.log.setEnabled(true)

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

tl;dr

  • Use modern java.time classes.
  • Never use Date/Calendar/SimpleDateFormat classes.

Example:

ZonedDateTime                                // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now(                                        // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )              // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo(                                // Lop off finer part of this value.
    ChronoUnit.MILLIS                        // Specify level of truncation via `ChronoUnit` enum object.
)                                            // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format(                                     // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME    // This standard ISO 8601 format is close to your desired output.
)                                            // Returns a `String`.
.replace( "T" , " " )                        // Replace `T` in middle with a SPACE.

java.time

The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.

want current date and time

Capture the current moment in UTC using Instant.

Instant instant = Instant.now() ;

To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;

The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.

ZonedDateTime
.now( 
    ZoneId.of( "Pacific/Auckland" ) 
)
.truncatedTo(
    ChronoUnit.MILLIS
)

in “dd/MM/yyyy HH:mm:ss.SS” format

I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.

But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.

String output = 
    zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
    .replace( "T" , " " )  
;

sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");

Date date = sdf1.parse(strDate);

Never exchange date-time values using text intended for presentation to humans.

Instead, use the standard formats defined for this very purpose, found in ISO 8601.

The java.time use these ISO 8601 formats by default when parsing/generating strings.

Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.

Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;

2018-01-23T01:23:45.123456789Z

This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How can I check the extension of a file?

if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"

How do I access previous promise results in a .then() chain?

Break the chain

When you need to access the intermediate values in your chain, you should split your chain apart in those single pieces that you need. Instead of attaching one callback and somehow trying to use its parameter multiple times, attach multiple callbacks to the same promise - wherever you need the result value. Don't forget, a promise just represents (proxies) a future value! Next to deriving one promise from the other in a linear chain, use the promise combinators that are given to you by your library to build the result value.

This will result in a very straightforward control flow, clear composition of functionalities and therefore easy modularisation.

function getExample() {
    var a = promiseA(…);
    var b = a.then(function(resultA) {
        // some processing
        return promiseB(…);
    });
    return Promise.all([a, b]).then(function([resultA, resultB]) {
        // more processing
        return // something using both resultA and resultB
    });
}

Instead of the parameter destructuring in the callback after Promise.all that only became avail­able with ES6, in ES5 the then call would be replaced by a nifty helper method that was provided by many promise libraries (Q, Bluebird, when, …): .spread(function(resultA, resultB) { ….

Bluebird also features a dedicated join function to replace that Promise.all+spread combination with a simpler (and more efficient) construct:

…
return Promise.join(a, b, function(resultA, resultB) { … });

A variable modified inside a while loop is not remembered

echo -e $lines | while read line 
    ...
done

The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

while read line
do
    if [[ "$line" == "second line" ]]
    then
        foo=2
        echo "Variable \$foo updated to $foo inside if inside while loop"
    fi
    echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"

You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

lines=$'first line\nsecond line\nthird line'
while read line; do
    ...
done <<< "$lines"

<embed> vs. <object>

Some other options:

<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>

<object type="application/pdf" data="#request.localhost#_includes/filename.pdf" 
        width="100%" height="100%">
  <param name="src" value="#request.localhost#_includes/filename.pdf">
</object>

Regex to extract substring, returning 2 results for some reason

I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.

RegEx: How can I match all numbers greater than 49?

I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:

First I match the numbers 50 through 99 (with possible leading zeros):

0*[5-9]\d

Then match numbers of 100 and above (also with leading zeros):

0*[1-9]\d{2,}

Add them together with an "or" and wrap it up to match the whole sentence:

^0*([1-9]\d{2,}|[5-9]\d)$

That's it!

In Python, how do I iterate over a dictionary in sorted key order?

A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.

sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!

foo = {
    'a':    1,
    'b':    2,
    'c':    3,
    }

print foo
>>> {'a': 1, 'c': 3, 'b': 2}

print foo.items()
>>> [('a', 1), ('c', 3), ('b', 2)]

print sorted(foo.items())
>>> [('a', 1), ('b', 2), ('c', 3)]

The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:

for k,v in sorted(foo.items()):
    print k, v

Roughly equivalent to:

for k in sorted(foo.keys()):
    print k, foo[k]

Command line for looking at specific port

To improve upon @EndUzr's response:

To find a foreign port (IPv4 or IPv6) you can use:

netstat -an | findstr /r /c:":N [^:]*$"

To find a local port (IPv4 or IPv6) you can use:

netstat -an | findstr /r /c:":N *[^ ]*:[^ ]* "

Where N is the port number you are interested in. The "/r" switch tells it to process it as regexp. The "/c" switch allows findstr to include spaces within search strings instead of treating a space as a search string delimiter. This added space prevents longer ports being mistreated - for example, ":80" vs ":8080" and other port munging issues.

To list remote connections to the local RDP server, for example:

netstat -an | findstr /r /c:":3389 *[^ ]*:[^ ]*"

Or to see who is touching your DNS:

netstat -an | findstr /r /c:":53 *[^ ]*:[^ ]*"

If you want to exclude local-only ports you can use a series of exceptions with "/v" and escape characters with a backslash:

netstat -an | findstr /v "0.0.0.0 127.0.0.1 \[::\] \[::1\] \*\:\*" | findstr /r /c:":80 *[^ ]*:[^ ]*"

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

What is the difference between require and require-dev sections in composer.json?

require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.

require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).

How do I get formatted JSON in .NET using C#?

Oneliner using Newtonsoft.Json.Linq:

string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);

char initial value in Java

i would just do:

char x = 0; //Which will give you an empty value of character

How to perform an SQLite query within an Android application?

This will return you the required cursor

Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"}, 
                "title_raw like " + "'%Smith%'", null, null, null, null);

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

"cannot resolve symbol R" in Android Studio

I faced this issue when I manually renamed the domain folder of my app. To fix this issue, I had to

  1. Set the proper package folder structure of <manifest> in AndroidManifest.xml.
  2. Set the new package location for android:name of <activity> in AndroidManifest.xml.
  3. Clear cache by

File Menu -> Invalidate Caches / Restart ...

The issue will be gone, once the Android studio restarts and builds the fresh index.

Checking if element exists with Python Selenium

you could use is_displayed() like below

res = driver.find_element_by_id("some_id").is_displayed()
assert res, 'element not displayed!'

Cannot lower case button text in android studio

add android:textAllCaps="false" in xml button It's true with this issue.

How do I instantiate a Queue object in java?

Queue is an interface in java, you could not do that. try:

Queue<Integer> Q = new LinkedList<Integer>();

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

Vector erase iterator

Something that you can do with modern C++ is using "std::remove_if" and lambda expression;

This code will remove "3" of the vector

vector<int> vec {1,2,3,4,5,6};

vec.erase(std::remove_if(begin(vec),end(vec),[](int elem){return (elem == 3);}), end(vec));

How to write a foreach in SQL Server?

I would say everything probably works except that the column idx doesn't actually exist in the table you're selecting from. Maybe you meant to select from @Practitioner:

WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

because that's defined in the code above like that:

DECLARE @Practitioner TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , PractitionerId int
)

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I had the same issue and took a whole day to figure out the problem. This error message by Facebook SDK is very vague. I had this problem due to openURL: method being overwritten in MyApplication. I removed the overwritten method and facebook login worked fine.

Can the Android layout folder contain subfolders?

Now with Android Studio and Gradle, you can have multiple resource folders in your project. Allowing to organize not only your layout files but any kind of resources.

It's not exactly a sub-folder, but may separte parts of your application.

The configuration is like this:

sourceSets {
    main {
        res.srcDirs = ['src/main/res', 'src/main/res2']
    }
}

Check the documentation.

Kafka consumer list

All the consumers per topic

(Replace --zookeeper with --bootstrap-server to get groups stored by newer Kafka clients)

Get all consumers-per-topic as a table of topictabconsumer:

for t in `kafka-consumer-groups.sh --zookeeper <HOST>:2181 --list 2>/dev/null`; do
    echo $t | xargs -I {} sh -c "kafka-consumer-groups.sh --zookeeper <HOST>:2181 --describe --group {} 2>/dev/null | grep ^{} | awk '{print \$2\"\t\"\$1}' "
done > topic-consumer.txt

Make this pairs unique:

cat topic-consumer.txt | sort -u > topic-consumer-u.txt

Get the desired one:

less topic-consumer-u.txt | grep -i <TOPIC>

Pick any kind of file via an Intent in Android

Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.

Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);

You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:

public void openFile(String mimeType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(mimeType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // special intent for Samsung file manager
        Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
         // if you want any file type, you can skip next line 
        sIntent.putExtra("CONTENT_TYPE", mimeType); 
        sIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(sIntent, 0) != null){
            // it is device with Samsung file manager
            chooserIntent = Intent.createChooser(sIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
        } else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
        }
    }

This solution works well for me, and maybe will be useful for someone else.

Formatting code snippets for blogging on Blogger

It looks like there have been some changes with SyntaxHighlighter 2.0 that make it easier to use with Blogger.

There are hosted versions of the styles and Javascripts at: http://alexgorbatchev.com/pub/sh/

How to resolve git stash conflict without commit?

git stash branch will works, which creates a new branch for you, checks out the commit you were on when you stashed your work, reapplies your work there, and then drops the stash if it applies successfully. check this

Apache Prefork vs Worker MPM

For CentOS 6.x and 7.x (including Amazon Linux) use:

sudo httpd -V

This will show you which of the MPMs are configured. Either prefork, worker, or event. Prefork is the earlier, threadsafe model. Worker is multi-threaded, and event supports php-mpm which is supposed to be a better system for handling threads and requests.

However, your results may vary, based on configuration. I've seen a lot of instability in php-mpm and not any speed improvements. An aggressive spider can exhaust the maximum child processes in php-mpm quite easily.

The setting for prefork, worker, or event is set in sudo nano /etc/httpd/conf.modules.d/00-mpm.conf (for CentOS 6.x/7.x/Apache 2.4).

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#LoadModule mpm_event_module modules/mod_mpm_event.so

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Disable future dates in jQuery UI Datepicker

Yes, datepicker supports max date property.

 $("#datepickeraddcustomer").datepicker({  
             dateFormat: "yy-mm-dd",  
             maxDate: new Date()  
        });

GROUP BY with MAX(DATE)

I know I'm late to the party, but try this...

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src: Group Concat Documentation

Edit: fixed sql syntax

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

@Transactional(propagation=Propagation.REQUIRED)

In Spring applications, if you enable annotation based transaction support using <tx:annotation-driven/> and annotate any class/method with @Transactional(propagation=Propagation.REQUIRED) then Spring framework will start a transaction and executes the method and commits the transaction. If any RuntimeException occurred then the transaction will be rolled back.

Actually propagation=Propagation.REQUIRED is default propagation level, you don't need to explicitly mentioned it.

For further info : http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

How to view data saved in android database(SQLite)?

Open DDMS than in DATA>DATA>"Select your package like com.example.foo"> than select your database folder than pull that data in eclipse you can see the pull an push icon on top right side ...

Replace and overwrite instead of appending

Using python3 pathlib library:

import re
from pathlib import Path
import shutil

shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

Similar method using different approach to backups:

from pathlib import Path

filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

SQL: Two select statements in one query

You can do something like this:

 (SELECT
    name, games, goals
    FROM tblMadrid WHERE name = 'ronaldo')
 UNION
 (SELECT
    name, games, goals
    FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;

See, for example: https://dev.mysql.com/doc/refman/5.0/en/union.html

How to assign execute permission to a .sh file in windows to be executed in linux

This is possible using the Info-Zip open-source Zip utilities. If unzip is run with the -X parameter, it will attempt to preserve the original permissions. If the source filesystem was NTFS and the destination is a Unix one, it will attempt to translate from one to the other. I do not have a Windows system available right now to test the translation, so you will have to experiment with which group needs to be awarded execute permissions. It'll be something like "Users" or "Any user"

Flask - Calling python function on button OnClick event

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/forward/", methods=['POST'])
def move_forward():
    #Moving forward code
    forward_message = "Moving Forward..."
    return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
    <button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

{{ forward_message }} 

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

How to amend a commit without changing commit message (reusing the previous one)?

To extend on the accepted answer, you can also do:

git commit --amend --no-edit -a

to add the currently changed files.

Could not establish secure channel for SSL/TLS with authority '*'

We had this issue on a new webserver from .aspx pages calling a webservice. We had not given permission to the app pool user to the machine certificate. The issue was fixed after we granted permission to the app pool user.

Read input numbers separated by spaces

I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.

#include <string>
#include <vector>
...
  string rawInput;
  vector<String> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }

So say the input looks like this:

Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7

You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.

Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.

while(!numbers.empty())
{
  string temp = numbers.pop_back();//removes the last element from the string
  num = atoi( temp.c_str() ); //re-used your 'num' variable from your code

  ...//do stuff
}

Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:

#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  num = atoi( rawInput.c_str() );
  ...//do your stuff
}

There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)

Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/

Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].

#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  bool isNum = true;
  for(int i = 0; i < rawInput.length() && isNum; ++i)
  {
    isNum = isdigit( rawInput[i]);
  }

  if(isNum)
  {
    num = atoi( rawInput.c_str() );
    ...//do your stuff
  }
  else
    cout << rawInput << " is not a number!" << endl;
}

The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.

How to use basic authorization in PHP curl

Try the following code :

$username='ABC';
$password='XYZ';
$URL='<URL>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

TypeScript for ... of with index / key?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries

for (var [key, item] of someArray.entries()) { ... }

In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.

The network path was not found

You will also get this exact error if attempting to access your remote/prod db from localhost and you've forgotten that this particular hosting company requires VPN logon in order to access the db (do i feel silly).

unable to remove file that really exists - fatal: pathspec ... did not match any files

Your file .idea/workspace.xml is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)

You can verify it using following git command, that lists all ignored files:

git ls-files --others -i --exclude-standard

Git commit with no commit message

I have the following config in my private project:

git config alias.auto 'commit -a -m "changes made from [device name]"'

That way, when I'm in a hurry I do

git auto
git push

And at least I know what device the commit was made from.

How many concurrent requests does a single Flask process receive?

When running the development server - which is what you get by running app.run(), you get a single synchronous process, which means at most 1 request is being processed at a time.

By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run() development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync worker type by default.

It is important to note that Gunicorn also includes asynchronous workers, namely eventlet and gevent (and also tornado, but that's best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don't use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be 'paused' when they are waiting on external processes to finish (think database queries or waiting on network I/O).

This means, if you're using one of Gunicorn's async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn's design page and notes on how gevent works on its intro page.

Pandas dataframe fillna() only some columns in place

Sometimes this syntax wont work:

df[['col1','col2']] = df[['col1','col2']].fillna()

Use the following instead:

df['col1','col2']

How to hide a button programmatically?

Hidde:

BUTTON.setVisibility(View.GONE);

Show:

BUTTON.setVisibility(View.VISIBLE);

How can foreign key constraints be temporarily disabled using T-SQL?

First post :)

For the OP, kristof's solution will work, unless there are issues with massive data and transaction log balloon issues on big deletes. Also, even with tlog storage to spare, since deletes write to the tlog, the operation can take a VERY long time for tables with hundreds of millions of rows.

I use a series of cursors to truncate and reload large copies of one of our huge production databases frequently. The solution engineered accounts for multiple schemas, multiple foreign key columns, and best of all can be sproc'd out for use in SSIS.

It involves creation of three staging tables (real tables) to house the DROP, CREATE, and CHECK FK scripts, creation and insertion of those scripts into the tables, and then looping over the tables and executing them. The attached script is four parts: 1.) creation and storage of the scripts in the three staging (real) tables, 2.) execution of the drop FK scripts via a cursor one by one, 3.) Using sp_MSforeachtable to truncate all the tables in the database other than our three staging tables and 4.) execution of the create FK and check FK scripts at the end of your ETL SSIS package.

Run the script creation portion in an Execute SQL task in SSIS. Run the "execute Drop FK Scripts" portion in a second Execute SQL task. Put the truncation script in a third Execute SQL task, then perform whatever other ETL processes you need to do prior to attaching the CREATE and CHECK scripts in a final Execute SQL task (or two if desired) at the end of your control flow.

Storage of the scripts in real tables has proven invaluable when the re-application of the foreign keys fails as you can select * from sync_CreateFK, copy/paste into your query window, run them one at a time, and fix the data issues once you find ones that failed/are still failing to re-apply.

Do not re-run the script again if it fails without making sure that you re-apply all of the foreign keys/checks prior to doing so, or you will most likely lose some creation and check fk scripting as our staging tables are dropped and recreated prior to the creation of the scripts to execute.

----------------------------------------------------------------------------
1)
/*
Author:         Denmach
DateCreated:    2014-04-23
Purpose:        Generates SQL statements to DROP, ADD, and CHECK existing constraints for a 
                database.  Stores scripts in tables on target database for execution.  Executes
                those stored scripts via independent cursors. 
DateModified:
ModifiedBy
Comments:       This will eliminate deletes and the T-log ballooning associated with it.
*/

DECLARE @schema_name SYSNAME; 
DECLARE @table_name SYSNAME; 
DECLARE @constraint_name SYSNAME; 
DECLARE @constraint_object_id INT; 
DECLARE @referenced_object_name SYSNAME; 
DECLARE @is_disabled BIT; 
DECLARE @is_not_for_replication BIT; 
DECLARE @is_not_trusted BIT; 
DECLARE @delete_referential_action TINYINT; 
DECLARE @update_referential_action TINYINT; 
DECLARE @tsql NVARCHAR(4000); 
DECLARE @tsql2 NVARCHAR(4000); 
DECLARE @fkCol SYSNAME; 
DECLARE @pkCol SYSNAME; 
DECLARE @col1 BIT; 
DECLARE @action CHAR(6);  
DECLARE @referenced_schema_name SYSNAME;



--------------------------------Generate scripts to drop all foreign keys in a database --------------------------------

IF OBJECT_ID('dbo.sync_dropFK') IS NOT NULL
DROP TABLE sync_dropFK

CREATE TABLE sync_dropFK
    (
    ID INT IDENTITY (1,1) NOT NULL
    , Script NVARCHAR(4000)
    )

DECLARE FKcursor CURSOR FOR

    SELECT 
        OBJECT_SCHEMA_NAME(parent_object_id)
        , OBJECT_NAME(parent_object_id)
        , name
    FROM 
        sys.foreign_keys WITH (NOLOCK)
    ORDER BY 
        1,2;

OPEN FKcursor;

FETCH NEXT FROM FKcursor INTO 
    @schema_name
    , @table_name
    , @constraint_name

WHILE @@FETCH_STATUS = 0

BEGIN
        SET @tsql = 'ALTER TABLE '
                + QUOTENAME(@schema_name) 
                + '.' 
                + QUOTENAME(@table_name)
                + ' DROP CONSTRAINT ' 
                + QUOTENAME(@constraint_name) 
                + ';';
    --PRINT @tsql;
    INSERT sync_dropFK  (
                        Script
                        )
                        VALUES (
                                @tsql
                                )   

    FETCH NEXT FROM FKcursor INTO 
    @schema_name
    , @table_name
    , @constraint_name
    ;

END;

CLOSE FKcursor;

DEALLOCATE FKcursor;


---------------Generate scripts to create all existing foreign keys in a database --------------------------------
----------------------------------------------------------------------------------------------------------
IF OBJECT_ID('dbo.sync_createFK') IS NOT NULL
DROP TABLE sync_createFK

CREATE TABLE sync_createFK
    (
    ID INT IDENTITY (1,1) NOT NULL
    , Script NVARCHAR(4000)
    )

IF OBJECT_ID('dbo.sync_createCHECK') IS NOT NULL
DROP TABLE sync_createCHECK

CREATE TABLE sync_createCHECK
    (
    ID INT IDENTITY (1,1) NOT NULL
    , Script NVARCHAR(4000)
    )   

DECLARE FKcursor CURSOR FOR

     SELECT 
        OBJECT_SCHEMA_NAME(parent_object_id)
        , OBJECT_NAME(parent_object_id)
        , name
        , OBJECT_NAME(referenced_object_id)
        , OBJECT_ID
        , is_disabled
        , is_not_for_replication
        , is_not_trusted
        , delete_referential_action
        , update_referential_action
        , OBJECT_SCHEMA_NAME(referenced_object_id)

    FROM 
        sys.foreign_keys WITH (NOLOCK)

    ORDER BY 
        1,2;

OPEN FKcursor;

FETCH NEXT FROM FKcursor INTO 
    @schema_name
    , @table_name
    , @constraint_name
    , @referenced_object_name
    , @constraint_object_id
    , @is_disabled
    , @is_not_for_replication
    , @is_not_trusted
    , @delete_referential_action
    , @update_referential_action
    , @referenced_schema_name;

WHILE @@FETCH_STATUS = 0

BEGIN

        BEGIN
            SET @tsql = 'ALTER TABLE '
                        + QUOTENAME(@schema_name) 
                        + '.' 
                        + QUOTENAME(@table_name)
                        +   CASE 
                                @is_not_trusted
                                WHEN 0 THEN ' WITH CHECK '
                                ELSE ' WITH NOCHECK '
                            END
                        + ' ADD CONSTRAINT ' 
                        + QUOTENAME(@constraint_name)
                        + ' FOREIGN KEY (';

        SET @tsql2 = '';

        DECLARE ColumnCursor CURSOR FOR 

            SELECT 
                COL_NAME(fk.parent_object_id
                , fkc.parent_column_id)
                , COL_NAME(fk.referenced_object_id
                , fkc.referenced_column_id)

            FROM 
                sys.foreign_keys fk WITH (NOLOCK)
                INNER JOIN sys.foreign_key_columns fkc WITH (NOLOCK) ON fk.[object_id] = fkc.constraint_object_id

            WHERE 
                fkc.constraint_object_id = @constraint_object_id

            ORDER BY 
                fkc.constraint_column_id;

        OPEN ColumnCursor;

        SET @col1 = 1;

        FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;

        WHILE @@FETCH_STATUS = 0

        BEGIN
            IF (@col1 = 1)
                SET @col1 = 0;
            ELSE
            BEGIN
                SET @tsql = @tsql + ',';
                SET @tsql2 = @tsql2 + ',';
            END;

            SET @tsql = @tsql + QUOTENAME(@fkCol);
            SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);
            --PRINT '@tsql = ' + @tsql 
            --PRINT '@tsql2 = ' + @tsql2
            FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
            --PRINT 'FK Column ' + @fkCol
            --PRINT 'PK Column ' + @pkCol 
        END;

        CLOSE ColumnCursor;
        DEALLOCATE ColumnCursor;

        SET @tsql = @tsql + ' ) REFERENCES ' 
                    + QUOTENAME(@referenced_schema_name) 
                    + '.' 
                    + QUOTENAME(@referenced_object_name)
                    + ' (' 
                    + @tsql2 + ')';

        SET @tsql = @tsql
                    + ' ON UPDATE ' 
                    + 
                        CASE @update_referential_action
                            WHEN 0 THEN 'NO ACTION '
                            WHEN 1 THEN 'CASCADE '
                            WHEN 2 THEN 'SET NULL '
                                ELSE 'SET DEFAULT '
                        END

                    + ' ON DELETE ' 
                    + 
                        CASE @delete_referential_action
                            WHEN 0 THEN 'NO ACTION '
                            WHEN 1 THEN 'CASCADE '
                            WHEN 2 THEN 'SET NULL '
                                ELSE 'SET DEFAULT '
                        END

                    + 
                    CASE @is_not_for_replication
                        WHEN 1 THEN ' NOT FOR REPLICATION '
                            ELSE ''
                    END
                    + ';';

        END;

    --  PRINT @tsql
        INSERT sync_createFK    
                        (
                        Script
                        )
                        VALUES (
                                @tsql
                                )

-------------------Generate CHECK CONSTRAINT scripts for a database ------------------------------
----------------------------------------------------------------------------------------------------------

        BEGIN

        SET @tsql = 'ALTER TABLE '
                    + QUOTENAME(@schema_name) 
                    + '.' 
                    + QUOTENAME(@table_name)
                    + 
                        CASE @is_disabled
                            WHEN 0 THEN ' CHECK '
                                ELSE ' NOCHECK '
                        END
                    + 'CONSTRAINT ' 
                    + QUOTENAME(@constraint_name)
                    + ';';
        --PRINT @tsql;
        INSERT sync_createCHECK 
                        (
                        Script
                        )
                        VALUES (
                                @tsql
                                )   
        END;

    FETCH NEXT FROM FKcursor INTO 
    @schema_name
    , @table_name
    , @constraint_name
    , @referenced_object_name
    , @constraint_object_id
    , @is_disabled
    , @is_not_for_replication
    , @is_not_trusted
    , @delete_referential_action
    , @update_referential_action
    , @referenced_schema_name;

END;

CLOSE FKcursor;

DEALLOCATE FKcursor;

--SELECT * FROM sync_DropFK
--SELECT * FROM sync_CreateFK
--SELECT * FROM sync_CreateCHECK
---------------------------------------------------------------------------
2.)
-----------------------------------------------------------------------------------------------------------------
----------------------------execute Drop FK Scripts --------------------------------------------------

DECLARE @scriptD NVARCHAR(4000)

DECLARE DropFKCursor CURSOR FOR
    SELECT Script 
    FROM sync_dropFK WITH (NOLOCK)

OPEN DropFKCursor

FETCH NEXT FROM DropFKCursor
INTO @scriptD

WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptD
EXEC (@scriptD)
FETCH NEXT FROM DropFKCursor
INTO @scriptD
END
CLOSE DropFKCursor
DEALLOCATE DropFKCursor
--------------------------------------------------------------------------------
3.) 

------------------------------------------------------------------------------------------------------------------
----------------------------Truncate all tables in the database other than our staging tables --------------------
------------------------------------------------------------------------------------------------------------------


EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN 
(
ISNULL(OBJECT_ID(''dbo.sync_createCHECK''),0),
ISNULL(OBJECT_ID(''dbo.sync_createFK''),0),
ISNULL(OBJECT_ID(''dbo.sync_dropFK''),0)
)
BEGIN TRY
 TRUNCATE TABLE ?
END TRY
BEGIN CATCH
 PRINT ''Truncation failed on''+ ? +''
END CATCH;' 
GO
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
----------------------------execute Create FK Scripts and CHECK CONSTRAINT Scripts---------------
----------------------------tack me at the end of the ETL in a SQL task-------------------------
-------------------------------------------------------------------------------------------------
DECLARE @scriptC NVARCHAR(4000)

DECLARE CreateFKCursor CURSOR FOR
    SELECT Script 
    FROM sync_createFK WITH (NOLOCK)

OPEN CreateFKCursor

FETCH NEXT FROM CreateFKCursor
INTO @scriptC

WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptC
EXEC (@scriptC)
FETCH NEXT FROM CreateFKCursor
INTO @scriptC
END
CLOSE CreateFKCursor
DEALLOCATE CreateFKCursor
-------------------------------------------------------------------------------------------------
DECLARE @scriptCh NVARCHAR(4000)

DECLARE CreateCHECKCursor CURSOR FOR
    SELECT Script 
    FROM sync_createCHECK WITH (NOLOCK)

OPEN CreateCHECKCursor

FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh

WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptCh
EXEC (@scriptCh)
FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh
END
CLOSE CreateCHECKCursor
DEALLOCATE CreateCHECKCursor

How can I merge two MySQL tables?

You can also try:

INSERT IGNORE
  INTO table_1 
SELECT *
  FROM table_2
     ;

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.

Alternatively,

REPLACE
   INTO table_1
 SELECT *
   FROM table_2
      ;

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.

How do you find out the caller function in JavaScript?

If you just want the function name and not the code, and want a browser-independent solution, use the following:

var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];

Note that the above will return an error if there is no caller function as there is no [1] element in the array. To work around, use the below:

var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

Efficient way to remove keys with empty strings from a dict

If you really need to modify the original dictionary:

empty_keys = [k for k,v in metadata.iteritems() if not v]
for k in empty_keys:
    del metadata[k]

Note that we have to make a list of the empty keys because we can't modify a dictionary while iterating through it (as you may have noticed). This is less expensive (memory-wise) than creating a brand-new dictionary, though, unless there are a lot of entries with empty values.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

This Proxy will expose the buffer as any of the TypedArrays, without any copy. :

https://www.npmjs.com/package/node-buffer-as-typedarray

It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.

How can I check if a string only contains letters in Python?

Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:

unicodedata.category('?')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

only_letters('Bzdrezylo')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.

How to get a list of images on docker registry v2

We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

enter image description here

enter image description here

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

How to remove multiple deleted files in Git repository

Here is how to detect deleted files and stage their deletion as part of the next commit. All the solutions on this thread have different merits. This solution bellow specifically deals with the problem of file names with spaces in them.

git status --porcelain | awk '/^.D .*$/ {print $0}' | sed 's/.D \(.*\)/\1/' | tr -d '"' | xargs -I {} git rm '{}'

make sure you test this with git's --dry-run option before running it with the following:

git status --porcelain | awk '/^.D .*$/ {print $0}' | sed 's/.D \(.*\)/\1/' | tr -d '"' | xargs -I {} git rm --dry-run '{}'

explanation:

git status --porcelain

This prints out something like D "/path to a folder/path to a file" which happens only when there are spaces in the path names

awk '/^.D .*$/ {print $0}'

match only lines that start with " D "

sed 's/ D \(.*\)/\1/'

remove " D " from the front of each string

tr -d '"'

remove quotes, if any

xargs -I {} git rm '{}'

define file name variables as {} run file name under git rm enclosed in single quotes in order to make sure that it supports file names with spaces.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Im new to java hibernate but i could solve this problem, this is how i did it : I was working with hibernate and maven project. First you have to put persistence.xml under project directory, then add jdbc manually. Maven couldn't download my dependency so i added it manually. In the persistence.xml in design jdbc connection add it manually ps: i work with netbeans good luck

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

Make the sql mode non strict

if using laravel go to config->database, the go to mysql settings and make the strict mode false

How to check if an object is a list or tuple (but not string)?

assert (type(lst) == list) | (type(lst) == tuple), "Not a valid lst type, cannot be string"

Get file path of image on Android

You can do like that In Kotlin If you need kotlin code in the future

val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))

fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
    val bytes = ByteArrayOutputStream()
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
    return Uri.parse(path)
}

fun getRealPathFromURI(uri: Uri): String {
    val cursor = contentResolver.query(uri, null, null, null, null)
    cursor!!.moveToFirst()
    val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
    return cursor.getString(idx)
}

Local variable referenced before assignment?

You have to specify that test1 is global:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

How to make an input type=button act like a hyperlink and redirect using a get request?

I think that is your need.

a href="#" onclick="document.forms[0].submit();return false;"

IO Error: The Network Adapter could not establish the connection

In my case, I needed to specify a viahost and viauser. Worth trying if you're in a complex system. :)

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

SVN "Already Locked Error"

I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

I will just give the analogy with which I understand memory consistency models (or memory models, for short). It is inspired by Leslie Lamport's seminal paper "Time, Clocks, and the Ordering of Events in a Distributed System". The analogy is apt and has fundamental significance, but may be overkill for many people. However, I hope it provides a mental image (a pictorial representation) that facilitates reasoning about memory consistency models.

Let’s view the histories of all memory locations in a space-time diagram in which the horizontal axis represents the address space (i.e., each memory location is represented by a point on that axis) and the vertical axis represents time (we will see that, in general, there is not a universal notion of time). The history of values held by each memory location is, therefore, represented by a vertical column at that memory address. Each value change is due to one of the threads writing a new value to that location. By a memory image, we will mean the aggregate/combination of values of all memory locations observable at a particular time by a particular thread.

Quoting from "A Primer on Memory Consistency and Cache Coherence"

The intuitive (and most restrictive) memory model is sequential consistency (SC) in which a multithreaded execution should look like an interleaving of the sequential executions of each constituent thread, as if the threads were time-multiplexed on a single-core processor.

That global memory order can vary from one run of the program to another and may not be known beforehand. The characteristic feature of SC is the set of horizontal slices in the address-space-time diagram representing planes of simultaneity (i.e., memory images). On a given plane, all of its events (or memory values) are simultaneous. There is a notion of Absolute Time, in which all threads agree on which memory values are simultaneous. In SC, at every time instant, there is only one memory image shared by all threads. That's, at every instant of time, all processors agree on the memory image (i.e., the aggregate content of memory). Not only does this imply that all threads view the same sequence of values for all memory locations, but also that all processors observe the same combinations of values of all variables. This is the same as saying all memory operations (on all memory locations) are observed in the same total order by all threads.

In relaxed memory models, each thread will slice up address-space-time in its own way, the only restriction being that slices of each thread shall not cross each other because all threads must agree on the history of every individual memory location (of course, slices of different threads may, and will, cross each other). There is no universal way to slice it up (no privileged foliation of address-space-time). Slices do not have to be planar (or linear). They can be curved and this is what can make a thread read values written by another thread out of the order they were written in. Histories of different memory locations may slide (or get stretched) arbitrarily relative to each other when viewed by any particular thread. Each thread will have a different sense of which events (or, equivalently, memory values) are simultaneous. The set of events (or memory values) that are simultaneous to one thread are not simultaneous to another. Thus, in a relaxed memory model, all threads still observe the same history (i.e., sequence of values) for each memory location. But they may observe different memory images (i.e., combinations of values of all memory locations). Even if two different memory locations are written by the same thread in sequence, the two newly written values may be observed in different order by other threads.

[Picture from Wikipedia] Picture from Wikipedia

Readers familiar with Einstein’s Special Theory of Relativity will notice what I am alluding to. Translating Minkowski’s words into the memory models realm: address space and time are shadows of address-space-time. In this case, each observer (i.e., thread) will project shadows of events (i.e., memory stores/loads) onto his own world-line (i.e., his time axis) and his own plane of simultaneity (his address-space axis). Threads in the C++11 memory model correspond to observers that are moving relative to each other in special relativity. Sequential consistency corresponds to the Galilean space-time (i.e., all observers agree on one absolute order of events and a global sense of simultaneity).

The resemblance between memory models and special relativity stems from the fact that both define a partially-ordered set of events, often called a causal set. Some events (i.e., memory stores) can affect (but not be affected by) other events. A C++11 thread (or observer in physics) is no more than a chain (i.e., a totally ordered set) of events (e.g., memory loads and stores to possibly different addresses).

In relativity, some order is restored to the seemingly chaotic picture of partially ordered events, since the only temporal ordering that all observers agree on is the ordering among “timelike” events (i.e., those events that are in principle connectible by any particle going slower than the speed of light in a vacuum). Only the timelike related events are invariantly ordered. Time in Physics, Craig Callender.

In C++11 memory model, a similar mechanism (the acquire-release consistency model) is used to establish these local causality relations.

To provide a definition of memory consistency and a motivation for abandoning SC, I will quote from "A Primer on Memory Consistency and Cache Coherence"

For a shared memory machine, the memory consistency model defines the architecturally visible behavior of its memory system. The correctness criterion for a single processor core partitions behavior between “one correct result” and “many incorrect alternatives”. This is because the processor’s architecture mandates that the execution of a thread transforms a given input state into a single well-defined output state, even on an out-of-order core. Shared memory consistency models, however, concern the loads and stores of multiple threads and usually allow many correct executions while disallowing many (more) incorrect ones. The possibility of multiple correct executions is due to the ISA allowing multiple threads to execute concurrently, often with many possible legal interleavings of instructions from different threads.

Relaxed or weak memory consistency models are motivated by the fact that most memory orderings in strong models are unnecessary. If a thread updates ten data items and then a synchronization flag, programmers usually do not care if the data items are updated in order with respect to each other but only that all data items are updated before the flag is updated (usually implemented using FENCE instructions). Relaxed models seek to capture this increased ordering flexibility and preserve only the orders that programmers “require” to get both higher performance and correctness of SC. For example, in certain architectures, FIFO write buffers are used by each core to hold the results of committed (retired) stores before writing the results to the caches. This optimization enhances performance but violates SC. The write buffer hides the latency of servicing a store miss. Because stores are common, being able to avoid stalling on most of them is an important benefit. For a single-core processor, a write buffer can be made architecturally invisible by ensuring that a load to address A returns the value of the most recent store to A even if one or more stores to A are in the write buffer. This is typically done by either bypassing the value of the most recent store to A to the load from A, where “most recent” is determined by program order, or by stalling a load of A if a store to A is in the write buffer. When multiple cores are used, each will have its own bypassing write buffer. Without write buffers, the hardware is SC, but with write buffers, it is not, making write buffers architecturally visible in a multicore processor.

Store-store reordering may happen if a core has a non-FIFO write buffer that lets stores depart in a different order than the order in which they entered. This might occur if the first store misses in the cache while the second hits or if the second store can coalesce with an earlier store (i.e., before the first store). Load-load reordering may also happen on dynamically-scheduled cores that execute instructions out of program order. That can behave the same as reordering stores on another core (Can you come up with an example interleaving between two threads?). Reordering an earlier load with a later store (a load-store reordering) can cause many incorrect behaviors, such as loading a value after releasing the lock that protects it (if the store is the unlock operation). Note that store-load reorderings may also arise due to local bypassing in the commonly implemented FIFO write buffer, even with a core that executes all instructions in program order.

Because cache coherence and memory consistency are sometimes confused, it is instructive to also have this quote:

Unlike consistency, cache coherence is neither visible to software nor required. Coherence seeks to make the caches of a shared-memory system as functionally invisible as the caches in a single-core system. Correct coherence ensures that a programmer cannot determine whether and where a system has caches by analyzing the results of loads and stores. This is because correct coherence ensures that the caches never enable new or different functional behavior (programmers may still be able to infer likely cache structure using timing information). The main purpose of cache coherence protocols is maintaining the single-writer-multiple-readers (SWMR) invariant for every memory location. An important distinction between coherence and consistency is that coherence is specified on a per-memory location basis, whereas consistency is specified with respect to all memory locations.

Continuing with our mental picture, the SWMR invariant corresponds to the physical requirement that there be at most one particle located at any one location but there can be an unlimited number of observers of any location.