Programs & Examples On #Fftw

FFTW, "The Fastest Fourier Transform in The West", is a C library which implements discrete Fourier Transforms. It is licensed under the GNU GPL.

How to use LogonUser properly to impersonate domain user from workgroup client

It's better to use a SecureString:

var password = new SecureString();
var phPassword phPassword = Marshal.SecureStringToGlobalAllocUnicode(password);
IntPtr phUserToken;
LogonUser(username, domain, phPassword, LOGON32_LOGON_INTERACTIVE,  LOGON32_PROVIDER_DEFAULT, out phUserToken);

And:

Marshal.ZeroFreeGlobalAllocUnicode(phPassword);
password.Dispose();

Function definition:

private static extern bool LogonUser(
  string pszUserName,
  string pszDomain,
  IntPtr pszPassword,
  int dwLogonType,
  int dwLogonProvider,
  out IntPtr phToken);

How to use class from other files in C# with visual studio?

According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)

Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.

npm throws error without sudo

Problem: You do not have permission to write to the directories that npm uses to store global packages and commands.

Solution: Allow permission for npm.

Open a terminal:

command + spacebar then type 'terminal'

Enter this command:

sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
  • Note: this will require your password.

This solution allows permission to ONLY the directories needed, keeping the other directories nice and safe.

How to open a folder in Windows Explorer from VBA?

The easiest way is

Application.FollowHyperlink [path]

Which only takes one line!

Getting RAW Soap Data from a Web Reference Client running in ASP.net

I made following changes in web.config to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log.

<system.diagnostics>
  <trace autoflush="true"/>
  <sources>
    <source name="System.Net" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
    <source name="System.Net.Sockets" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
      initializeData="trace.log"/>
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
  </switches>
</system.diagnostics>

What are the differences between Deferred, Promise and Future in JavaScript?

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

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

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.

Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.


enter image description here

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Change border color on <select> HTML form

Replacing the border-color with outline-color should work.

How to change DataTable columns order

This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.

public static class DataTableExtensions
{
    /// <summary>
    /// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
    /// </summary>
    /// <param name="table"></param>
    /// <param name="columnNames"></param>
    /// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
    public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
    {
        List<string> listColNames = columnNames.ToList();

        //Remove invalid column names.
        foreach (string colName in columnNames)
        {
            if (!dtbl.Columns.Contains(colName))
            {
                listColNames.Remove(colName);
            }
        }

        foreach (string colName in listColNames)
        {
            dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
        }
}

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

Sending a file over TCP sockets in Python

Put file inside while True like so

while True:
     f = open('torecv.png','wb')
     c, addr = s.accept()     # Establish connection with client.
     print 'Got connection from', addr
     print "Receiving..."
     l = c.recv(1024)
     while (l):
         print "Receiving..."
         f.write(l)
         l = c.recv(1024)
     f.close()
     print "Done Receiving"
     c.send('Thank you for connecting')
     c.close()   

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

SQL injection that gets around mysql_real_escape_string()

TL;DR

mysql_real_escape_string() will provide no protection whatsoever (and could furthermore munge your data) if:

  • MySQL's NO_BACKSLASH_ESCAPES SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); and

  • your SQL string literals are quoted using double-quote " characters.

This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).

This is another, (perhaps less?) obscure EDGE CASE!!!

In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:

The Attack

Starting off with a demonstration...

mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

This will return all records from the test table. A dissection:

  1. Selecting an SQL Mode

    mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
    

    As documented under String Literals:

    There are several ways to include quote characters within a string:

    • A “'” inside a string quoted with “'” may be written as “''”.

    • A “"” inside a string quoted with “"” may be written as “""”.

    • Precede the quote character by an escape character (“\”).

    • A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.

    If the server's SQL mode includes NO_BACKSLASH_ESCAPES, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.

  2. The Payload

    " OR 1=1 -- 
    

    The payload initiates this injection quite literally with the " character. No particular encoding. No special characters. No weird bytes.

  3. mysql_real_escape_string()

    $var = mysql_real_escape_string('" OR 1=1 -- ');
    

    Fortunately, mysql_real_escape_string() does check the SQL mode and adjust its behaviour accordingly. See libmysql.c:

    ulong STDCALL
    mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
                 ulong length)
    {
      if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
        return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
      return escape_string_for_mysql(mysql->charset, to, 0, from, length);
    }
    

    Thus a different underlying function, escape_quotes_for_mysql(), is invoked if the NO_BACKSLASH_ESCAPES SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.

    However, this function arbitrarily assumes that the string will be quoted using the single-quote ' character. See charset.c:

    /*
      Escape apostrophes by doubling them up
    
    // [ deletia 839-845 ]
    
      DESCRIPTION
        This escapes the contents of a string by doubling up any apostrophes that
        it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
        effect on the server.
    
    // [ deletia 852-858 ]
    */
    
    size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
                                   char *to, size_t to_length,
                                   const char *from, size_t length)
    {
    // [ deletia 865-892 ]
    
        if (*from == '\'')
        {
          if (to + 2 > to_end)
          {
            overflow= TRUE;
            break;
          }
          *to++= '\'';
          *to++= '\'';
        }
    

    So, it leaves double-quote " characters untouched (and doubles all single-quote ' characters) irrespective of the actual character that is used to quote the literal! In our case $var remains exactly the same as the argument that was provided to mysql_real_escape_string()—it's as though no escaping has taken place at all.

  4. The Query

    mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
    

    Something of a formality, the rendered query is:

    SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
    

As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

mysql_set_charset() cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string(), since that's just a different wrapper around this same function.

The problem, if not already obvious, is that the call to mysql_real_escape_string() cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).

The Ugly

It gets worse. NO_BACKSLASH_ESCAPES may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote> grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes().

Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.

The Saving Grace

So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql() will not be used, or its assumption about which quote characters require repeating will be correct.

For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES also enables ANSI_QUOTES mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).

In PDO, both its equivalent function PDO::quote() and its prepared statement emulator call upon mysql_handle_quoter()—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.

As of MySQL v5.7.6, this bug has been fixed. See change log:

Functionality Added or Changed

Safe Examples

Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):

mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES.

mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

...because we're quoting our string literal with single-quotes.

$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);

...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).

$var  = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

...because PDO's quote() function not only escapes the literal, but also quotes it (in single-quote ' characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.

$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

...because MySQLi prepared statements are safe.

Wrapping Up

Thus, if you:

  • use native prepared statements

OR

  • use MySQL v5.7.6 or later

OR

  • in addition to employing one of the solutions in ircmaxell's summary, use at least one of:

    • PDO;
    • single-quoted string literals; or
    • an explicitly set SQL mode that does not include NO_BACKSLASH_ESCAPES

...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).

Is it better to use "is" or "==" for number comparison in Python?

>>> 2 == 2.0
True
>>> 2 is 2.0
False

Use ==

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In JSF 1.2 this was done by <f:setPropertyActionListener> (within the command component). In JSF 2.0 (EL 2.2 to be precise, thanks to BalusC) it's possible to do it like this: action="${filterList.insert(f.id)}

Read file line by line in PowerShell

The almighty switch works well here:

'one
two
three' > file

$regex = '^t'

switch -regex -file file { 
  $regex { "line is $_" } 
}

Output:

line is two
line is three

JAXB: how to marshall map into <key>value</key>

When using xml-apis-1.0, you can serialize and deserialize this:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <map>
        <key>value</key>
        <key2>value2</key2>
    </map>
</root>

Using this code:

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

@XmlRootElement
class Root {

    public XmlRawData map;

}

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/input.xml"));

        System.out.println(root.map.getAsMap());

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

class XmlRawData {

    @XmlAnyElement
    public List<Element> elements;

    public void setFromMap(Map<String, String> values) {

        Document document;
        try {
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }

        for (Entry<String, String> entry : values.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.appendChild(document.createTextNode(entry.getValue()));
            elements.add(mapElement);
        }
    }

    public Map<String, String> getAsMap() {
        Map<String, String> map = new HashMap<String, String>();

        for (Element element : elements) {
            if (element.getNodeType() == Node.ELEMENT_NODE) {
                map.put(element.getLocalName(), element.getFirstChild().getNodeValue());
            }
        }

        return map;
    }
}

TypeScript sorting an array

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

Linux: is there a read or recv from socket with timeout?

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Reportedly on Windows this should be done before calling bind. I have verified by experiment that it can be done either before or after bind on Linux and OS X.

Fail during installation of Pillow (Python module) in Linux

The alternative, if you don't want to install libjpeg:

CFLAGS="--disable-jpeg" pip install pillow

From https://pillow.readthedocs.io/en/3.0.0/installation.html#external-libraries

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

if-else statement inside jsx: ReactJS

 render() {
     return (   
         <View style={styles.container}>
         (() => {                                                       
             if (this.state == 'news') {
                return  <Text>data</Text>
            }
            else 
             return  <Text></Text>
        })()
         </View>
     )
 }

https://react-cn.github.io/react/tips/if-else-in-JSX.html

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

What's the best way to validate an XML file against an XSD file?

Validate against online schemas

Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));
Validator validator = schema.newValidator();
validator.validate(xmlFile);

Validate against local schemas

Offline XML Validation with Java

How do I create a multiline Python string with inline variables?

If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

Make sure to escape all curly braces like I did: "{{", "}}"

print call stack in C or C++

Boost stacktrace

Documented at: https://www.boost.org/doc/libs/1_66_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack

This is the most convenient option I've seen so far, because it:

  • can actually print out the line numbers.

    It just makes calls to addr2line however, which is ugly and might be slow if your are taking too many traces.

  • demangles by default

  • Boost is header only, so no need to modify your build system most likely

boost_stacktrace.cpp

#include <iostream>

#define BOOST_STACKTRACE_USE_ADDR2LINE
#include <boost/stacktrace.hpp>

void my_func_2(void) {
    std::cout << boost::stacktrace::stacktrace() << std::endl;
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main(int argc, char **argv) {
    long long unsigned int n;
    if (argc > 1) {
        n = strtoul(argv[1], NULL, 0);
    } else {
        n = 1;
    }
    for (long long unsigned int i = 0; i < n; ++i) {
        my_func_1(1);   // line 28
        my_func_1(2.0); // line 29
    }
}

Unfortunately, it seems to be a more recent addition, and the package libboost-stacktrace-dev is not present in Ubuntu 16.04, only 18.04:

sudo apt-get install libboost-stacktrace-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o boost_stacktrace.out -std=c++11 \
  -Wall -Wextra -pedantic-errors boost_stacktrace.cpp -ldl
./boost_stacktrace.out

We have to add -ldl at the end or else compilation fails.

Output:

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::basic_stacktrace() at /usr/include/boost/stacktrace/stacktrace.hpp:129
 1# my_func_1(int) at /home/ciro/test/boost_stacktrace.cpp:18
 2# main at /home/ciro/test/boost_stacktrace.cpp:29 (discriminator 2)
 3# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 4# _start in ./boost_stacktrace.out

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::basic_stacktrace() at /usr/include/boost/stacktrace/stacktrace.hpp:129
 1# my_func_1(double) at /home/ciro/test/boost_stacktrace.cpp:13
 2# main at /home/ciro/test/boost_stacktrace.cpp:27 (discriminator 2)
 3# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 4# _start in ./boost_stacktrace.out

The output and is further explained on the "glibc backtrace" section below, which is analogous.

Note how my_func_1(int) and my_func_1(float), which are mangled due to function overload, were nicely demangled for us.

Note that the first int calls is off by one line (28 instead of 27 and the second one is off by two lines (27 instead of 29). It was suggested in the comments that this is because the following instruction address is being considered, which makes 27 become 28, and 29 jump off the loop and become 27.

We then observe that with -O3, the output is completely mutilated:

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::size() const at /usr/include/boost/stacktrace/stacktrace.hpp:215
 1# my_func_1(double) at /home/ciro/test/boost_stacktrace.cpp:12
 2# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 3# _start in ./boost_stacktrace.out

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::size() const at /usr/include/boost/stacktrace/stacktrace.hpp:215
 1# main at /home/ciro/test/boost_stacktrace.cpp:31
 2# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 3# _start in ./boost_stacktrace.out

Backtraces are in general irreparably mutilated by optimizations. Tail call optimization is a notable example of that: What is tail call optimization?

Benchmark run on -O3:

time  ./boost_stacktrace.out 1000 >/dev/null

Output:

real    0m43.573s
user    0m30.799s
sys     0m13.665s

So as expected, we see that this method is extremely slow likely to to external calls to addr2line, and is only going to be feasible if a limited number of calls are being made.

Each backtrace print seems to take hundreds of milliseconds, so be warned that if a backtrace happens very often, program performance will suffer significantly.

Tested on Ubuntu 19.10, GCC 9.2.1, boost 1.67.0.

glibc backtrace

Documented at: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html

main.c

#include <stdio.h>
#include <stdlib.h>

/* Paste this on the file you want to debug. */
#include <stdio.h>
#include <execinfo.h>
void print_trace(void) {
    char **strings;
    size_t i, size;
    enum Constexpr { MAX_SIZE = 1024 };
    void *array[MAX_SIZE];
    size = backtrace(array, MAX_SIZE);
    strings = backtrace_symbols(array, size);
    for (i = 0; i < size; i++)
        printf("%s\n", strings[i]);
    puts("");
    free(strings);
}

void my_func_3(void) {
    print_trace();
}

void my_func_2(void) {
    my_func_3();
}

void my_func_1(void) {
    my_func_3();
}

int main(void) {
    my_func_1(); /* line 33 */
    my_func_2(); /* line 34 */
    return 0;
}

Compile:

gcc -fno-pie -ggdb3 -O3 -no-pie -o main.out -rdynamic -std=c99 \
  -Wall -Wextra -pedantic-errors main.c

-rdynamic is the key required option.

Run:

./main.out

Outputs:

./main.out(print_trace+0x2d) [0x400a3d]
./main.out(main+0x9) [0x4008f9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f35a5aad830]
./main.out(_start+0x29) [0x400939]

./main.out(print_trace+0x2d) [0x400a3d]
./main.out(main+0xe) [0x4008fe]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f35a5aad830]
./main.out(_start+0x29) [0x400939]

So we immediately see that an inlining optimization happened, and some functions were lost from the trace.

If we try to get the addresses:

addr2line -e main.out 0x4008f9 0x4008fe

we obtain:

/home/ciro/main.c:21
/home/ciro/main.c:36

which is completely off.

If we do the same with -O0 instead, ./main.out gives the correct full trace:

./main.out(print_trace+0x2e) [0x4009a4]
./main.out(my_func_3+0x9) [0x400a50]
./main.out(my_func_1+0x9) [0x400a68]
./main.out(main+0x9) [0x400a74]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f4711677830]
./main.out(_start+0x29) [0x4008a9]

./main.out(print_trace+0x2e) [0x4009a4]
./main.out(my_func_3+0x9) [0x400a50]
./main.out(my_func_2+0x9) [0x400a5c]
./main.out(main+0xe) [0x400a79]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f4711677830]
./main.out(_start+0x29) [0x4008a9]

and then:

addr2line -e main.out 0x400a74 0x400a79

gives:

/home/cirsan01/test/main.c:34
/home/cirsan01/test/main.c:35

so the lines are off by just one, TODO why? But this might still be usable.

Conclusion: backtraces can only possibly show perfectly with -O0. With optimizations, the original backtrace is fundamentally modified in the compiled code.

I couldn't find a simple way to automatically demangle C++ symbols with this however, here are some hacks:

Tested on Ubuntu 16.04, GCC 6.4.0, libc 2.23.

glibc backtrace_symbols_fd

This helper is a bit more convenient than backtrace_symbols, and produces basically identical output:

/* Paste this on the file you want to debug. */
#include <execinfo.h>
#include <stdio.h>
#include <unistd.h>
void print_trace(void) {
    size_t i, size;
    enum Constexpr { MAX_SIZE = 1024 };
    void *array[MAX_SIZE];
    size = backtrace(array, MAX_SIZE);
    backtrace_symbols_fd(array, size, STDOUT_FILENO);
    puts("");
}

Tested on Ubuntu 16.04, GCC 6.4.0, libc 2.23.

glibc backtrace with C++ demangling hack 1: -export-dynamic + dladdr

Adapted from: https://gist.github.com/fmela/591333/c64f4eb86037bb237862a8283df70cdfc25f01d3

This is a "hack" because it requires changing the ELF with -export-dynamic.

glibc_ldl.cpp

#include <dlfcn.h>     // for dladdr
#include <cxxabi.h>    // for __cxa_demangle

#include <cstdio>
#include <string>
#include <sstream>
#include <iostream>

// This function produces a stack backtrace with demangled function & method names.
std::string backtrace(int skip = 1)
{
    void *callstack[128];
    const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
    char buf[1024];
    int nFrames = backtrace(callstack, nMaxFrames);
    char **symbols = backtrace_symbols(callstack, nFrames);

    std::ostringstream trace_buf;
    for (int i = skip; i < nFrames; i++) {
        Dl_info info;
        if (dladdr(callstack[i], &info)) {
            char *demangled = NULL;
            int status;
            demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
            std::snprintf(
                buf,
                sizeof(buf),
                "%-3d %*p %s + %zd\n",
                i,
                (int)(2 + sizeof(void*) * 2),
                callstack[i],
                status == 0 ? demangled : info.dli_sname,
                (char *)callstack[i] - (char *)info.dli_saddr
            );
            free(demangled);
        } else {
            std::snprintf(buf, sizeof(buf), "%-3d %*p\n",
                i, (int)(2 + sizeof(void*) * 2), callstack[i]);
        }
        trace_buf << buf;
        std::snprintf(buf, sizeof(buf), "%s\n", symbols[i]);
        trace_buf << buf;
    }
    free(symbols);
    if (nFrames == nMaxFrames)
        trace_buf << "[truncated]\n";
    return trace_buf.str();
}

void my_func_2(void) {
    std::cout << backtrace() << std::endl;
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

Compile and run:

g++ -fno-pie -ggdb3 -O0 -no-pie -o glibc_ldl.out -std=c++11 -Wall -Wextra \
  -pedantic-errors -fpic glibc_ldl.cpp -export-dynamic -ldl
./glibc_ldl.out 

output:

1             0x40130a my_func_2() + 41
./glibc_ldl.out(_Z9my_func_2v+0x29) [0x40130a]
2             0x40139e my_func_1(int) + 16
./glibc_ldl.out(_Z9my_func_1i+0x10) [0x40139e]
3             0x4013b3 main + 18
./glibc_ldl.out(main+0x12) [0x4013b3]
4       0x7f7594552b97 __libc_start_main + 231
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7f7594552b97]
5             0x400f3a _start + 42
./glibc_ldl.out(_start+0x2a) [0x400f3a]

1             0x40130a my_func_2() + 41
./glibc_ldl.out(_Z9my_func_2v+0x29) [0x40130a]
2             0x40138b my_func_1(double) + 18
./glibc_ldl.out(_Z9my_func_1d+0x12) [0x40138b]
3             0x4013c8 main + 39
./glibc_ldl.out(main+0x27) [0x4013c8]
4       0x7f7594552b97 __libc_start_main + 231
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7f7594552b97]
5             0x400f3a _start + 42
./glibc_ldl.out(_start+0x2a) [0x400f3a]

Tested on Ubuntu 18.04.

glibc backtrace with C++ demangling hack 2: parse backtrace output

Shown at: https://panthema.net/2008/0901-stacktrace-demangled/

This is a hack because it requires parsing.

TODO get it to compile and show it here.

libunwind

TODO does this have any advantage over glibc backtrace? Very similar output, also requires modifying the build command, but not part of glibc so requires an extra package installation.

Code adapted from: https://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/

main.c

/* This must be on top. */
#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

/* Paste this on the file you want to debug. */
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <stdio.h>
void print_trace() {
    char sym[256];
    unw_context_t context;
    unw_cursor_t cursor;
    unw_getcontext(&context);
    unw_init_local(&cursor, &context);
    while (unw_step(&cursor) > 0) {
        unw_word_t offset, pc;
        unw_get_reg(&cursor, UNW_REG_IP, &pc);
        if (pc == 0) {
            break;
        }
        printf("0x%lx:", pc);
        if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
            printf(" (%s+0x%lx)\n", sym, offset);
        } else {
            printf(" -- error: unable to obtain symbol name for this frame\n");
        }
    }
    puts("");
}

void my_func_3(void) {
    print_trace();
}

void my_func_2(void) {
    my_func_3();
}

void my_func_1(void) {
    my_func_3();
}

int main(void) {
    my_func_1(); /* line 46 */
    my_func_2(); /* line 47 */
    return 0;
}

Compile and run:

sudo apt-get install libunwind-dev
gcc -fno-pie -ggdb3 -O3 -no-pie -o main.out -std=c99 \
  -Wall -Wextra -pedantic-errors main.c -lunwind

Either #define _XOPEN_SOURCE 700 must be on top, or we must use -std=gnu99:

Run:

./main.out

Output:

0x4007db: (main+0xb)
0x7f4ff50aa830: (__libc_start_main+0xf0)
0x400819: (_start+0x29)

0x4007e2: (main+0x12)
0x7f4ff50aa830: (__libc_start_main+0xf0)
0x400819: (_start+0x29)

and:

addr2line -e main.out 0x4007db 0x4007e2

gives:

/home/ciro/main.c:34
/home/ciro/main.c:49

With -O0:

0x4009cf: (my_func_3+0xe)
0x4009e7: (my_func_1+0x9)
0x4009f3: (main+0x9)
0x7f7b84ad7830: (__libc_start_main+0xf0)
0x4007d9: (_start+0x29)

0x4009cf: (my_func_3+0xe)
0x4009db: (my_func_2+0x9)
0x4009f8: (main+0xe)
0x7f7b84ad7830: (__libc_start_main+0xf0)
0x4007d9: (_start+0x29)

and:

addr2line -e main.out 0x4009f3 0x4009f8

gives:

/home/ciro/main.c:47
/home/ciro/main.c:48

Tested on Ubuntu 16.04, GCC 6.4.0, libunwind 1.1.

libunwind with C++ name demangling

Code adapted from: https://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/

unwind.cpp

#define UNW_LOCAL_ONLY
#include <cxxabi.h>
#include <libunwind.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>

void backtrace() {
  unw_cursor_t cursor;
  unw_context_t context;

  // Initialize cursor to current frame for local unwinding.
  unw_getcontext(&context);
  unw_init_local(&cursor, &context);

  // Unwind frames one by one, going up the frame stack.
  while (unw_step(&cursor) > 0) {
    unw_word_t offset, pc;
    unw_get_reg(&cursor, UNW_REG_IP, &pc);
    if (pc == 0) {
      break;
    }
    std::printf("0x%lx:", pc);

    char sym[256];
    if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
      char* nameptr = sym;
      int status;
      char* demangled = abi::__cxa_demangle(sym, nullptr, nullptr, &status);
      if (status == 0) {
        nameptr = demangled;
      }
      std::printf(" (%s+0x%lx)\n", nameptr, offset);
      std::free(demangled);
    } else {
      std::printf(" -- error: unable to obtain symbol name for this frame\n");
    }
  }
}

void my_func_2(void) {
    backtrace();
    std::cout << std::endl; // line 43
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}  // line 54

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

Compile and run:

sudo apt-get install libunwind-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o unwind.out -std=c++11 \
  -Wall -Wextra -pedantic-errors unwind.cpp -lunwind -pthread
./unwind.out

Output:

0x400c80: (my_func_2()+0x9)
0x400cb7: (my_func_1(int)+0x10)
0x400ccc: (main+0x12)
0x7f4c68926b97: (__libc_start_main+0xe7)
0x400a3a: (_start+0x2a)

0x400c80: (my_func_2()+0x9)
0x400ca4: (my_func_1(double)+0x12)
0x400ce1: (main+0x27)
0x7f4c68926b97: (__libc_start_main+0xe7)
0x400a3a: (_start+0x2a)

and then we can find the lines of my_func_2 and my_func_1(int) with:

addr2line -e unwind.out 0x400c80 0x400cb7

which gives:

/home/ciro/test/unwind.cpp:43
/home/ciro/test/unwind.cpp:54

TODO: why are the lines off by one?

Tested on Ubuntu 18.04, GCC 7.4.0, libunwind 1.2.1.

GDB automation

We can also do this with GDB without recompiling by using: How to do an specific action when a certain breakpoint is hit in GDB?

Although if you are going to print the backtrace a lot, this will likely be less fast than the other options, but maybe we can reach native speeds with compile code, but I'm lazy to test it out now: How to call assembly in gdb?

main.cpp

void my_func_2(void) {}

void my_func_1(double f) {
    my_func_2();
}

void my_func_1(int i) {
    my_func_2();
}

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

main.gdb

start
break my_func_2
commands
  silent
  backtrace
  printf "\n"
  continue
end
continue

Compile and run:

g++ -ggdb3 -o main.out main.cpp
gdb -nh -batch -x main.gdb main.out

Output:

Temporary breakpoint 1 at 0x1158: file main.cpp, line 12.

Temporary breakpoint 1, main () at main.cpp:12
12          my_func_1(1);
Breakpoint 2 at 0x555555555129: file main.cpp, line 1.
#0  my_func_2 () at main.cpp:1
#1  0x0000555555555151 in my_func_1 (i=1) at main.cpp:8
#2  0x0000555555555162 in main () at main.cpp:12

#0  my_func_2 () at main.cpp:1
#1  0x000055555555513e in my_func_1 (f=2) at main.cpp:4
#2  0x000055555555516f in main () at main.cpp:13

[Inferior 1 (process 14193) exited normally]

TODO I wanted to do this with just -ex from the command line to not have to create main.gdb but I couldn't get the commands to work there.

Tested in Ubuntu 19.04, GDB 8.2.

Linux kernel

How to print the current thread stack trace inside the Linux kernel?

libdwfl

This was originally mentioned at: https://stackoverflow.com/a/60713161/895245 and it might be the best method, but I have to benchmark a bit more, but please go upvote that answer.

TODO: I tried to minimize the code in that answer, which was working, to a single function, but it is segfaulting, let me know if anyone can find why.

dwfl.cpp

#include <cassert>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>

#include <cxxabi.h> // __cxa_demangle
#include <elfutils/libdwfl.h> // Dwfl*
#include <execinfo.h> // backtrace
#include <unistd.h> // getpid

// https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname
std::string demangle(const char* name) {
    int status = -4;
    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };
    return (status==0) ? res.get() : name ;
}

std::string debug_info(Dwfl* dwfl, void* ip) {
    std::string function;
    int line = -1;
    char const* file;
    uintptr_t ip2 = reinterpret_cast<uintptr_t>(ip);
    Dwfl_Module* module = dwfl_addrmodule(dwfl, ip2);
    char const* name = dwfl_module_addrname(module, ip2);
    function = name ? demangle(name) : "<unknown>";
    if (Dwfl_Line* dwfl_line = dwfl_module_getsrc(module, ip2)) {
        Dwarf_Addr addr;
        file = dwfl_lineinfo(dwfl_line, &addr, &line, nullptr, nullptr, nullptr);
    }
    std::stringstream ss;
    ss << ip << ' ' << function;
    if (file)
        ss << " at " << file << ':' << line;
    ss << std::endl;
    return ss.str();
}

std::string stacktrace() {
    // Initialize Dwfl.
    Dwfl* dwfl = nullptr;
    {
        Dwfl_Callbacks callbacks = {};
        char* debuginfo_path = nullptr;
        callbacks.find_elf = dwfl_linux_proc_find_elf;
        callbacks.find_debuginfo = dwfl_standard_find_debuginfo;
        callbacks.debuginfo_path = &debuginfo_path;
        dwfl = dwfl_begin(&callbacks);
        assert(dwfl);
        int r;
        r = dwfl_linux_proc_report(dwfl, getpid());
        assert(!r);
        r = dwfl_report_end(dwfl, nullptr, nullptr);
        assert(!r);
        static_cast<void>(r);
    }

    // Loop over stack frames.
    std::stringstream ss;
    {
        void* stack[512];
        int stack_size = ::backtrace(stack, sizeof stack / sizeof *stack);
        for (int i = 0; i < stack_size; ++i) {
            ss << i << ": ";

            // Works.
            ss << debug_info(dwfl, stack[i]);

#if 0
            // TODO intended to do the same as above, but segfaults,
            // so possibly UB In above function that does not blow up by chance?
            void *ip = stack[i];
            std::string function;
            int line = -1;
            char const* file;
            uintptr_t ip2 = reinterpret_cast<uintptr_t>(ip);
            Dwfl_Module* module = dwfl_addrmodule(dwfl, ip2);
            char const* name = dwfl_module_addrname(module, ip2);
            function = name ? demangle(name) : "<unknown>";
            // TODO if I comment out this line it does not blow up anymore.
            if (Dwfl_Line* dwfl_line = dwfl_module_getsrc(module, ip2)) {
              Dwarf_Addr addr;
              file = dwfl_lineinfo(dwfl_line, &addr, &line, nullptr, nullptr, nullptr);
            }
            ss << ip << ' ' << function;
            if (file)
                ss << " at " << file << ':' << line;
            ss << std::endl;
#endif
        }
    }
    dwfl_end(dwfl);
    return ss.str();
}

void my_func_2() {
    std::cout << stacktrace() << std::endl;
    std::cout.flush();
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main(int argc, char **argv) {
    long long unsigned int n;
    if (argc > 1) {
        n = strtoul(argv[1], NULL, 0);
    } else {
        n = 1;
    }
    for (long long unsigned int i = 0; i < n; ++i) {
        my_func_1(1);
        my_func_1(2.0);
    }
}

Compile and run:

sudo apt install libdw-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o dwfl.out -std=c++11 -Wall -Wextra -pedantic-errors dwfl.cpp -ldw
./dwfl.out

Output:

0: 0x402b74 stacktrace[abi:cxx11]() at /home/ciro/test/dwfl.cpp:65
1: 0x402ce0 my_func_2() at /home/ciro/test/dwfl.cpp:100
2: 0x402d7d my_func_1(int) at /home/ciro/test/dwfl.cpp:112
3: 0x402de0 main at /home/ciro/test/dwfl.cpp:123
4: 0x7f7efabbe1e3 __libc_start_main at ../csu/libc-start.c:342
5: 0x40253e _start at ../csu/libc-start.c:-1

0: 0x402b74 stacktrace[abi:cxx11]() at /home/ciro/test/dwfl.cpp:65
1: 0x402ce0 my_func_2() at /home/ciro/test/dwfl.cpp:100
2: 0x402d66 my_func_1(double) at /home/ciro/test/dwfl.cpp:107
3: 0x402df1 main at /home/ciro/test/dwfl.cpp:121
4: 0x7f7efabbe1e3 __libc_start_main at ../csu/libc-start.c:342
5: 0x40253e _start at ../csu/libc-start.c:-1

Benchmark run:

g++ -fno-pie -ggdb3 -O3 -no-pie -o dwfl.out -std=c++11 -Wall -Wextra -pedantic-errors dwfl.cpp -ldw
time ./dwfl.out 1000 >/dev/null

Output:

real    0m3.751s
user    0m2.822s
sys     0m0.928s

So we see that this method is 10x faster than Boost's stacktrace, and might therefore be applicable to more use cases.

Tested in Ubuntu 19.10 amd64, libdw-dev 0.176-1.1.

See also

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

This worked for me

<p:column headerText="name" style="width:20px;"/>

How to use ADB in Android Studio to view an SQLite DB

What it mentions as you type adb?

step1. >adb shell
step2. >cd data/data
step3. >ls -l|grep "your app package here"
step4. >cd "your app package here"
step5. >sqlite3 xx.db

Removing unwanted table cell borders with CSS

Try assigning the style of border: 0px; border-collapse: collapse; to the table element.

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

If you are passing (like me) all the parameters like port, username, password through a system and you are not allow to modify the code, then you can do that easy change on the web.config:

<system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true"/>
    </smtp>
  </mailSettings>
</system.net>

How to Refresh a Component in Angular

router.navigate['/path'] will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page

Call to undefined function mysql_query() with Login

You are mixing the deprecated mysql extension with mysqli.

Try something like:

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

Windows 7 environment variable not working in path

I had the same problem, I fixed it by removing PATHEXT from user variable. It must only exist in System variable with .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

Also remove the variable from user to system and only include that path on user variable

Android Studio update -Error:Could not run build action using Gradle distribution

Go on Project->Settings->Compiler(Gradle-based android project), find the text field "VM option" and put there:

-Xmx512m -XX:MaxPermSize=512m

This shouls solve the issue in any case the error shown in the gradle message window is "Could not reserve enough space for object heap"

Hope this helps

Are PHP short tags acceptable to use?

3 tags are available in php:

  1. long-form tag that <?php ?> no need to directive any configured
  2. short_open_tag that <? ?> available if short_open_tag option in php.ini is on
  3. shorten tag <?= since php 5.4.0 it is always available

from php 7.0.0 asp and script tag are removed

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

How do you pass view parameters when navigating from an action in JSF2?

Without a nicer solution, what I found to work is simply building my query string in the bean return:

public String submit() {
    // Do something
    return "/page2.xhtml?faces-redirect=true&id=" + id;
}

Not the most flexible of solutions, but seems to work how I want it to.

Also using this approach to clean up the process of building the query string: http://www.warski.org/blog/?p=185

How to center horizontally div inside parent div

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

Convert a Unicode string to a string in Python (containing extra symbols)

If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first encode it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:

>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'

This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.

When writing to files, you can get rid of this manual encode/decode process by using the codecs module. So, to open a file that encodes all Unicode strings into UTF-8, use:

import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string)  # Stored on disk as UTF-8

Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.

In Python 3, this form of file access is the default, and the built-in open function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

"Cross origin requests are only supported for HTTP." error when loading a local file

Many problem for this, with my problem is missing '/' example: jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/ It's must be: http://localhost:xxx/Product/getList_tagLabels/

I hope this help for who meet this problem.

NullInjectorError: No provider for AngularFirestore

I had same issue and below is resolved.

Old Service Code:

@Injectable()

Updated working Service Code:

@Injectable({
  providedIn: 'root'
})

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

  • Update your support library to last version

  • Open Manifest File , and add it into Manifest File

  • <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>

  • And add for recyclerview in >> build.gradle Module app :

  • compile 'com.android.support:recyclerview-v7:25.3.1'

  • And click : Sync Now

Angular no provider for NameService

You should be injecting NameService inside providers array of your AppModule's NgModule metadata.

@NgModule({
   providers: [MyService]
})

and be sure import in your component by same name (case sensitive),becouse SystemJs is case sensitive (by design). If you use different path name in your project files like this:

main.module.ts

import { MyService } from './MyService';

your-component.ts

import { MyService } from './Myservice';

then System js will make double imports

Can I hide/show asp:Menu items based on role?

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">, you need to remove NoActionBar, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java

How to link home brew python version and set it as default

If you used

brew install python

before 'unlink' you got

brew info python
/usr/local/Cellar/python/2.7.11

python -V
Python 2.7.10

so do

brew unlink python && brew link python

and open a new terminal shell

python -V
Python 2.7.11

Flexbox: center horizontally and vertically

How to Center Elements Vertically and Horizontally in Flexbox

Below are two general centering solutions.

One for vertically-aligned flex items (flex-direction: column) and the other for horizontally-aligned flex items (flex-direction: row).

In both cases the height of the centered divs can be variable, undefined, unknown, whatever. The height of the centered divs doesn't matter.

Here's the HTML for both:

<div id="container"><!-- flex container -->

    <div class="box" id="bluebox"><!-- flex item -->
        <p>DIV #1</p>
    </div>

    <div class="box" id="redbox"><!-- flex item -->
        <p>DIV #2</p>
    </div>

</div>

CSS (excluding decorative styles)

When flex items are stacked vertically:

#container {
    display: flex;           /* establish flex container */
    flex-direction: column;  /* make main axis vertical */
    justify-content: center; /* center items vertically, in this case */
    align-items: center;     /* center items horizontally, in this case */
    height: 300px;
}

.box {
    width: 300px;
    margin: 5px;
    text-align: center;     /* will center text in <p>, which is not a flex item */
}

enter image description here

DEMO


When flex items are stacked horizontally:

Adjust the flex-direction rule from the code above.

#container {
    display: flex;
    flex-direction: row;     /* make main axis horizontal (default setting) */
    justify-content: center; /* center items horizontally, in this case */
    align-items: center;     /* center items vertically, in this case */
    height: 300px;
}

enter image description here

DEMO


Centering the content of the flex items

The scope of a flex formatting context is limited to a parent-child relationship. Descendants of a flex container beyond the children do not participate in flex layout and will ignore flex properties. Essentially, flex properties are not inheritable beyond the children.

Hence, you will always need to apply display: flex or display: inline-flex to a parent element in order to apply flex properties to the child.

In order to vertically and/or horizontally center text or other content contained in a flex item, make the item a (nested) flex container, and repeat the centering rules.

.box {
    display: flex;
    justify-content: center;
    align-items: center;        /* for single line flex container */
    align-content: center;      /* for multi-line flex container */
}

More details here: How to vertically align text inside a flexbox?

Alternatively, you can apply margin: auto to the content element of the flex item.

p { margin: auto; }

Learn about flex auto margins here: Methods for Aligning Flex Items (see box#56).


Centering multiple lines of flex items

When a flex container has multiple lines (due to wrapping) the align-content property will be necessary for cross-axis alignment.

From the spec:

8.4. Packing Flex Lines: the align-content property

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container.

More details here: How does flex-wrap work with align-self, align-items and align-content?


Browser support

Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.


Centering solution for older browsers

For an alternative centering solution using CSS table and positioning properties see this answer: https://stackoverflow.com/a/31977476/3597276

REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

Pretty-Printing JSON with PHP

here's the function i use myself, the api is just like json_encode, except it has a 3rd argument exclude_flags in case you want to exclude some of the default flags (like JSON_UNESCAPED_SLASHES)

function json_encode_pretty($data, int $extra_flags = 0, int $exclude_flags = 0): string
{
    // prettiest flags for: 7.3.9
    $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_PRESERVE_ZERO_FRACTION | (defined("JSON_THROW_ON_ERROR") ? JSON_THROW_ON_ERROR : 0);
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;
    return (json_encode($data, $flags));
}

Hive insert query like SQL

No. This INSERT INTO tablename VALUES (x,y,z) syntax is currently not supported in Hive.

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

php artisan dump-autoload was deprecated on Laravel 5, so you need to use composer dump-autoload

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

PHP foreach change original array values

function checkForm(& $fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

This is what I would Suggest pass by reference

How do I get the directory that a program is running from?

As Minok mentioned, there is no such functionality specified ini C standard or C++ standard. This is considered to be purely OS-specific feature and it is specified in POSIX standard, for example.

Thorsten79 has given good suggestion, it is Boost.Filesystem library. However, it may be inconvenient in case you don't want to have any link-time dependencies in binary form for your program.

A good alternative I would recommend is collection of 100% headers-only STLSoft C++ Libraries Matthew Wilson (author of must-read books about C++). There is portable facade PlatformSTL gives access to system-specific API: WinSTL for Windows and UnixSTL on Unix, so it is portable solution. All the system-specific elements are specified with use of traits and policies, so it is extensible framework. There is filesystem library provided, of course.

How to playback MKV video in web browser?

You can use this following code. work just on chrome browser.

_x000D_
_x000D_
 function failed(e) {_x000D_
   // video playback failed - show a message saying why_x000D_
   switch (e.target.error.code) {_x000D_
     case e.target.error.MEDIA_ERR_ABORTED:_x000D_
       alert('You aborted the video playback.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_NETWORK:_x000D_
       alert('A network error caused the video download to fail part-way.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_DECODE:_x000D_
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
       break;_x000D_
     default:_x000D_
       alert('An unknown error occurred.');_x000D_
       break;_x000D_
   }_x000D_
 }
_x000D_
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
 <meta name="author" content="Amin Developer!" />_x000D_
_x000D_
 <title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

convert NSDictionary to NSString

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222

LIMIT 10..20 in SQL Server

For SQL Server 2012 + you can use.

SELECT  *
FROM     sys.databases
ORDER BY name 
OFFSET  5 ROWS 
FETCH NEXT 5 ROWS ONLY 

Storing Images in DB - Yea or Nay?

I have recently created a PHP/MySQL app which stores PDFs/Word files in a MySQL table (as big as 40MB per file so far).

Pros:

  • Uploaded files are replicated to backup server along with everything else, no separate backup strategy is needed (peace of mind).
  • Setting up the web server is slightly simpler because I don't need to have an uploads/ folder and tell all my applications where it is.
  • I get to use transactions for edits to improve data integrity - I don't have to worry about orphaned and missing files

Cons:

  • mysqldump now takes a looooong time because there is 500MB of file data in one of the tables.
  • Overall not very memory/cpu efficient when compared to filesystem

I'd call my implementation a success, it takes care of backup requirements and simplifies the layout of the project. The performance is fine for the 20-30 people who use the app.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

Looping through dictionary object

One way is to loop through the keys of the dictionary, which I recommend:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x) helps you retrieve the items in ascending order of the key. Note that Dictionary uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

Convert object string to JSON

Your string is not valid JSON, so JSON.parse (or jQuery's $.parseJSON) won't work.

One way would be to use eval to "parse" the "invalid" JSON, and then stringify it to "convert" it to valid JSON.

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));

I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str being generated, it should be fixed there, before it's generated, not after.

EDIT: You said (in the comments) this string is stored in a data attribute:

<div data-object="{hello:'world'}"></div>

I suggest you fix it here, so it can just be JSON.parsed. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):

<div data-object='{"hello":"world"}'></div>

Now, you can just use JSON.parse (or jQuery's $.parseJSON).

var str = '{"hello":"world"}';
var obj = JSON.parse(str);

Format decimal for percentage values?

If you want to use a format that allows you to keep the number like your entry this format works for me: "# \\%"

Removing first x characters from string?

Use del.

Example:

>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

Hamcrest compare collections

To complement @Joe's answer:

Hamcrest provides you with three main methods to match a list:

contains Checks for matching all the elements taking in count the order, if the list has more or less elements, it will fail

containsInAnyOrder Checks for matching all the elements and it doesn't matter the order, if the list has more or less elements, will fail

hasItems Checks just for the specified objects it doesn't matter if the list has more

hasItem Checks just for one object it doesn't matter if the list has more

All of them can receive a list of objects and use equals method for comparation or can be mixed with other matchers like @borjab mentioned:

assertThat(myList , contains(allOf(hasProperty("id", is(7L)), 
                                   hasProperty("name", is("testName1")),
                                   hasProperty("description", is("testDesc1"))),
                             allOf(hasProperty("id", is(11L)), 
                                   hasProperty("name", is("testName2")),
                                   hasProperty("description", is("testDesc2")))));

http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#contains(E...) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(java.util.Collection) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItems(T...)

Center a button in a Linear layout

Have you tried defining android:gravity="center_vertical|center_horizontal" inside the layout and setting android:layout_weight="1" in the image?

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Download this Sqlite manager its the easiest one to use Sqlite manager

and drag and drop your fetched file on its running instance

only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.

So i Use Firefox Plugin Side by side also which you can find at FireFox addons

How to get store information in Magento?

Just for information sake, in regards to my need... The answer I was looking for here was:

Mage::app()->getStore()->getGroup()->getName()

That is referenced on the admin page, where one can manage multiple stores... admin/system_store, I wanted to retrieve the store group title...

Convert Dictionary<string,string> to semicolon separated string in c#

For Linq to work over Dictionary you need at least .Net v3.5 and using System.Linq;.

Some alternatives:

string myDesiredOutput = string.Join(";", myDict.Select(x => string.Join("=", x.Key, x.Value)));

or

string myDesiredOutput = string.Join(";", myDict.Select(x => $"{x.Key}={x.Value}"));

If you can't use Linq for some reason, use Stringbuilder:

StringBuilder sb = new StringBuilder();
var isFirst = true;
foreach(var x in myDict) 
{
  if (isFirst) 
  {
    sb.Append($"{x.Key}={x.Value}");
    isFirst = false;
  }
  else
    sb.Append($";{x.Key}={x.Value}"); 
}

string myDesiredOutput = sb.ToString(); 

myDesiredOutput:

A=1;B=2;C=3;D=4

Login failed for user 'DOMAIN\MACHINENAME$'

This error occurs when you have configured your application with IIS, and IIS goes to SQL Server and tries to login with credentials that do not have proper permissions. This error can also occur when replication or mirroring is set up. I will be going over a solution that works always and is very simple. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties

In newly opened screen of Login Properties, go to the “User Mapping” tab. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed. On the lower screen, check the role db_owner. Click OK.

What does the exclamation mark do before the function?

There is a good point for using ! for function invocation marked on airbnb JavaScript guide

Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

!function abc(){}();
!function bca(){}();

Will work the same as

!function abc(){}();
(function bca(){})();

but saves one character and arbitrary looks better.

And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?

but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()

Will do safe code execution, same as a very first code sample.

This one will throw error cause JavaScript ASI will not be able to do its work.

!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()

One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

This works:

!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()

This not:

^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()

Angularjs $http.get().then and binding to a list

Promise returned from $http can not be binded directly (I dont exactly know why). I'm using wrapping service that works perfectly for me:

.factory('DocumentsList', function($http, $q){
    var d = $q.defer();
    $http.get('/DocumentsList').success(function(data){
        d.resolve(data);
    });
    return d.promise;
});

and bind to it in controller:

function Ctrl($scope, DocumentsList) {
    $scope.Documents = DocumentsList;
    ...
}

UPDATE!:

In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises

How to wrap async function calls into a sync function in Node.js or Javascript?

You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:

function f1() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);   
}

function f2() {
    f1();
    f1();
}

Fiber(function() {
    f2();
}).run();

Inside the fiber you call f1, f2 and sleep as if they were sync.

In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).

How to insert data into elasticsearch

You have to install the curl binary in your PC first. You can download it from here.

After that unzip it into a folder. Lets say C:\curl. In that folder you'll find curl.exe file with several .dll files.

Now open a command prompt by typing cmd from the start menu. And type cd c:\curl on there and it will take you to the curl folder. Now execute the curl command that you have.

One thing, windows doesn't support single quote around around the fields. So you have to use double quotes. For example I have converted your curl command like appropriate one.

curl -H "Content-Type: application/json" -XPOST "http://localhost:9200/indexname/typename/optionalUniqueId" -d "{ \"field\" : \"value\"}"

What is the recommended way to make a numeric TextField in JavaFX?

rate_text.textProperty().addListener(new ChangeListener<String>() {

    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        String s="";
        for(char c : newValue.toCharArray()){
            if(((int)c >= 48 && (int)c <= 57 || (int)c == 46)){
                s+=c;
            }
        }
        rate_text.setText(s);
    }
});

This works fine as it allows you to enter only integer value and decimal value (having ASCII code 46).

add elements to object array

You can't. However, you can replace the array with a new one which contains the extra element.

But it is easier and gives better performance to use an List<T> (uses interface IList) for this. List<T> does not resize the array every time you add an item - instead it doubles it when needed.

Try:

class Student
{
    IList<Subject> subjects = new List<Subject>();
}

class Subject
{
    string Name;
    string referenceBook;
}

Now you can say:

someStudent.subjects.Add(new Subject());

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

Javascript - get array of dates between 2 dates

d3js provides a lot of handy functions and includes d3.time for easy date manipulations

https://github.com/d3/d3-time

For your specific request:

Utc

var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));

or local time

var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));

range will be an array of date objects that fall on the first possible value for each day

you can change timeDay to timeHour, timeMonth etc for the same results on different intervals

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

CRC32 C or C++ implementation

The mhash library works pretty good for me. It's fast enough, supports multiple types of hashing (crc32, MD5, SHA-1, HAVAL, RIPEMD128, RIPEMD160, TIGER, GOST, etc.). To get CRC32 of a string you would do something like this:

 MHASH td = mhash_init(MHASH_CRC32);

 if (td == MHASH_FAILED) return -1; // handle failure

 mhash(td, s, strlen(s));

 unsigned int digest = 0; // crc32 will be stored here

 mhash_deinit(td, &digest);

 // do endian swap here if desired

Count of "Defined" Array Elements

Unfortunately, No. You will you have to go through a loop and count them.

EDIT :

var arrLength = arr.filter(Number);
alert(arrLength);

How do you append to a file?

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

How can I show/hide a specific alert with twitter bootstrap?

JS

        function showAlert(){
         $('#alert').show();
         setTimeout(function() { 
             $('#alert').hide(); 
         }, 5000);
        }

HTML

<div class="alert alert-success" id="alert" role="alert" style="display:none;" >YOUR MESSAGE</div>

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I am using Eclipse mars, Hibernate 5.2.1, Jdk7 and Oracle 11g.

I get the same error when I run Hibernate code generation tool. I guess it is a versions issue due to I have solved it through choosing Hibernate version (5.1 to 5.0) in the type frame in my Hibernate console configuration.

Difference between static class and singleton pattern?

I'm agree with this definition:

The word "single" means single object across the application life cycle, so the scope is at application level.

The static does not have any Object pointer, so the scope is at App Domain level.

Moreover both should be implemented to be thread-safe.

You can find interesting other differences about: Singleton Pattern Versus Static Class

Liquibase lock - reasons?

The problem was the buggy implementation of SequenceExists in Liquibase. Since the changesets with these statements took a very long time and was accidently aborted. Then the next try executing the liquibase-scripts the lock was held.

  <changeSet author="user" id="123">
    <preConditions onFail="CONTINUE">
      <not><sequenceExists sequenceName="SEQUENCE_NAME_SEQ" /></not>
    </preConditions>
    <createSequence sequenceName="SEQUENCE_NAME_SEQ"/>
  </changeSet>

A work around is using plain SQL to check this instead:

  <changeSet author="user" id="123">
    <preConditions onFail="CONTINUE">
            <sqlCheck expectedResult="0">
              select count(*) from user_sequences where sequence_name = 'SEQUENCE_NAME_SEQ';
            </sqlCheck>
    </preConditions>
    <createSequence sequenceName="SEQUENCE_NAME_SEQ"/>
  </changeSet>

Lockdata is stored in the table DATABASECHANGELOCK. To get rid of the lock you just change 1 to 0 or drop that table and recreate.

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

How to configure the web.config to allow requests of any length

I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.

Put spacing between divs in a horizontal row?

A possible idea would be to:

  1. delete the width: 25%; float:left; from the style of your divs
  2. wrap each of the four colored divs in a div that has style="width: 25%; float:left;"

The advantage with this approach is that all four columns will have equal width and the gap between them will always be 5px * 2.

Here's what it looks like:

_x000D_
_x000D_
.cellContainer {_x000D_
  width: 25%;_x000D_
  float: left;_x000D_
}
_x000D_
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: red;">A</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: orange;">B</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: green;">C</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: blue;">D</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

std::cin input with spaces?

How do I read a string from input?

You can read a single, whitespace terminated word with std::cin like this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a word:\n";

    string s;
    cin>>s;

    cout << "You entered " << s << '\n';
}

Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow. If you really need a whole line (and not just a single word) you can do this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a line:\n";

    string s;
    getline(cin,s);

    cout << "You entered " << s << '\n';
}

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

This code seems completely unnecessary:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS is assigned the result of getRecipientURL(message)
  2. Then immediately you overwrite the value of serverURLS, making the previous statement a dead store
  3. Then, because if (serverURLS != null) evaluates to true, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL. It is impossible for if (serverURLS != null) to evaluate to false!
  4. You never actually use the variable serverURLS beyond the previous line of code.

You could replace all of this with just:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

"Exception has been thrown by the target of an invocation" error (mscorlib)

I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.

Read/write to file using jQuery

No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.

If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.

Open Bootstrap Modal from code-behind

By default Bootstrap javascript files are included just before the closing body tag

        <script src="vendors/jquery-1.9.1.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
        <script src="assets/scripts.js"></script>
 </body>

I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:

    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
    <script src="assets/scripts.js"></script>

 <script type="text/javascript">
    function openModal() {
        $('#myModal').modal('show');
    }
</script>
</head>
<body>

then I could call the modal popup from code-behind with the following:

protected void lbEdit_Click(object sender, EventArgs e) {   
      ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}

Form onSubmit determine which submit button was pressed

First Suggestion:

Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex

<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />

Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.

Second Suggestion

The way I would handle this is to create two JS functions that handle each of the two buttons.

First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"

change

<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />

to

<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add 

the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.

Then your functions will work something like this...

function submitFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}
function submitAndAddFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

$(this).serialize() -- How to add a value?

You can write an extra function to process form data and you should add your nonform data as the data valu in the form.seethe example :

<form method="POST" id="add-form">
    <div class="form-group required ">
        <label for="key">Enter key</label>
        <input type="text" name="key" id="key"  data-nonformdata="hai"/>
    </div>
    <div class="form-group required ">
        <label for="name">Ente Name</label>
        <input type="text" name="name" id="name"  data-nonformdata="hello"/>
    </div>
    <input type="submit" id="add-formdata-btn" value="submit">
</form>

Then add this jquery for form processing

<script>
$(document).onready(function(){
    $('#add-form').submit(function(event){
        event.preventDefault();
        var formData = $("form").serializeArray();
        formData = processFormData(formData);
        // write further code here---->
    });
});
processFormData(formData)
{
    var data = formData;
    data.forEach(function(object){
        $('#add-form input').each(function(){
            if(this.name == object.name){
                var nonformData = $(this).data("nonformdata");
                formData.push({name:this.name,value:nonformData});
            }
        });
    });
    return formData;
}

How to open a website when a Button is clicked in Android application?

Here is a workable answer.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.tutorial.todolist"
  android:versionCode="1"
  android:versionName="1.0">
  <uses-sdk android:minSdkVersion="3"></uses-sdk>
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".todolist"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  </application>
</manifest>

todolist.java

package com.tutorial.todolist;
import android.app.Activity; 
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle; 
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class todolist extends Activity {    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.btn_clickme);
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
                myWebLink.setData(Uri.parse("http://www.anddev.org"));
                    startActivity(myWebLink);
             }
        });
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" > 

    <Button android:id="@+id/btn_clickme" 
      android:text="Click me..." 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 
</LinearLayout>

Pass form data to another page with php

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

index.php

<html>
<body>

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

</body>
</html> 

site2.php

 <html>
 <body>

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

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

New to unit testing, how to write great tests?

For unit testing, I found both Test Driven (tests first, code second) and code first, test second to be extremely useful.

Instead of writing code, then writing test. Write code then look at what you THINK the code should be doing. Think about all the intended uses of it and then write a test for each. I find writing tests to be faster but more involved than the coding itself. The tests should test the intention. Also thinking about the intentions you wind up finding corner cases in the test writing phase. And of course while writing tests you might find one of the few uses causes a bug (something I often find, and I am very glad this bug did not corrupt data and go unchecked).

Yet testing is almost like coding twice. In fact I had applications where there was more test code (quantity) than application code. One example was a very complex state machine. I had to make sure that after adding more logic to it, the entire thing always worked on all previous use cases. And since those cases were quite hard to follow by looking at the code, I wound up having such a good test suite for this machine that I was confident that it would not break even after making changes, and the tests saved my ass a few times. And as users or testers were finding bugs with the flow or corner cases unaccounted for, guess what, added to tests and never happened again. This really gave users confidence in my work in addition to making the whole thing super stable. And when it had to be re-written for performance reasons, guess what, it worked as expected on all inputs thanks to the tests.

All the simple examples like function square(number) is great and all, and are probably bad candidates to spend lots of time testing. The ones that do important business logic, thats where the testing is important. Test the requirements. Don't just test the plumbing. If the requirements change then guess what, the tests must too.

Testing should not be literally testing that function foo invoked function bar 3 times. That is wrong. Check if the result and side-effects are correct, not the inner mechanics.

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

How to restart Jenkins manually?

This can also be done using the Jenkins CLI:

java -jar jenkins-cli.jar -s http://[jenkins-server]/ restart

The jenkins-cli.jar file along with a full list of commands are available at http://[jenkins-server]/cli.

How to show loading spinner in jQuery?

You can always use Block UI jQuery plugin which does everything for you, and it even blocks the page of any input while the ajax is loading. In case that the plugin seems to not been working, you can read about the right way to use it in this answer. Check it out.

difference between throw and throw new Exception()

If you want you can throw a new Exception, with the original one set as an inner exception.

How to find files modified in last x minutes (find -mmin does not work as expected)

this command may be help you sir

find -type f -mtime -60

Loop through JSON object List

Here it is:

success: 
    function(data) {
        $.each(data, function(i, item){
            alert("Mine is " + i + "|" + item.title + "|" + item.key);
        });
    }

Sample JSON text:

{"title": "camp crowhouse", 
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}

Get OS-level system information

For windows I went this way.

    com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    long physicalMemorySize = os.getTotalPhysicalMemorySize();
    long freePhysicalMemory = os.getFreePhysicalMemorySize();
    long freeSwapSize = os.getFreeSwapSpaceSize();
    long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();

Here is the link with details.

Getting the difference between two repositories

git diff master remotes/b

That's incorrect. remotes/b is a remote, but not a branch.

To get it to work, I had to do:

git diff master remotes/b/master

Padding characters in printf

This one is even simpler and execs no external commands.

$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"

JBoss............... [UP]

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

How to unlock android phone through ADB

If you have to click OK after entering your passcode, this command will unlock your phone:

adb shell input text XXXX && adb shell input keyevent 66

Where

  • XXXX is your passcode.
  • 66 is keycode of button OK.
  • adb shell input text XXXX will enter your passcode.
  • adb shell input keyevent 66 will simulate click the OK button

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

Inline Form nested within Horizontal Form in Bootstrap 3

I had problems aligning the label to the input(s) elements so I transferred the label element inside the form-inline and form-group too...and it works..

<div class="form-group">
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <label for="birthday" class="col-xs-2 control-label">Birthday:</label>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

Specify the date format in XMLGregorianCalendar

you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);

How to reverse apply a stash?

The V1 git man page had a reference about un-applying a stash. The excerpt is below.

The newer V2 git man page doesn't include any reference to un-applying a stash but the below still works well

Un-applying a Stash In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash. Git does not provide such a stash un-apply command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse:

$ git stash show -p stash@{0} | git apply -R

Again, if you don’t specify a stash, Git assumes the most recent stash:

$ git stash show -p | git apply -R

You may want to create an alias and effectively add a stash-unapply command to your Git. For example:

$ git config --global alias.stash-unapply '!git stash show -p | git apply -R'
$ git stash apply
$ #... work work work
$ git stash-unapply

Why not use Double or Float to represent currency?

From Bloch, J., Effective Java, 2nd ed, Item 48:

The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.

For example, suppose you have $1.03 and you spend 42c. How much money do you have left?

System.out.println(1.03 - .42);

prints out 0.6100000000000001.

The right way to solve this problem is to use BigDecimal, int or long for monetary calculations.

Though BigDecimal has some caveats (please see currently accepted answer).

Get selected row item in DataGrid WPF

There are a lot of answers here that probably work in a specific context, but I was simply trying to get the text value of the first cell in a selected row. While the accepted answer here was the closest for me, it still required creating a type and casting the row into that type. I was looking for a simpler solution, and this is what I came up with:

MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row[0].ToString());

This gives me the first column in the selected row. Hopefully this helps someone else.

duplicate 'row.names' are not allowed error

In my case was a comma at the end of every line. By removing that worked

How to have an auto incrementing version number (Visual Studio)?

  • Star in version (like "2.10.3.*") - it is simple, but the numbers are too large

  • AutoBuildVersion - looks great but its dont work on my VS2010.

  • @DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.

so I changed the script a bit... commamd:

"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"

and script (this works to the "Debug" and "Release" configurations):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

What does "./" (dot slash) refer to in terms of an HTML file path location?

You can use the following list as quick reference:

   /   = Root directory
   .   = This location
   ..  = Up a directory
   ./  = Current directory
   ../ = Parent of current directory
   ../../ = Two directories backwards

Useful article: https://css-tricks.com/quick-reminder-about-file-paths/

How to print variable addresses in C?

I tried in online compiler https://www.onlinegdb.com/online_c++_compiler

int main()
{
    cout<<"Hello World";
    int x = 10;
    int *p = &x;
    printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
    printf("Address of p is %p\n", p);    // 0x7ffc7df0ea54

    return 0;
}

How do I fix the npm UNMET PEER DEPENDENCY warning?

Ok so i struggled for a long time trying to figure this out. Here is the nuclear option, for when you have exhausted all other ways..

When you are done, and it still works, import your actual code into this new project. Fix any compile errors the newer version of angular causes.

Thats what did it for me.. 1 hour of rework vs 6 hours of trying to figure out wtf was wrong.. wish i did it this way to start..

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

None of the above answer solved my issue. I got this same error when after I upgraded Xcode to 8, I went to Target --> Build Phases --> The Link Binary With Libraries and delete the framework that caused the problem and re added it and all the errors went away. Hope this will help others. enter image description here

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

Do this:

"android:style/Theme.Holo.Light.DarkActionBar"

You missed the android keyword before style. This denotes that it is an inbuilt style for Android.

Conditional statement in a one line lambda function in python?

The right way to do this is simple:

def rate(T):
    if (T > 200):
        return 200*exp(-T)
    else:
        return 400*exp(-T)

There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.

The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).


From a comment:

Well the function needed to fit in one line, which i didn't think you could do with a named function?

I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:

>>> def foo(x): return x + 1

Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.

Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.

But on the off chance that this really is what you need here: Just use exec instead of eval.

You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:

exec(my_function_string, my_globals, my_locals)

In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.

In earlier 2.x (before 2.6, I think?) you have to do it like this instead:

exec my_function_string in my_globals, my_locals

Show and hide a View with a slide up/down animation

I had a corner case where my view's height was still zero so...

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.view.View;

public final class AnimationUtils {

  public static void slideDown(final View view) {
        view.animate()
                .translationY(view.getHeight())
                .alpha(0.f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        // superfluous restoration
                        view.setVisibility(View.GONE);
                        view.setAlpha(1.f);
                        view.setTranslationY(0.f);
                    }
                });
    }

    public static void slideUp(final View view) {
        view.setVisibility(View.VISIBLE);
        view.setAlpha(0.f);

        if (view.getHeight() > 0) {
            slideUpNow(view);
        } else {
            // wait till height is measured
            view.post(new Runnable() {
                @Override
                public void run() {
                    slideUpNow(view);
                }
            });
        }
    }

    private static void slideUpNow(final View view) {
        view.setTranslationY(view.getHeight());
        view.animate()
                .translationY(0)
                .alpha(1.f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view.setVisibility(View.VISIBLE);
                        view.setAlpha(1.f);
                    }
                });
    }

}

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

ASP.NET MVC Razor render without encoding

Use @Html.Raw() with caution as you may cause more trouble with encoding and security. I understand the use case as I had to do this myself, but carefully... Just avoid allowing all text through. For example only preserve/convert specific character sequences and always encode the rest:

@Html.Raw(Html.Encode(myString).Replace("\n", "<br/>"))

Then you have peace of mind that you haven't created a potential security hole and any special/foreign characters are displayed correctly in all browsers.

How to decrypt an encrypted Apple iTunes iPhone backup?

Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.

Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.

Encrypted backups are great

The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.

An important warning: obviously, decrypting your iOS device’s backup removes its encryption. To protect your privacy and security, you should only run these scripts on a machine with full-disk encryption. While it is possible for a security expert to write software that protects keys in memory, e.g. by using functions like VirtualLock() and SecureZeroMemory() among many other things, these Python scripts will store your encryption keys and passwords in strings to be garbage-collected by Python. This means your secret keys and passwords will live in RAM for a while, from whence they will leak into your swap file and onto your disk, where an adversary can recover them. This completely defeats the point of having an encrypted backup.

How to decrypt backups: in theory

The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.

Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.

To decrypt:

  1. Decode the keybag stored in the BackupKeyBag entry of Manifest.plist. A high-level overview of this structure is given in the whitepaper. The iPhone Wiki describes the binary format: a 4-byte string type field, a 4-byte big-endian length field, and then the value itself.

    The important values are the PBKDF2 ITERations and SALT, the double protection salt DPSL and iteration count DPIC, and then for each protection CLS, the WPKY wrapped key.

  2. Using the backup password derive a 32-byte key using the correct PBKDF2 salt and number of iterations. First use a SHA256 round with DPSL and DPIC, then a SHA1 round with ITER and SALT.

    Unwrap each wrapped key according to RFC 3394.

  3. Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey in Manifest.plist, and unwrapping it. You now have a SQLite database with all file metadata.

  4. For each file of interest, get the class-encrypted per-file encryption key and protection class code by looking in the Files.file database column for a binary plist containing EncryptionKey and ProtectionClass entries. Strip the initial four-byte length tag from EncryptionKey before using.

    Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.

How to decrypt backups: in practice

First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:

CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \    
    pip install biplist fastpbkdf2 pycrypto

In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:

#!/usr/bin/env python3.7
# coding: UTF-8

from __future__ import print_function
from __future__ import division

import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify

import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException


def main():
    ## Parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('--backup-directory', dest='backup_directory',
                    default='testdata/encrypted')
    parser.add_argument('--password-pipe', dest='password_pipe',
                        help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
    parser.add_argument('--no-anonymize-output', dest='anonymize',
                        action='store_false')
    args = parser.parse_args()
    global ANONYMIZE_OUTPUT
    ANONYMIZE_OUTPUT = args.anonymize
    if ANONYMIZE_OUTPUT:
        print('Warning: All output keys are FAKE to protect your privacy')

    manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
    with open(manifest_file, 'rb') as infile:
        manifest_plist = biplist.readPlist(infile)
    keybag = Keybag(manifest_plist['BackupKeyBag'])
    # the actual keys are unknown, but the wrapped keys are known
    keybag.printClassKeys()

    if args.password_pipe:
        password = readpipe(args.password_pipe)
        if password.endswith(b'\n'):
            password = password[:-1]
    else:
        password = getpass.getpass('Backup password: ').encode('utf-8')

    ## Unlock keybag with password
    if not keybag.unlockWithPasscode(password):
        raise Exception('Could not unlock keybag; bad password?')
    # now the keys are known too
    keybag.printClassKeys()

    ## Decrypt metadata DB
    manifest_key = manifest_plist['ManifestKey'][4:]
    with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
        encrypted_db = db.read()

    manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
    key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
    decrypted_data = AESdecryptCBC(encrypted_db, key)

    temp_dir = tempfile.mkdtemp()
    try:
        # Does anyone know how to get Python’s SQLite module to open some
        # bytes in memory as a database?
        db_filename = os.path.join(temp_dir, 'db.sqlite3')
        with open(db_filename, 'wb') as db_file:
            db_file.write(decrypted_data)
        conn = sqlite3.connect(db_filename)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # c.execute("select * from Files limit 1");
        # r = c.fetchone()
        c.execute("""
            SELECT fileID, domain, relativePath, file
            FROM Files
            WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
            ORDER BY domain, relativePath""")
        results = c.fetchall()
    finally:
        shutil.rmtree(temp_dir)

    for item in results:
        fileID, domain, relativePath, file_bplist = item

        plist = biplist.readPlistFromString(file_bplist)
        file_data = plist['$objects'][plist['$top']['root'].integer]
        size = file_data['Size']

        protection_class = file_data['ProtectionClass']
        encryption_key = plist['$objects'][
            file_data['EncryptionKey'].integer]['NS.data'][4:]

        backup_filename = os.path.join(args.backup_directory,
                                    fileID[:2], fileID)
        with open(backup_filename, 'rb') as infile:
            data = infile.read()
            key = keybag.unwrapKeyForClass(protection_class, encryption_key)
            # truncate to actual length, as encryption may introduce padding
            decrypted_data = AESdecryptCBC(data, key)[:size]

        print('== decrypted data:')
        print(wrap(decrypted_data))
        print()

        print('== pretty-printed plist')
        pprint.pprint(biplist.readPlistFromString(decrypted_data))

##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/

CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"]  #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
    1:"NSFileProtectionComplete",
    2:"NSFileProtectionCompleteUnlessOpen",
    3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
    4:"NSFileProtectionNone",
    5:"NSFileProtectionRecovery?",

    6: "kSecAttrAccessibleWhenUnlocked",
    7: "kSecAttrAccessibleAfterFirstUnlock",
    8: "kSecAttrAccessibleAlways",
    9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
    10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
    11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2

class Keybag(object):
    def __init__(self, data):
        self.type = None
        self.uuid = None
        self.wrap = None
        self.deviceKey = None
        self.attrs = {}
        self.classKeys = {}
        self.KeyBagKeys = None #DATASIGN blob
        self.parseBinaryBlob(data)

    def parseBinaryBlob(self, data):
        currentClassKey = None

        for tag, data in loopTLVBlocks(data):
            if len(data) == 4:
                data = struct.unpack(">L", data)[0]
            if tag == b"TYPE":
                self.type = data
                if self.type > 3:
                    print("FAIL: keybag type > 3 : %d" % self.type)
            elif tag == b"UUID" and self.uuid is None:
                self.uuid = data
            elif tag == b"WRAP" and self.wrap is None:
                self.wrap = data
            elif tag == b"UUID":
                if currentClassKey:
                    self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
                currentClassKey = {b"UUID": data}
            elif tag in CLASSKEY_TAGS:
                currentClassKey[tag] = data
            else:
                self.attrs[tag] = data
        if currentClassKey:
            self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey

    def unlockWithPasscode(self, passcode):
        passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
                                        self.attrs[b"DPSL"],
                                        self.attrs[b"DPIC"], 32)
        passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
                                            self.attrs[b"SALT"],
                                            self.attrs[b"ITER"], 32)
        print('== Passcode key')
        print(anonymize(hexlify(passcode_key)))
        for classkey in self.classKeys.values():
            if b"WPKY" not in classkey:
                continue
            k = classkey[b"WPKY"]
            if classkey[b"WRAP"] & WRAP_PASSCODE:
                k = AESUnwrap(passcode_key, classkey[b"WPKY"])
                if not k:
                    return False
                classkey[b"KEY"] = k
        return True

    def unwrapKeyForClass(self, protection_class, persistent_key):
        ck = self.classKeys[protection_class][b"KEY"]
        if len(persistent_key) != 0x28:
            raise Exception("Invalid key length")
        return AESUnwrap(ck, persistent_key)

    def printClassKeys(self):
        print("== Keybag")
        print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
        print("Keybag version: %d" % self.attrs[b"VERS"])
        print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
        print("-"*209)
        print("".join(["Class".ljust(53),
                    "WRAP".ljust(5),
                    "Type".ljust(11),
                    "Key".ljust(65),
                    "WPKY".ljust(65),
                    "Public key"]))
        print("-"*208)
        for k, ck in self.classKeys.items():
            if k == 6:print("")

            print("".join(
                [PROTECTION_CLASSES.get(k).ljust(53),
                str(ck.get(b"WRAP","")).ljust(5),
                KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
                anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
                anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
            ]))
        print()

def loopTLVBlocks(blob):
    i = 0
    while i + 8 <= len(blob):
        tag = blob[i:i+4]
        length = struct.unpack(">L",blob[i+4:i+8])[0]
        data = blob[i+8:i+8+length]
        yield (tag,data)
        i += 8 + length

def unpack64bit(s):
    return struct.unpack(">Q",s)[0]
def pack64bit(s):
    return struct.pack(">Q",s)

def AESUnwrap(kek, wrapped):
    C = []
    for i in range(len(wrapped)//8):
        C.append(unpack64bit(wrapped[i*8:i*8+8]))
    n = len(C) - 1
    R = [0] * (n+1)
    A = C[0]

    for i in range(1,n+1):
        R[i] = C[i]

    for j in reversed(range(0,6)):
        for i in reversed(range(1,n+1)):
            todec = pack64bit(A ^ (n*j+i))
            todec += pack64bit(R[i])
            B = Crypto.Cipher.AES.new(kek).decrypt(todec)
            A = unpack64bit(B[:8])
            R[i] = unpack64bit(B[8:])

    if A != 0xa6a6a6a6a6a6a6a6:
        return None
    res = b"".join(map(pack64bit, R[1:]))
    return res

ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
    if len(data) % 16:
        print("AESdecryptCBC: data length not /16, truncating")
        data = data[0:(len(data)/16) * 16]
    data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
    if padding:
        return removePadding(16, data)
    return data

##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange

anon_random = random.Random(0)
memo = {}
def anonymize(s):
    if type(s) == str:
        s = s.encode('utf-8')
    global anon_random, memo
    if ANONYMIZE_OUTPUT:
        if s in memo:
            return memo[s]
        possible_alphabets = [
            string.digits,
            string.digits + 'abcdef',
            string.ascii_letters,
            "".join(chr(x) for x in range(0, 256)),
        ]
        for a in possible_alphabets:
            if all((chr(c) if type(c) == int else c) in a for c in s):
                alphabet = a
                break
        ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
        memo[s] = ret
        return ret
    else:
        return s

def wrap(s, width=78):
    "Return a width-wrapped repr(s)-like string without breaking on \’s"
    s = repr(s)
    quote = s[0]
    s = s[1:-1]
    ret = []
    while len(s):
        i = s.rfind('\\', 0, width)
        if i <= width - 4: # "\x??" is four characters
            i = width
        ret.append(s[:i])
        s = s[i:]
    return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)

def readpipe(path):
    if stat.S_ISFIFO(os.stat(path).st_mode):
        with open(path, 'rb') as pipe:
            return pipe.read()
    else:
        raise Exception("Not a pipe: {!r}".format(path))

if __name__ == '__main__':
    main()

Which then prints this output:

Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES                                                                         4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES                                                                         09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES                                                                         e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES                                                                         902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES                                                                         a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES                                                                         09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES                                                                         0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES                                                                         b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES                                                                         417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES                                                                         b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES                                                                         9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612

== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES        64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES        22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES        1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES        2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES        9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES        606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES        6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES        c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES        80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES        a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES        1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'

== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}

Extra credit

The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:

$ python iphone-dataprotection/python_scripts/keychain_tool.py ...

--------------------------------------------------------------------------------------
|                              Passwords                                             |
--------------------------------------------------------------------------------------
|Service           |Account          |Data           |Access group  |Protection class|
--------------------------------------------------------------------------------------
|AirPort           |Ed’s Coffee Shop |<3FrenchRoast  |apple         |AfterFirstUnlock|
...

That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.

What are file descriptors, explained in simple terms?

Any operating system has processes (p's) running, say p1, p2, p3 and so forth. Each process usually makes an ongoing usage of files.

Each process is consisted of a process tree (or a process table, in another phrasing).

Usually, Operating systems represent each file in each process by a number (that is to say, in each process tree/table).

The first file used in the process is file0, second is file1, third is file2, and so forth.

Any such number is a file descriptor.

File descriptors are usually integers (0, 1, 2 and not 0.5, 1.5, 2.5).

Given we often describe processes as "process-tables", and given that tables has rows (entries) we can say that the file descriptor cell in each entry, uses to represent the whole entry.

In a similar way, when you open a network socket, it has a socket descriptor.

In some operating systems, you can run out of file descriptors, but such case is extremely rare, and the average computer user shouldn't worry from that.

File descriptors might be global (process A starts in say 0, and ends say in 1 ; Process B starts say in 2, and ends say in 3) and so forth, but as far as I know, usually in modern operating systems, file descriptors are not global, and are actually process-specific (process A starts in say 0 and ends say in 5, while process B starts in 0 and ends say in 10).

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

Can a CSS class inherit one or more other classes?

While direct inheritance isn't possible.

It is possible to use a class (or id) for a parent tag and then use CSS combinators to alter child tag behaviour from it's heirarchy.

_x000D_
_x000D_
p.test{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
_x000D_
<p class="test"><span>One <span>possible <span>solution <span>is <span>using <span>multiple <span>nested <span>tags</span></span></span></span></span></span></span></span></p>
_x000D_
_x000D_
_x000D_

I wouldn't suggest using so many spans like the example, however it's just a proof of concept. There are still many bugs that can arise when trying to apply CSS in this manner. (For example altering text-decoration types).

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

Visualizing branch topology in Git

The most rated answers showing git log commands as favorite solutions.

If you need a tablelike, say column like output, you can use your awesome git log commands with slight modifications and some limitations with the .gitconfig alias.tably snippet below.

Modifications:

  • you have to use %><(<N>[,ltrunc|mtrunc|trunc]) before every commit placeholder
  • add a unique delimiter as column seperator
  • add --color option for colored output

Limitations:

  • you can place the git graph at every column as long as you do not use non-empty newlines %n...
  • the last commit placeholder of any newline can be used without %><(<N>[,trunc])
  • if extra characters are needed for decoration like (committer:, < and >) in

    ...%C(dim white)(committer: %cn% <%ce>)%C(reset)...

    to get a tablelike output they must be written directly before and after the commit placeholder

    ...%C(dim white)%<(25,trunc)(committer: %cn%<(25,trunc) <%ce>)%C(reset)...

  • if the --format=format: option is not the last one close it with %C(reset) as mostly done

  • compared to normal git log output this one is slow but nice

Example taken from this site:

thompson1     = log --all --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)'

will be with ^ as delimiter and without added characters

thompson1-new = log --all --graph --color --abbrev-commit --decorate --format=format:'^%C(bold blue)%<(7,trunc)%h%C(reset)^%C(bold green)%<(21,trunc)%ar%C(reset)^%C(white)%<(40,trunc)%s%C(reset)^%C(dim white)%<(25,trunc)%an%C(reset)^%C(auto)%d%C(reset)'

which compares like

enter image description here

enter image description here

or with moving graph to column 5

enter image description here

To achieve this add the following to your .gitconfig and call your log alias with git tably YourLogAlias

[color "decorate"]
    HEAD = bold blink italic 196
    branch = 214
    tag = bold 222

[alias]

    # delimiter used as column seperator
    delim = ^
    # example thompson1
    thompson1     = log --all --graph         --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)'
    # modified thompson1 example
    thompson1-new = log --all --graph --color --abbrev-commit --decorate --format=format:'^%C(bold blue)%<(7,trunc)%h%C(reset)^%C(bold green)%<(21,trunc)%ar%C(reset)^%C(white)%<(40,trunc)%s%C(reset)^%C(dim white)%<(25,trunc)%an%C(reset)^%C(auto)%d%C(reset)'
    # set a column for the graph
    thompson1-new-col = 1

tably     = !bash -c '"                                                                                                              \
              declare -A col_length;                                                                                                 \
              delim=$(git config alias.delim);                                                                                       \
              git_log_cmd=$(git config alias.$1);                                                                                    \
              git_tre_col=${2:-$(git config alias.$1-col)};                                                                          \
                                                                                                                                     \
              i=0;                                                                                                                   \
              n=0;                                                                                                                   \
              while IFS= read -r line; do                                                                                            \
                ((n++));                                                                                                             \
                while read -d\"$delim\" -r col_info;do                                                                               \
                  ((i++));                                                                                                           \
                  [[ -z \"$col_info\" ]] && col_length[\"$n:$i\"]=${col_length[\"${last[$i]:-1}:$i\"]} && ((i--)) && continue;       \
                  [[ $i -gt ${i_max:-0} ]] && i_max=$i;                                                                              \
                  col_length[\"$n:$i\"]=$(grep -Eo \"\\([0-9]*,[lm]*trunc\\)\" <<< \"$col_info\" | grep -Eo \"[0-9]*\" | head -n 1); \
                  [[ -n \"${col_length[\"$n:$i\"]}\" ]] && last[$i]=$n;                                                              \
                  chars_extra=$(grep -Eo \"\\trunc\\).*\" <<< \"$col_info\");                                                        \
                  chars_extra=${chars_extra#trunc)};                                                                                 \
                  chars_begin=${chars_extra%%\\%*};                                                                                  \
                  chars_extra=${chars_extra#*\\%};                                                                                   \
                  case \" ad aD ae aE ai aI al aL an aN ar as at b B cd cD ce cE ci cI cl cL cn cN cr                                \
                          cs ct d D e f G? gd gD ge gE GF GG GK gn gN GP gs GS GT h H N p P s S t T \" in                            \
                   *\" ${chars_extra:0:2} \"*)                                                                                       \
                     chars_extra=${chars_extra:2};                                                                                   \
                     chars_after=${chars_extra%%\\%*};                                                                               \
                     ;;                                                                                                              \
                   *\" ${chars_extra:0:1} \"*)                                                                                       \
                     chars_extra=${chars_extra:1};                                                                                   \
                     chars_after=${chars_extra%%\\%*};                                                                               \
                     ;;                                                                                                              \
                   *)                                                                                                                \
                     echo \"No Placeholder found. Probably no tablelike output.\";                                                   \
                     continue;                                                                                                       \
                     ;;                                                                                                              \
                  esac ;                                                                                                             \
                  if [[ -n \"$chars_begin$chars_after\" ]];then                                                                      \
                    len_extra=$(echo \"$chars_begin$chars_after\" | wc -m);                                                          \
                    col_length["$n:$i"]=$((${col_length["$n:$i"]}+$len_extra-1));                                                    \
                  fi;                                                                                                                \
                                                                                                                                     \
                done <<< \"${line#*=format:}$delim\";                                                                                \
                i=1;                                                                                                                 \
              done <<< \"$(echo -e \"${git_log_cmd//\\%n/\\\\n}\")\";                                                                \
                                                                                                                                     \
              while IFS= read -r graph;do                                                                                            \
                chars_count=$(sed -nl1000 \"l\" <<< \"$graph\" | grep -Eo \"\\\\\\\\\\\\\\\\|\\||\\/|\\ |\\*|_\" | wc -l);           \
                [[ ${chars_count:-0} -gt ${col_length["1:1"]:-0} ]] && col_length["1:1"]=$chars_count;                               \
              done < <([[ -n \"$(grep -F graph <<< \"$git_log_cmd\")\" ]] && git log --all --graph --pretty=format:\" \" && echo);   \
                                                                                                                                     \
              l=0;                                                                                                                   \
              while IFS= read -r line;do                                                                                             \
                c=0;                                                                                                                 \
                ((l++));                                                                                                             \
                [[ $l -gt $n ]] && l=1;                                                                                              \
                while IFS= read -d\"$delim\" -r col_content;do                                                                       \
                  ((c++));                                                                                                           \
                  if [[ $c -eq 1 ]];then                                                                                             \
                    [[ -n \"$(grep -F \"*\" <<< \"$col_content\")\" ]] || l=2;                                                       \
                    chars=$(sed -nl1000 \"l\" <<< \"$col_content\" | grep -Eo \"\\\\\\\\\\\\\\\\|\\||\\/|\\ |\\*|_\" | wc -l);       \
                    whitespaces=$((${col_length["1:1"]}-$chars));                                                                    \
                    whitespaces=$(seq -s\" \" $whitespaces|tr -d \"[:digit:]\");                                                     \
                    col_content[1]=\"${col_content[1]}$col_content$whitespaces\n\";                                                  \
                  else                                                                                                               \
                    col_content[$c]=\"${col_content[$c]}$(printf \"%-${col_length[\"$l:$c\"]}s\" \"${col_content:-\"\"}\")\n\";      \
                  fi;                                                                                                                \
                done <<< \"$line$delim\";                                                                                            \
                for ((k=$c+1;k<=$i_max;k++));do                                                                                      \
                  empty_content=\"$(printf \"%-${col_length[\"$l:$k\"]:-${col_length[\"${last[$k]:-1}:$k\"]:-0}}s\" \"\")\";         \
                  col_content[$k]=\"${col_content[$k]}$empty_content\n\";                                                            \
                done;                                                                                                                \
              done < <(git $1 && echo);                                                                                              \
                                                                                                                                     \
              while read col_num;do                                                                                                  \
                if [[ -z \"$cont_all\" ]];then                                                                                       \
                  cont_all=${col_content[$col_num]};                                                                                 \
                else                                                                                                                 \
                  cont_all=$(paste -d\" \" <(echo -e \"$cont_all\") <(echo -e \"${col_content[$col_num]}\"));                        \
                fi;                                                                                                                  \
              done <<< $(seq 2 1 ${git_tre_col:-1};seq 1;seq $((${git_tre_col:-1}+1)) 1 $i_max);                                     \
              echo -e \"$cont_all\";                                                                                                 \
              "' "git-tably"

This is more or less only a part of my answer https://stackoverflow.com/a/61487052/8006273 where you can find deeper explanations, but nicely fits to this question here too.

If there are problems with your git log commands leave a comment.

How can I display a modal dialog in Redux that performs asynchronous actions?

The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you'd like to see:

Dispatching an Action to Show the Modal

this.props.dispatch({
  type: 'SHOW_MODAL',
  modalType: 'DELETE_POST',
  modalProps: {
    postId: 42
  }
})

(Strings can be constants of course; I’m using inline strings for simplicity.)

Writing a Reducer to Manage Modal State

Then make sure you have a reducer that just accepts these values:

const initialState = {
  modalType: null,
  modalProps: {}
}

function modal(state = initialState, action) {
  switch (action.type) {
    case 'SHOW_MODAL':
      return {
        modalType: action.modalType,
        modalProps: action.modalProps
      }
    case 'HIDE_MODAL':
      return initialState
    default:
      return state
  }
}

/* .... */

const rootReducer = combineReducers({
  modal,
  /* other reducers */
})

Great! Now, when you dispatch an action, state.modal will update to include the information about the currently visible modal window.

Writing the Root Modal Component

At the root of your component hierarchy, add a <ModalRoot> component that is connected to the Redux store. It will listen to state.modal and display an appropriate modal component, forwarding the props from the state.modal.modalProps.

// These are regular React components we will write soon
import DeletePostModal from './DeletePostModal'
import ConfirmLogoutModal from './ConfirmLogoutModal'

const MODAL_COMPONENTS = {
  'DELETE_POST': DeletePostModal,
  'CONFIRM_LOGOUT': ConfirmLogoutModal,
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span /> // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)

What have we done here? ModalRoot reads the current modalType and modalProps from state.modal to which it is connected, and renders a corresponding component such as DeletePostModal or ConfirmLogoutModal. Every modal is a component!

Writing Specific Modal Components

There are no general rules here. They are just React components that can dispatch actions, read something from the store state, and just happen to be modals.

For example, DeletePostModal might look like:

import { deletePost, hideModal } from '../actions'

const DeletePostModal = ({ post, dispatch }) => (
  <div>
    <p>Delete post {post.name}?</p>
    <button onClick={() => {
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    }}>
      Yes
    </button>
    <button onClick={() => dispatch(hideModal())}>
      Nope
    </button>
  </div>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

The DeletePostModal is connected to the store so it can display the post title and works like any connected component: it can dispatch actions, including hideModal when it is necessary to hide itself.

Extracting a Presentational Component

It would be awkward to copy-paste the same layout logic for every “specific” modal. But you have components, right? So you can extract a presentational <Modal> component that doesn’t know what particular modals do, but handles how they look.

Then, specific modals such as DeletePostModal can use it for rendering:

import { deletePost, hideModal } from '../actions'
import Modal from './Modal'

const DeletePostModal = ({ post, dispatch }) => (
  <Modal
    dangerText={`Delete post ${post.name}?`}
    onDangerClick={() =>
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    })
  />
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

It is up to you to come up with a set of props that <Modal> can accept in your application but I would imagine that you might have several kinds of modals (e.g. info modal, confirmation modal, etc), and several styles for them.

Accessibility and Hiding on Click Outside or Escape Key

The last important part about modals is that generally we want to hide them when the user clicks outside or presses Escape.

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.

You can even wrap react-modal in your own <Modal> that accepts props specific to your applications and generates child buttons or other content. It’s all just components!

Other Approaches

There is more than one way to do it.

Some people don’t like the verbosity of this approach and prefer to have a <Modal> component that they can render right inside their components with a technique called “portals”. Portals let you render a component inside yours while actually it will render at a predetermined place in the DOM, which is very convenient for modals.

In fact react-modal I linked to earlier already does that internally so technically you don’t even need to render it from the top. I still find it nice to decouple the modal I want to show from the component showing it, but you can also use react-modal directly from your components, and skip most of what I wrote above.

I encourage you to consider both approaches, experiment with them, and pick what you find works best for your app and for your team.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

I created simple examples to clarify understanding of ManualResetEvent vs AutoResetEvent.

AutoResetEvent: lets assume you have 3 workers thread. If any of those threads will call WaitOne() all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne(). It is like; if I do not work, nobody works. In first example you can see that

autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();

When you call Set() all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set())

public class AutoResetEventSample
{
    private AutoResetEvent autoReset = new AutoResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        autoReset.Set();
        Thread.Sleep(1000);
        autoReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
}

In this example you can clearly see that when you first hit Set() it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne() inside, they will keep running because you have to manually call Reset() to stop them all.

manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();

It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()) then all players will wait until next signal.

public class ManualResetEventSample
{
    private ManualResetEvent manualReset = new ManualResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        manualReset.Set();
        Thread.Sleep(1000);
        manualReset.Reset();
        Console.WriteLine("Press to release all threads.");
        Console.ReadLine();
        manualReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
}

IIS 7, HttpHandler and HTTP Error 500.21

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

Can't PUT to my IHttpHandler, GET works fine

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

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

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

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

How to unit test abstract classes: extend with stubs?

I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.

As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

How do I copy a 2 Dimensional array in Java?

public  static byte[][] arrayCopy(byte[][] arr){
    if(arr!=null){
        int[][] arrCopy = new int[arr.length][] ;
        System.arraycopy(arr, 0, arrCopy, 0, arr.length);
        return arrCopy;
    }else { return new int[][]{};}
}

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07"), the Java SE Runtime Environment version ("build 1.6.0_07-b06"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"). I suspect the "11.0" you are seeing is the HotSpot version.

Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.

jQuery selector first td of each row

You should use :first-child instead of :first:

Sounds like you're wanting to iterate through them. You can do this using .each().

Example:

$('td:first-child').each(function() {
    console.log($(this).text());
});

Result:

nonono
nonono2
nonono3

Alernatively if you're not wanting to iterate:

$('td:first-child').css('background', '#000');

JSFiddle demo.

How to find the mysql data directory from command line in windows

public function variables($variable="")
{
  return empty($variable) ? mysql_query("SHOW VARIABLES") : mysql_query("SELECT @@$variable");
}

/*get datadir*/
$res = variables("datadir");

/*or get all variables*/
$res = variables();

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I know you had this problem in an internal host, but I had experienced such an issue before in an external host and in my case it had it's own resolution, maybe it could save somebody's time:

In fact my website was STOPPED by some reason which currently I'm not aware of, to check it out if you have the same problem, in WebsitePanel main page go to Web -> Websites then select the domain name of your website from the list, after that in the right side of the page just opened, check if you see the word STARTED, else if you see the word STOPPED, make it get started again. That's all.

How to upgrade scikit-learn package in anaconda

Updating a Specific Library - scikit-learn:

Anaconda (conda):

conda install scikit-learn

Pip Installs Packages (pip):

pip install --upgrade scikit-learn

Verify Update:

conda list scikit-learn

It should now display the current (and desired) version of the scikit-learn library.

For me personally, I tried using the conda command to update the scikit-learn library and it acted as if it were installing the latest version to then later discover (with an execution of the conda list scikit-learn command) that it was the same version as previously and never updated (or recognized the update?). When I used the pip command, it worked like a charm and correctly updated the scikit-learn library to the latest version!

Hope this helps!

More in-depth details of latest version can be found here (be mindful this applies to the scikit-learn library version of 0.22):

Reset git proxy to default configuration

Remove both http and https setting by using commands.

git config --global --unset http.proxy

git config --global --unset https.proxy

How do you move a file?

Cut file via operating system context menu as you usually do, then instead of doing regular paste, right click to bring context menu, then choose TortoiseSVN -> Paste (make sure you commit from root to include both old and new files in the commit).

Cannot change version of project facet Dynamic Web Module to 3.0?

I had the same symptom with a different cure. I was trying to upgrade my JSF 2.2.4/Spring 3.0 webapp to JSF 2.3 in order to enjoy the new JSF websocket hooks there and Eclipse (actually STS) would not cooperate. In Eclipse's Project Facets, JSF 2.3 never became available until I edited directly the org.eclipse.wst.common.project.facet.core.xml file as directed in previous answers - the highest it would go was 2.2.

Here are the hoops I jumped through. I don't know that all of these were necessary because I fundamentally don't understand all this configuration.

In Eclipse I frequently got a scary warning, "Modifying a faceted project when implementations of one or more installed facets are not available can potentially result in a corrupted project. Are you sure you want to proceed?" This prompted me to do more frequent commits but no corruption occurred.

  1. Upgrade JDK from 1.7 to 1.8 in POM, Eclipse compiler, and Eclipse Project Facets.
  2. Update the following Maven dependencies:

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
        <scope>provided</scope>
    </dependency>
    

    ... to:

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.0</version>
        <scope>provided</scope>
    </dependency>
    

... and ...

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.4</version>
    </dependency>

... to:

    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>javax.faces-api</artifactId>
        <version>2.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0</version>
    </dependency>

I had to update my web.xml namespace declarations from:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

... to:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

I had to update Project Facets -> Dynamic Web Module from 2.5 to 3.0. I tried 3.1 but got errors.

In this process I frequently got the error in the title of this post, "Cannot change version of project facet Dynamic Web Module to 3.0" and Eclipse refused to compile the project or offer JSF 2.3 in the Project Facets. When I edited the org.eclipse.wst.common.project.facet.core.xml file as directed the errors disappeared, Eclipse offered JSF 2.3 in Project Facets, and the project compiled and ran fine on Tomcat 9.0.8. However, Project Facets still warned "Implementation of version 2.3 of project facet jst.jsf could not be found. Functionality will be limited." I suspect this simply means that autocomplete and other Eclipse conveniences will not be available because it cannot find the JSF 2.3 implementation declared in my POM.

Hope this helps someone. Google searches yielded only this post by Ali Bassam and indirectly BalusC which helped.

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

Add centered text to the middle of a <hr/>-like line

I use a h1 with a span in the middle.

HTML Example:

<h1><span>Test archief</span></h1>

CSS Example:

.archive h1 {border-top:3px dotted #AAAAAA;}
.archive h1 span { display:block; background:#fff; width:200px; margin:-23px auto; text-align:center }

Simple as that.

How can I include a YAML file inside another?

The YML standard does not specify a way to do this. And this problem does not limit itself to YML. JSON has the same limitations.

Many applications which use YML or JSON based configurations run into this problem eventually. And when that happens, they make up their own convention.

e.g. for swagger API definitions:

$ref: 'file.yml'

e.g. for docker compose configurations:

services:
  app:
    extends:
      file: docker-compose.base.yml

Alternatively, if you want to split up the content of a yml file in multiple files, like a tree of content, you can define your own folder-structure convention and use an (existing) merge script.

Switching a DIV background image with jQuery

I personally would just use the JavaScript code to switch between 2 classes.

Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).

CSS with different images

.div {
    /* button size etc properties */
}

.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}

Or CSS with image sprite

.div {
    background: url(img/sprite.gif) no-repeat left top;
    /* Other styles */
}

.expanded {background-position: left bottom;}

Then...

JavaScript code with images

$(function){
    $('#button').click(function(){
        if($(this).hasClass('expanded'))
        {
            $(this).addClass('collapsed').removeClass('expanded');
        }
        else
        {
            $(this).addClass('expanded').removeClass('collapsed');
        }
    });
}

JavaScript with sprite

Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass/removeClass method will work fine in this situation as well

The most elegant solution (unfortunately not Internet Explorer 6 friendly)

$(function){
        $('#button').click(function(){
            $(this).toggleClass('expanded');
        });
    }

$(function){
        $('#button').click(function(){
            if($(this).hasClass('expanded'))
            {
                $(this).removeClass('expanded');
            }
            else
            {
                $(this).addClass('expanded');
            }
        });
    }

As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.

Aborting a shell script if any command returns a non-zero value

To add to the accepted answer:

Bear in mind that set -e sometimes is not enough, specially if you have pipes.

For example, suppose you have this script

#!/bin/bash
set -e 
./configure  > configure.log
make

... which works as expected: an error in configure aborts the execution.

Tomorrow you make a seemingly trivial change:

#!/bin/bash
set -e 
./configure  | tee configure.log
make

... and now it does not work. This is explained here, and a workaround (Bash only) is provided:

#!/bin/bash
set -e 
set -o pipefail

./configure  | tee configure.log
make

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Manually Triggering Form Validation using jQuery

I seem to find the trick: Just remove the form target attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me:

<form>
  <input name="foo" required>
  <button id="submit">Submit</button>
</form>

<script>
$('#submit').click( function(e){
  var isValid = true;
  $('form input').map(function() {
    isValid &= this.validity['valid'] ;
  }) ;
  if (isValid) {
    console.log('valid!');
    // post something..
  } else
    console.log('not valid!');
});
</script>

CSS3 selector to find the 2nd div of the same class

UPDATE: This answer was originally written in 2008 when nth-of-type support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2), unless you have to support IE8 and older.


Original answer from 2008 follows (Note that I would not recommend this anymore!):

If you can use Prototype JS you can use this code to set some style values, or add another classname:

// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });
// OR add class name:
$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...

(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)

But if you're generating the html serverside you might just as well add an extra class on the second item...

How to parse JSON in Java

Please do something like this:

JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");

Create an empty data.frame

You could use read.table with an empty string for the input text as follows:

colClasses = c("Date", "character", "character")
col.names = c("Date", "File", "User")

df <- read.table(text = "",
                 colClasses = colClasses,
                 col.names = col.names)

Alternatively specifying the col.names as a string:

df <- read.csv(text="Date,File,User", colClasses = colClasses)

Thanks to Richard Scriven for the improvement

Do you get charged for a 'stopped' instance on EC2?

This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.

If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.

If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.

HttpContext.Current.Session is null when routing requests

Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

Simply adding it won't work since "Session" should have already been defined in the machine.config.

Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

Maven Install on Mac OS X

OS X prior to Mavericks (10.9) actually comes with Maven 3 built in.

If you're on OS X Lion, you won't have java installed by default. Run java by itself and it'll prompt you to install it.

Assuming qualifications are met, run mvn -version and see some output like this:

Apache Maven 3.0.3 (r1075438; 2011-02-28 12:31:09-0500)
Maven home: /usr/share/maven
Java version: 1.6.0_29, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.7.2", arch: "x86_64", family: "mac"

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

How to convert POJO to JSON and vice versa?

You can use jackson api for the conversion

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.4</version>
</dependency>

add above maven dependency in your POM, In your main method create ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

later we nee to add our POJO class to the mapper

String json = mapper.writeValueAsString(pojo);

How to create multiple output paths in Webpack config

I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.

//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
    this.cacheable && this.cacheable();
    if(!this.emitFile) throw new Error("emitFile is required from module system");
    var query = loaderUtils.parseQuery(this.query);
    var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
        context: query.context || this.options.context,
        content: content,
        regExp: query.regExp
    });
    this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
    return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;

Why does foo = filter(...) return a <filter object>, not a list?

the reason why it returns < filter object > is that, filter is class instead of built-in function.

help(filter) you will get following: Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

Preventing form resubmission

Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:

Prevent Back button from showing POST confirmation alert

Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.

Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.

Inserting Data into Hive Table

You may try this, I have developed a tool to generate hive scripts from a csv file. Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory

  1. Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/

  2. Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop

    #!/bin/bash -v
    hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv hive -f ./AllstarFull.hive

    hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv hive -f ./Appearances.hive

    hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv hive -f ./AwardsManagers.hive

  3. Sample of generated Hive scripts

    CREATE DATABASE IF NOT EXISTS lahman;
    USE lahman;
    CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
    LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
    SELECT * FROM AllstarFull;

Thanks Vijay

How to suppress "unused parameter" warnings in C?

I've seen this style being used:

if (when || who || format || data || len);

Add a CSS class to <%= f.submit %>

Rails 4 and Bootstrap 3 "primary" button

<%= f.submit nil, :class => 'btn btn-primary' %>

Yields something like:

screen-2014-01-22_02.24.26.png

Getting a link to go to a specific section on another page

To link from a page to another section of the page, I navigate through the page depending on the page's location to the other, at the URL bar, and add the #id. So what I mean;

<a href = "../#the_part_that_you_want">This takes you #the_part_that_you_want at the page before</a>

How to check for an empty struct?

Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:

session := &Session{}
if (Session{}) == *session {
    fmt.Println("session is empty")
}

Check this playground.

Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...

What's the difference between ".equals" and "=="?

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

How to clean node_modules folder of packages that are not in package.json?

You could remove your node_modules/ folder and then reinstall the dependencies from package.json.

rm -rf node_modules/
npm install

This would erase all installed packages in the current folder and only install the dependencies from package.json. If the dependencies have been previously installed npm will try to use the cached version, avoiding downloading the dependency a second time.

Ways to eliminate switch in code

Switch statements can often be replaced by a good OO design.

For example, you have an Account class, and are using a switch statement to perform a different calculation based on the type of account.

I would suggest that this should be replaced by a number of account classes, representing the different types of account, and all implementing an Account interface.

The switch then becomes unnecessary, as you can treat all types of accounts the same and thanks to polymorphism, the appropriate calculation will be run for the account type.

C++ pass an array by reference

Arrays can only be passed by reference, actually:

void foo(double (&bar)[10])
{
}

This prevents you from doing things like:

double arr[20];
foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>
void foo(T (&bar)[N])
{
    // use N here
}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.

Android: java.lang.SecurityException: Permission Denial: start Intent

My problem was that I had this: wrong Instead of this: correct

Converting char[] to byte[]

Edit: Andrey's answer has been updated so the following no longer applies.

Andrey's answer (the highest voted at the time of writing) is slightly incorrect. I would have added this as comment but I am not reputable enough.

In Andrey's answer:

char[] chars = {'c', 'h', 'a', 'r', 's'}
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();

the call to array() may not return the desired value, for example:

char[] c = "aaaaaaaaaa".toCharArray();
System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));

output:

[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]

As can be seen a zero byte has been added. To avoid this use the following:

char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));

output:

[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]

As the answer also alluded to using passwords it might be worth blanking out the array that backs the ByteBuffer (accessed via the array() function):

ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
blankOutByteArray(bb.array());
System.out.println(Arrays.toString(b));

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

The error is because you are including the script links at two places which will do the override and re-initialization of date-picker

_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />_x000D_
_x000D_
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
    $('.dateinput').datepicker({ format: "yyyy/mm/dd" });_x000D_
}); _x000D_
</script>_x000D_
_x000D_
      <!-- Bootstrap core JavaScript_x000D_
================================================== -->_x000D_
<!-- Placed at the end of the document so the pages load faster -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"

or src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"

It will work..

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

What is the difference between a Docker image and a container?

As many answers pointed this out: You build Dockerfile to get an image and you run image to get a container.

However, following steps helped me get a better feel for what Docker image and container are:

1) Build Dockerfile:

docker build -t my_image dir_with_dockerfile

2) Save the image to .tar file

docker save -o my_file.tar my_image_id

my_file.tar will store the image. Open it with tar -xvf my_file.tar, and you will get to see all the layers. If you dive deeper into each layer you can see what changes were added in each layer. (They should be pretty close to commands in the Dockerfile).

3) To take a look inside of a container, you can do:

sudo docker run -it my_image bash

and you can see that is very much like an OS.