Programs & Examples On #Mprotect

Initialize empty vector in structure - c++

How about

user r = {"",{}};

or

user r = {"",{'\0'}};

or

user r = {"",std::vector<unsigned char>()};

or

user r;

How to change color in markdown cells ipython/jupyter notebook?

Similarly to Jakob's answer, you can use HTML tags. Just a note that the color attribute of font (<font color=...>) is deprecated in HTML5. The following syntax would be HTML5-compliant:

This <span style="color:red">word</span> is not black.

Same caution that Jakob made probably still applies:

Be aware that this will not survive a conversion of the notebook to latex.

Regular expression for floating point numbers

I don't think that any of the answers on this page at the time of writing are correct (also many other suggestions elsewhere on SO are wrong too). The complication is that you have to match all of the following possibilities:

  • No decimal point (i.e. an integer value)
  • Digits both before and after the decimal point (e.g. 0.35 , 22.165)
  • Digits before the decimal point only (e.g. 0. , 1234.)
  • Digits after the decimal point only (e.g. .0 , .5678)

At the same time, you must ensure that there is at least one digit somewhere, i.e. the following are not allowed:

  • a decimal point on its own
  • a signed decimal point with no digits (i.e. +. or -.)
  • + or - on their own
  • an empty string

This seems tricky at first, but one way of finding inspiration is to look at the OpenJDK source for the java.lang.Double.valueOf(String) method (start at http://hg.openjdk.java.net/jdk8/jdk8/jdk, click "browse", navigate down /src/share/classes/java/lang/ and find the Double class). The long regex that this class contains caters for various possibilities that the OP probably didn't have in mind, but ignoring for simplicity the parts of it that deal with NaN, infinity, Hexadecimal notation and exponents, and using \d rather than the POSIX notation for a single digit, I can reduce the important parts of the regex for a signed floating point number with no exponent to:

[+-]?((\d+\.?\d*)|(\.\d+))

I don't think that there is a way of avoiding the (...)|(...) construction without allowing something that contains no digits, or forbidding one of the possibilities that has no digits before the decimal point or no digits after it.

Obviously in practice you will need to cater for trailing or preceding whitespace, either in the regex itself or in the code that uses it.

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

Getting raw SQL query string from PDO prepared statements

I know this question is a bit old, but, I'm using this code since lot time ago (I've used response from @chris-go), and now, these code are obsolete with PHP 7.2

I'll post an updated version of these code (Credit for the main code are from @bigwebguy, @mike and @chris-go, all of them answers of this question):

/**
 * Replaces any parameter placeholders in a query with the value of that
 * parameter. Useful for debugging. Assumes anonymous parameters from 
 * $params are are in the same order as specified in $query
 *
 * @param string $query The sql query with parameter placeholders
 * @param array $params The array of substitution parameters
 * @return string The interpolated query
 */
public function interpolateQuery($query, $params) {
    $keys = array();
    $values = $params;

    # build a regular expression for each parameter
    foreach ($params as $key => $value) {
        if (is_string($key)) {
            $keys[] = '/:'.$key.'/';
        } else {
            $keys[] = '/[?]/';
        }

        if (is_array($value))
            $values[$key] = implode(',', $value);

        if (is_null($value))
            $values[$key] = 'NULL';
    }
    // Walk the array to see if we can add single-quotes to strings
    array_walk($values, function(&$v, $k) { if (!is_numeric($v) && $v != "NULL") $v = "\'" . $v . "\'"; });

    $query = preg_replace($keys, $values, $query, 1, $count);

    return $query;
}

Note the change on the code are on array_walk() function, replacing create_function by an anonymous function. This make these good piece of code functional and compatible with PHP 7.2 (and hope future versions too).

Parsing JSON from XmlHttpRequest.responseJSON

You can simply set xhr.responseType = 'json';

_x000D_
_x000D_
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
  if (this.status == 200) {_x000D_
    console.log('response', this.response); // JSON response  _x000D_
  }_x000D_
};_x000D_
xhr.send();_x000D_
  
_x000D_
_x000D_
_x000D_

Documentation for responseType

How to add headers to a multicolumn listbox in an Excel userform using VBA

You can give this a try. I am quite new to the forum but wanted to offer something that worked for me since I've gotten so much help from this site in the past. This is essentially a variation of the above, but I found it simpler.

Just paste this into the Userform_Initialize section of your userform code. Note you must already have a listbox on the userform or have it created dynamically above this code. Also please note the Array is a list of headings (below as "Header1", "Header2" etc. Replace these with your own headings. This code will then set up a heading bar at the top based on the column widths of the list box. Sorry it doesn't scroll - it's fixed labels.

More senior coders - please feel free to comment or improve this.

    Dim Mywidths As String
    Dim Arrwidths, Arrheaders As Variant
    Dim ColCounter, Labelleft As Long
    Dim theLabel As Object                

    [Other code here that you would already have in the Userform_Initialize section]

    Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
            With theLabel
                    .Left = ListBox1.Left
                    .Top = ListBox1.Top - 10
                    .Width = ListBox1.Width - 1
                    .Height = 10
                    .BackColor = RGB(200, 200, 200)
            End With
            Arrheaders = Array("Header1", "Header2", "Header3", "Header4")

            Mywidths = Me.ListBox1.ColumnWidths
            Mywidths = Replace(Mywidths, " pt", "")
            Arrwidths = Split(Mywidths, ";")
            Labelleft = ListBox1.Left + 18
            For ColCounter = LBound(Arrwidths) To UBound(Arrwidths)
                        If Arrwidths(ColCounter) > 0 Then
                                Header = Header + 1
                                Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)

                                With theLabel
                                    .Caption = Arrheaders(Header - 1)
                                    .Left = Labelleft
                                    .Width = Arrwidths(ColCounter)
                                    .Height = 10
                                    .Top = ListBox1.Top - 10
                                    .BackColor = RGB(200, 200, 200)
                                    .Font.Bold = True
                                End With
                                 Labelleft = Labelleft + Arrwidths(ColCounter)

                        End If
             Next

What does "The APR based Apache Tomcat Native library was not found" mean?

Unless you're running a production server, don't worry about this message. This is a library which is used to improve performance (on production systems). From Apache Portable Runtime (APR) based Native library for Tomcat:

Tomcat can use the Apache Portable Runtime to provide superior scalability, performance, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).

Show percent % instead of counts in charts of categorical variables

Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".

df <- data.frame(V1 = rnorm(100))

ggplot(df, aes(x = V1)) +  
  geom_histogram(aes(y = 100*(..count..)/sum(..count..))) 

# if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
# different category. In this case this does not make sense, as the variable is 
# really continuous. With the hp variable of the mtcars (see previous answer), it 
# worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
# can want to see each value of this variable, and not to group it in bins.
ggplot(df, aes(x = factor(V1))) +  
  geom_bar(aes(y = (..count..)/sum(..count..))) 

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

jQuery UI Dialog individual CSS styling

I created custom styles by just overriding jQuery classes in inline style. So on top of the page, you have the jQuery CSS linked and right after that override the classes you need to modify:

<head>
    <link href="/Content/theme/base/jquery.ui.all.css" rel="stylesheet"/>

    <style type="text/css">
        .ui-dialog .ui-dialog-content
        {
            position: relative;
            border: 0;
            padding: .5em 1em;
            background: none;
            overflow: auto;
            zoom: 1;
            background-color: #ffd;
            border: solid 1px #ea7;
        }

        .ui-dialog .ui-dialog-titlebar
        {
            display:none;
        }

        .ui-widget-content
        {
            border:none;
        }
    </style>
</head>

Check if all checkboxes are selected

Alternatively, you could have also used every():

// Cache DOM Lookup
var abc = $(".abc");

// On Click
abc.on("click",function(){

    // Check if all items in list are selected
    if(abc.toArray().every(areSelected)){
        //do something
    }

    function areSelected(element, index, array){
        return array[index].checked;
    }
});

What is the difference between String and StringBuffer in Java?

A String is immutable, i.e. when it's created, it can never change.

A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.

The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays only have an int for their length pseudo-field.

The performance improvement between Strings and StringBuffers for multiple concatenation is quite significant. If you run the following test code, you will see the difference. On my ancient laptop with Java 6, I get these results:

Concat with String took: 1781ms
Concat with StringBuffer took: 0ms
public class Concat
{
    public static String concatWithString()
    {
        String t = "Cat";
        for (int i=0; i<10000; i++)
        {
            t = t + "Dog";
        }
        return t;
    }
    public static String concatWithStringBuffer()
    {
        StringBuffer sb = new StringBuffer("Cat");
        for (int i=0; i<10000; i++)
        {
            sb.append("Dog");
        }
        return sb.toString();
    }
    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        concatWithString();
        System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
        start = System.currentTimeMillis();
        concatWithStringBuffer();
        System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
    }
}

How can I right-align text in a DataGridView column?

I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

In this case e is from:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

Why doesn't C++ have a garbage collector?

To add to the debate here.

There are known issues with garbage collection, and understanding them helps understanding why there is none in C++.

1. Performance ?

The first complaint is often about performance, but most people don't really realize what they are talking about. As illustrated by Martin Beckett the problem may not be performance per se, but the predictability of performance.

There are currently 2 families of GC that are widely deployed:

  • Mark-And-Sweep kind
  • Reference-Counting kind

The Mark And Sweep is faster (less impact on overall performance) but it suffers from a "freeze the world" syndrome: i.e. when the GC kicks in, everything else is stopped until the GC has made its cleanup. If you wish to build a server that answers in a few milliseconds... some transactions will not live up to your expectations :)

The problem of Reference Counting is different: reference-counting adds overhead, especially in Multi-Threading environments because you need to have an atomic count. Furthermore there is the problem of reference cycles so you need a clever algorithm to detect those cycles and eliminate them (generally implement by a "freeze the world" too, though less frequent). In general, as of today, this kind (even though normally more responsive or rather, freezing less often) is slower than the Mark And Sweep.

I have seen a paper by Eiffel implementers that were trying to implement a Reference Counting Garbage Collector that would have a similar global performance to Mark And Sweep without the "Freeze The World" aspect. It required a separate thread for the GC (typical). The algorithm was a bit frightening (at the end) but the paper made a good job of introducing the concepts one at a time and showing the evolution of the algorithm from the "simple" version to the full-fledged one. Recommended reading if only I could put my hands back on the PDF file...

2. Resources Acquisition Is Initialization (RAII)

It's a common idiom in C++ that you will wrap the ownership of resources within an object to ensure that they are properly released. It's mostly used for memory since we don't have garbage collection, but it's also useful nonetheless for many other situations:

  • locks (multi-thread, file handle, ...)
  • connections (to a database, another server, ...)

The idea is to properly control the lifetime of the object:

  • it should be alive as long as you need it
  • it should be killed when you're done with it

The problem of GC is that if it helps with the former and ultimately guarantees that later... this "ultimate" may not be sufficient. If you release a lock, you'd really like that it be released now, so that it does not block any further calls!

Languages with GC have two work arounds:

  • don't use GC when stack allocation is sufficient: it's normally for performance issues, but in our case it really helps since the scope defines the lifetime
  • using construct... but it's explicit (weak) RAII while in C++ RAII is implicit so that the user CANNOT unwittingly make the error (by omitting the using keyword)

3. Smart Pointers

Smart pointers often appear as a silver bullet to handle memory in C++. Often times I have heard: we don't need GC after all, since we have smart pointers.

One could not be more wrong.

Smart pointers do help: auto_ptr and unique_ptr use RAII concepts, extremely useful indeed. They are so simple that you can write them by yourself quite easily.

When one need to share ownership however it gets more difficult: you might share among multiple threads and there are a few subtle issues with the handling of the count. Therefore, one naturally goes toward shared_ptr.

It's great, that's what Boost for after all, but it's not a silver bullet. In fact, the main issue with shared_ptr is that it emulates a GC implemented by Reference Counting but you need to implement the cycle detection all by yourself... Urg

Of course there is this weak_ptr thingy, but I have unfortunately already seen memory leaks despite the use of shared_ptr because of those cycles... and when you are in a Multi Threaded environment, it's extremely difficult to detect!

4. What's the solution ?

There is no silver bullet, but as always, it's definitely feasible. In the absence of GC one need to be clear on ownership:

  • prefer having a single owner at one given time, if possible
  • if not, make sure that your class diagram does not have any cycle pertaining to ownership and break them with subtle application of weak_ptr

So indeed, it would be great to have a GC... however it's no trivial issue. And in the mean time, we just need to roll up our sleeves.

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

Add Whatsapp function to website, like sms, tel

below link will open the whatsapp. Here "0123456789" is the contact of the person you want to communicate with.

href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">

Is there a method that calculates a factorial in Java?

i believe this would be the fastest way, by a lookup table:

private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
    final long[] factorialTable = new long[21];
    factorialTable[0] = 1;
    for (int i=1; i<factorialTable.length; i++)
        factorialTable[i] = factorialTable[i-1] * i;
    return factorialTable;
}
/**
 * Actually, even for {@code long}, it works only until 20 inclusively.
 */
public static long factorial(final int n) {
    if ((n < 0) || (n > 20))
        throw new OutOfRangeException("n", 0, 20);
    return FACTORIAL_TABLE[n];
}

For the native type long (8 bytes), it can only hold up to 20!

20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000

Obviously, 21! will cause overflow.

Therefore, for native type long, only a maximum of 20! is allowed, meaningful, and correct.

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

Output in a table format in Java's System.out

Using j-text-utils you may print to console a table like: enter image description here

And it as simple as:

TextTable tt = new TextTable(columnNames, data);                                                         
tt.printTable();   

The API also allows sorting and row numbering ...

How to get the sign, mantissa and exponent of a floating point number

  1. Don't make functions that do multiple things.
  2. Don't mask then shift; shift then mask.
  3. Don't mutate values unnecessarily because it's slow, cache-destroying and error-prone.
  4. Don't use magic numbers.
/* NaNs, infinities, denormals unhandled */
/* assumes sizeof(float) == 4 and uses ieee754 binary32 format */
/* assumes two's-complement machine */
/* C99 */
#include <stdint.h>

#define SIGN(f) (((f) <= -0.0) ? 1 : 0)

#define AS_U32(f) (*(const uint32_t*)&(f))
#define FLOAT_EXPONENT_WIDTH 8
#define FLOAT_MANTISSA_WIDTH 23
#define FLOAT_BIAS ((1<<(FLOAT_EXPONENT_WIDTH-1))-1) /* 2^(e-1)-1 */
#define MASK(width)  ((1<<(width))-1) /* 2^w - 1 */
#define FLOAT_IMPLICIT_MANTISSA_BIT (1<<FLOAT_MANTISSA_WIDTH)

/* correct exponent with bias removed */
int float_exponent(float f) {
  return (int)((AS_U32(f) >> FLOAT_MANTISSA_WIDTH) & MASK(FLOAT_EXPONENT_WIDTH)) - FLOAT_BIAS;
}

/* of non-zero, normal floats only */
int float_mantissa(float f) {
  return (int)(AS_U32(f) & MASK(FLOAT_MANTISSA_BITS)) | FLOAT_IMPLICIT_MANTISSA_BIT;
}

/* Hacker's Delight book is your friend. */

Adding form action in html in laravel

if you want to call controller from form action that time used following code:

<form action="{{ action('SchoolController@getSchool') }}"  >

Here SchoolController is a controller name and getSchool is a method name, you must use get or post before method name which should be same as in form tag.

do <something> N times (declarative syntax)

Possible ES6 alternative.

Array.from(Array(3)).forEach((x, i) => {
  something();
});

And, if you want it "to be called 1,2 and 3 times respectively".

Array.from(Array(3)).forEach((x, i) => {
  Array.from(Array(i+1)).forEach((x, i2) => {
    console.log(`Something ${ i } ${ i2 }`)
  });
});

Update:

Taken from filling-arrays-with-undefined

This seems to be a more optimised way of creating the initial array, I've also updated this to use the second parameter map function suggested by @felix-eve.

Array.from({ length: 3 }, (x, i) => {
  something();
});

If input value is blank, assign a value of "empty" with Javascript

You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":

<form name="my_form" action="validate.php" onsubmit="check()">
    <input type="text" name="text1" />
    <input type="submit" value="submit" />
</form>

and in your js:

function check() {
    if(document.forms["my_form"]["text1"].value == "")
        document.forms["my_form"]["text1"].value = "empty";
}

How do I grant myself admin access to a local SQL Server instance?

Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.

SQL Server: Query fast, but slow from procedure

Have you tried rebuilding the statistics and/or the indexes on the Report_Opener table. All the recomplies of the SP won't be worth anything if the stats still show data from when the database was first inauguarated.

The initial query itself works quickly because the optimiser can see that the parameter will never be null. In the case of the SP the optimiser cannot be sure that the parameter will never be null.

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

Get query string parameters url values with jQuery / Javascript (querystring)

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

How do I count columns of a table

I have a more general answer; but I believe it is useful for counting the columns for all tables in a DB:

SELECT table_name, count(*)
FROM information_schema.columns
GROUP BY table_name;

Using OpenSSL what does "unable to write 'random state'" mean?

The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.

How to check if an integer is within a range?

There is no builtin function, but you can easily achieve it by calling the functions min() and max() appropriately.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

From the experiment branch

git rebase master
git push -f origin <experiment-branch>

This creates a common commit history to be able to compare both branches.

What is the correct way of reading from a TCP socket in C/C++?

For any non-trivial application (I.E. the application must receive and handle different kinds of messages with different lengths), the solution to your particular problem isn't necessarily just a programming solution - it's a convention, I.E. a protocol.

In order to determine how many bytes you should pass to your read call, you should establish a common prefix, or header, that your application receives. That way, when a socket first has reads available, you can make decisions about what to expect.

A binary example might look like this:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

enum MessageType {
    MESSAGE_FOO,
    MESSAGE_BAR,
};

struct MessageHeader {
    uint32_t type;
    uint32_t length;
};

/**
 * Attempts to continue reading a `socket` until `bytes` number
 * of bytes are read. Returns truthy on success, falsy on failure.
 *
 * Similar to @grieve's ReadXBytes.
 */
int readExpected(int socket, void *destination, size_t bytes)
{
    /*
    * Can't increment a void pointer, as incrementing
    * is done by the width of the pointed-to type -
    * and void doesn't have a width
    *
    * You can in GCC but it's not very portable
    */
    char *destinationBytes = destination;
    while (bytes) {
        ssize_t readBytes = read(socket, destinationBytes, bytes);
        if (readBytes < 1)
            return 0;
        destinationBytes += readBytes;
        bytes -= readBytes;
    }
    return 1;
}

int main(int argc, char **argv)
{
    int selectedFd;

    // use `select` or `poll` to wait on sockets
    // received a message on `selectedFd`, start reading

    char *fooMessage;
    struct {
        uint32_t a;
        uint32_t b;
    } barMessage;

    struct MessageHeader received;
    if (!readExpected (selectedFd, &received, sizeof(received))) {
        // handle error
    }
    // handle network/host byte order differences maybe
    received.type = ntohl(received.type);
    received.length = ntohl(received.length);

    switch (received.type) {
        case MESSAGE_FOO:
            // "foo" sends an ASCII string or something
            fooMessage = calloc(received.length + 1, 1);
            if (readExpected (selectedFd, fooMessage, received.length))
                puts(fooMessage);
            free(fooMessage);
            break;
        case MESSAGE_BAR:
            // "bar" sends a message of a fixed size
            if (readExpected (selectedFd, &barMessage, sizeof(barMessage))) {
                barMessage.a = ntohl(barMessage.a);
                barMessage.b = ntohl(barMessage.b);
                printf("a + b = %d\n", barMessage.a + barMessage.b);
            }
            break;
        default:
            puts("Malformed type received");
            // kick the client out probably
    }
}

You can likely already see one disadvantage of using a binary format - for each attribute greater than a char you read, you will have to ensure its byte order is correct using the ntohl or ntohs functions.

An alternative is to use byte-encoded messages, such as simple ASCII or UTF-8 strings, which avoid byte-order issues entirely but require extra effort to parse and validate.

There are two final considerations for network data in C.

The first is that some C types do not have fixed widths. For example, the humble int is defined as the word size of the processor, so 32 bit processors will produce 32 bit ints, while 64 bit processors will produces 64 bit ints. Good, portable code should have network data use fixed-width types, like those defined in stdint.h.

The second is struct padding. A struct with different-widthed members will add data in between some members to maintain memory alignment, making the struct faster to use in the program but sometimes producing confusing results.

#include <stdio.h>
#include <stdint.h>

int main()
{
    struct A {
        char a;
        uint32_t b;
    } A;

    printf("sizeof(A): %ld\n", sizeof(A));
}

In this example, its actual width won't be 1 char + 4 uint32_t = 5 bytes, it'll be 8:

mharrison@mharrison-KATANA:~$ gcc -o padding padding.c
mharrison@mharrison-KATANA:~$ ./padding 
sizeof(A): 8

This is because 3 bytes are added after char a to make sure uint32_t b is memory-aligned.

So if you write a struct A, then attempt to read a char and a uint32_t on the other side, you'll get char a, and a uint32_t where the first three bytes are garbage and the last byte is the first byte of the actual integer you wrote.

Either document your data format explicitly as C struct types or, better yet, document any padding bytes they might contain.

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

Changing background color of text box input not working when empty

Don't add styles to value of input so use like

function checkFilled() {
    var inputElem = document.getElementById("subEmail");
    if (inputElem.value == "") {
        inputElem.style.backgroundColor = "yellow";
                }
        }

How to remove leading and trailing spaces from a string

I really don't understand some of the hoops the other answers are jumping through.

var myString = "    this    is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";

It's not rocket science.

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

_x000D_
_x000D_
var temp = "This is a string.";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

And, if there are no matches, it returns 0:

_x000D_
_x000D_
var temp = "Hello World!";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

Default value in Doctrine

Adding to @romanb brilliant answer.

This adds a little overhead in migration, because you obviously cannot create a field with not null constraint and with no default value.

// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

//lets add property without not null contraint        
$this->addSql("ALTER TABLE tablename ADD property BOOLEAN");

//get the default value for property       
$object = new Object();
$defaultValue = $menuItem->getProperty() ? "true":"false";

$this->addSql("UPDATE tablename SET property = {$defaultValue}");

//not you can add constraint
$this->addSql("ALTER TABLE tablename ALTER property SET NOT NULL");

With this answer, I encourage you to think why do you need the default value in the database in the first place? And usually it is to allow creating objects with not null constraint.

How to modify a global variable within a function in bash?

Maybe you can use a file, write to file inside function, read from file after it. I have changed e to an array. In this example blanks are used as separator when reading back the array.

#!/bin/bash

declare -a e
e[0]="first"
e[1]="secondddd"

function test1 () {
 e[2]="third"
 e[1]="second"
 echo "${e[@]}" > /tmp/tempout
 echo hi
}

ret=$(test1)

echo "$ret"

read -r -a e < /tmp/tempout
echo "${e[@]}"
echo "${e[0]}"
echo "${e[1]}"
echo "${e[2]}"

Output:

hi
first second third
first
second
third

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

How to get the IP address of the docker host from inside a docker container

As of version 18.03, you can use host.docker.internal as the host's IP.

Works in Docker for Mac, Docker for Windows, and perhaps other platforms as well.

This is an update from the Mac-specific docker.for.mac.localhost, available since version 17.06, and docker.for.mac.host.internal, available since version 17.12, which may also still work on that platform.

Note, as in the Mac and Windows documentation, this is for development purposes only.

For example, I have environment variables set on my host:

MONGO_SERVER=host.docker.internal

In my docker-compose.yml file, I have this:

version: '3'

services:
  api:
    build: ./api
    volumes:
      - ./api:/usr/src/app:ro
    ports:
      - "8000"
    environment:
      - MONGO_SERVER
    command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi

How to delete or add column in SQLITE?

This answer to a different question is oriented toward modifying a column, but I believe a portion of the answer could also yield a useful approach if you have lots of columns and don't want to retype most of them by hand for your INSERT statement:

https://stackoverflow.com/a/10385666

You could dump your database as described in the link above, then grab the "create table" statement and an "insert" template from that dump, then follow the instructions in the SQLite FAQ entry "How do I add or delete columns from an existing table in SQLite." (FAQ is linked elsewhere on this page.)

Android basics: running code in the UI thread

If you need to use in Fragment you should use

private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }


    ((MainActivity)context).runOnUiThread(new Runnable() {
        public void run() {
            Log.d("UI thread", "I am the UI thread");
        }
    });

instead of

getActivity().runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

Because There will be null pointer exception in some situation like pager fragment

How to check version of a CocoaPods framework

The highest voted answer (MishieMoo) is correct but it doesn't explain how to open Podfile.lock. Everytime I tried I kept getting:

enter image description here

You open it in terminal by going to the folder it's in and running:

vim Podfile.lock

I got the answer from here: how to open Podfile.lock

You close it by pressing the colon and typing quit or by pressing the colon and the letter q then enter

:quit // then return key
:q // then return key

Another way is in terminal, you can also cd to the folder that your Xcode project is in and enter

$ open Podfile.lock -a Xcode

Doing it the second way, after it opens just press the red X button in the upper left hand corner to close.

C++ Array Of Pointers

If you don't use the STL, then the code looks a lot bit like C.

#include <cstdlib>
#include <new>

template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
    T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
    if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
       // assign things now that there is no exception
    arr = tmp;
    new( &arr[ n ] ) T( obj ); // placement new
    ++ n;
}

T can be any POD type, including pointers.

Note that arr must be allocated by malloc, not new[].

Initializing multiple variables to the same value in Java

You can declare multiple variables, and initialize multiple variables, but not both at the same time:

 String one,two,three;
 one = two = three = "";

However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".

How to display Wordpress search results?

Check whether your template in theme folder contains search.php and searchform.php or not.

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

What's the best way to check if a file exists in C?

Yes. Use stat(). See the man page forstat(2).

stat() will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).

Oh, as someone else mentioned, you can also use access(). However I prefer stat(), as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).

Implement an input with a mask

Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);

function applyDataMask(field) {
    var mask = field.dataset.mask.split('');

    // For now, this just strips everything that's not a number
    function stripMask(maskedData) {
        function isDigit(char) {
            return /\d/.test(char);
        }
        return maskedData.split('').filter(isDigit);
    }

    // Replace `_` characters with characters from `data`
    function applyMask(data) {
        return mask.map(function(char) {
            if (char != '_') return char;
            if (data.length == 0) return char;
            return data.shift();
        }).join('')
    }

    function reapplyMask(data) {
        return applyMask(stripMask(data));
    }

    function changed() {   
        var oldStart = field.selectionStart;
        var oldEnd = field.selectionEnd;

        field.value = reapplyMask(field.value);

        field.selectionStart = oldStart;
        field.selectionEnd = oldEnd;
    }

    field.addEventListener('click', changed)
    field.addEventListener('keyup', changed)
}
Date: <input type="text" value="__-__-____" data-mask="__-__-____"/><br/>
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>

Performance of FOR vs FOREACH in PHP

I think but I am not sure : the for loop takes two operations for checking and incrementing values. foreach loads the data in memory then it will iterate every values.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In your home directory, you should edit .bash_profile if you have Git for Windows 2.21.0 or later (as of this writing).

You could direct .bash_profile to just source .bashrc, but if something happens to your .bash_profile, then it will be unclear why your .bashrc is again not working.

I put all my aliases and other environment stuff in .bash_profile, and I also added this line:

echo "Sourcing ~/.bash_profile - this version of Git Bash doesn't use .bashrc"

And THEN, in .bashrc I have

echo "This version of Git Bash doesn't use .bashrc. Use .bash_profile instead"

(Building on @harsel's response. I woulda commented, but I have no points yet.)

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

How to format DateTime columns in DataGridView?

You can set the format you want:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn

Truncate all tables in a MySQL database in one command?

I found it most simple to just do something like the code below, just replace the table names with your own. important make sure the last line is always SET FOREIGN_KEY_CHECKS=1;

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `table1`;
TRUNCATE `table2`;
TRUNCATE `table3`;
TRUNCATE `table4`;
TRUNCATE `table5`;
TRUNCATE `table6`;
TRUNCATE `table7`;
SET FOREIGN_KEY_CHECKS=1;

Cannot resolve symbol 'AppCompatActivity'

After upgrading to the latest support library, I had to upgrade to the latest Android studio (beta) version and gradle version before the IDE recognized AppCompatActivity again (invalidating caches and restart did not do the trick)

How can I check that JButton is pressed? If the isEnable() is not work?

Seems you need to use JToggleButton :

JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        JToggleButton btn =  (JToggleButton) e.getSource();
        btn.setText(btn.isSelected() ? "pushed" : "push me");
    }
});

EF Migrations: Rollback last applied migration?

As of EF 5.0, the approach you describe is the preferred way. So

PM> Update-Database -TargetMigration:"NameOfSecondToLastMigration"

or using your example migrations

PM> Update-Database -TargetMigration:"CategoryIdIsLong"

One solution would be to create a wrapper PS script that automates the steps above. Additionally, feel free to create a feature request for this, or better yet, take a shot at implementing it! https://github.com/dotnet/ef6

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

How does MySQL process ORDER BY and LIMIT in a query?

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

All details on: http://dev.mysql.com/doc/refman/5.0/en/select.html

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

Escape quotes in JavaScript

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

Get all child elements

Yes, you can achieve it by find_elements_by_css_selector("*") or find_elements_by_xpath(".//*").

However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")

header = driver.find_element_by_id("header")

# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")

print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

None of the previous post solve my issue. Here is what's happening with me:
I normally load the app from android studio by clicking on the "Run" button. When you do this, android would create an app that's good for debug but not for install. If you try to install using:

adb install -r yourapk

you will get a message that says:

Failure [INSTALL_FAILED_TEST_ONLY]

When this happens, you will need to rebuilt the apk by first clean the build, then select Build->Build APK. See the image bellow:

build android apk

This APK is ready to be installed either through adb install command or any other methods

Hope this helps

David

Quickest way to compare two generic lists for differences

using System.Collections.Generic;
using System.Linq;

namespace YourProject.Extensions
{
    public static class ListExtensions
    {
        public static bool SetwiseEquivalentTo<T>(this List<T> list, List<T> other)
            where T: IEquatable<T>
        {
            if (list.Except(other).Any())
                return false;
            if (other.Except(list).Any())
                return false;
            return true;
        }
    }
}

Sometimes you only need to know if two lists are different, and not what those differences are. In that case, consider adding this extension method to your project. Note that your listed objects should implement IEquatable!

Usage:

public sealed class Car : IEquatable<Car>
{
    public Price Price { get; }
    public List<Component> Components { get; }

    ...
    public override bool Equals(object obj)
        => obj is Car other && Equals(other);

    public bool Equals(Car other)
        => Price == other.Price
            && Components.SetwiseEquivalentTo(other.Components);

    public override int GetHashCode()
        => Components.Aggregate(
            Price.GetHashCode(),
            (code, next) => code ^ next.GetHashCode()); // Bitwise XOR
}

Whatever the Component class is, the methods shown here for Car should be implemented almost identically.

It's very important to note how we've written GetHashCode. In order to properly implement IEquatable, Equals and GetHashCode must operate on the instance's properties in a logically compatible way.

Two lists with the same contents are still different objects, and will produce different hash codes. Since we want these two lists to be treated as equal, we must let GetHashCode produce the same value for each of them. We can accomplish this by delegating the hashcode to every element in the list, and using the standard bitwise XOR to combine them all. XOR is order-agnostic, so it doesn't matter if the lists are sorted differently. It only matters that they contain nothing but equivalent members.

Note: the strange name is to imply the fact that the method does not consider the order of the elements in the list. If you do care about the order of the elements in the list, this method is not for you!

Error during installing HAXM, VT-X not working

BIOS -> Overclockong -> CPU Features -> Intel Virtualization Tech -> Enabled

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

Writing your own square root function

In general the square root of an integer (like 2, for example) can only be approximated (not because of problems with floating point arithmetic, but because they're irrational numbers which can't be calculated exactly).

Of course, some approximations are better than others. I mean, of course, that the value 1.732 is a better approximation to the square root of 3, than 1.7

The method used by the code at that link you gave works by taking a first approximation and using it to calculate a better approximation.

This is called Newton's Method, and you can repeat the calculation with each new approximation until it's accurate enough for you.

In fact there must be some way to decide when to stop the repetition or it will run forever.

Usually you would stop when the difference between approximations is less than a value you decide.

EDIT: I don't think there can be a simpler implementation than the two you already found.

Get parent of current directory from Python script

from os.path import dirname
from os.path import abspath

def get_file_parent_dir_path():
    """return the path of the parent directory of current file's directory """
    current_dir_path = dirname(abspath(__file__))
    path_sep = os.path.sep
    components = current_dir_path.split(path_sep)
    return path_sep.join(components[:-1])

Export table from database to csv file

Dead horse perhaps, but a while back I was trying to do the same and came across a script to create a STP that tried to do what I was looking for, but it had a few quirks that needed some attention. In an attempt to track down where I found the script to post an update, I came across this thread and it seemed like a good spot to share it.

This STP (Which for the most part I take no credit for, and I can't find the site I found it on), takes a schema name, table name, and Y or N [to include or exclude headers] as input parameters and queries the supplied table, outputting each row in comma-separated, quoted, csv format.

I've made numerous fixes/changes to the original script, but the bones of it are from the OP, whoever that was.

Here is the script:

IF OBJECT_ID('get_csvFormat', 'P') IS NOT NULL
    DROP PROCEDURE get_csvFormat
GO

CREATE PROCEDURE get_csvFormat(@schemaname VARCHAR(20), @tablename VARCHAR(30),@header char(1))
AS
BEGIN
    IF ISNULL(@tablename, '') = ''
    BEGIN
        PRINT('NO TABLE NAME SUPPLIED, UNABLE TO CONTINUE')
        RETURN
    END
    ELSE
    BEGIN
        DECLARE @cols VARCHAR(MAX), @sqlstrs VARCHAR(MAX), @heading VARCHAR(MAX), @schemaid int

        --if no schemaname provided, default to dbo
        IF ISNULL(@schemaname, '') = ''
            SELECT @schemaname = 'dbo'

        --if no header provided, default to Y
        IF ISNULL(@header, '') = ''
            SELECT @header = 'Y'

        SELECT @schemaid = (SELECT schema_id FROM sys.schemas WHERE [name] = @schemaname)
        SELECT 
        @cols = (
            SELECT ' , CAST([', b.name + '] AS VARCHAR(50)) '  
            FROM sys.objects a 
            INNER JOIN sys.columns b ON a.object_id=b.object_id 
            WHERE a.name = @tablename AND a.schema_id = @schemaid
            FOR XML PATH('')
        ),
        @heading = (
            SELECT ',"' + b.name + '"' FROM sys.objects a 
            INNER JOIN sys.columns b ON a.object_id=b.object_id 
            WHERE a.name= @tablename AND a.schema_id = @schemaid
            FOR XML PATH('')
        )

        SET @tablename = @schemaname + '.' + @tablename
        SET @heading =  'SELECT ''' + right(@heading,len(@heading)-1) + ''' AS CSV, 0 AS Sort'  + CHAR(13)
        SET @cols =  '''"'',' + replace(right(@cols,len(@cols)-1),',', ',''","'',') + ',''"''' + CHAR(13)

        IF @header = 'Y'
            SET @sqlstrs =  'SELECT CSV FROM (' + CHAR(13) + @heading + ' UNION SELECT CONCAT(' + @cols + ') CSV, 1 AS Sort FROM ' + @tablename + CHAR(13) + ') X ORDER BY Sort, CSV ASC'
        ELSE
            SET @sqlstrs =  'SELECT CONCAT(' + @cols + ') CSV FROM ' + @tablename 

        IF @schemaid IS NOT NULL 
            EXEC(@sqlstrs)
        ELSE 
            PRINT('SCHEMA DOES NOT EXIST')
    END
END

GO

--------------------------------------

--EXEC get_csvFormat @schemaname='dbo', @tablename='TradeUnion', @header='Y'

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

_csv.Error: field larger than field limit (131072)

The csv file might contain very huge fields, therefore increase the field_size_limit:

import sys
import csv

csv.field_size_limit(sys.maxsize)

sys.maxsize works for Python 2.x and 3.x. sys.maxint would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)

Update

As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long. To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):

import sys
import csv
maxInt = sys.maxsize

while True:
    # decrease the maxInt value by factor 10 
    # as long as the OverflowError occurs.

    try:
        csv.field_size_limit(maxInt)
        break
    except OverflowError:
        maxInt = int(maxInt/10)

typecast string to integer - Postgres

If the value contains non-numeric characters, you can convert the value to an integer as follows:

SELECT CASE WHEN <column>~E'^\\d+$' THEN CAST (<column> AS INTEGER) ELSE 0 END FROM table;

The CASE operator checks the < column>, if it matches the integer pattern, it converts the rate into an integer, otherwise it returns 0

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Convert generic List/Enumerable to DataTable?

A 2019 answer if you're using .NET Core - use the Nuget ToDataTable library. Advantages:

Disclaimer - I'm the author of ToDataTable

Performance - I span up some Benchmark .Net tests and included them in the ToDataTable repo. The results were as follows:

Creating a 100,000 Row Datatable:

                           MacOS         Windows
Reflection                 818.5 ms      818.3 ms
FastMember from           1105.5 ms      976.4 ms
 Mark's answer
Improved FastMember        524.6 ms      456.4 ms
ToDataTable                449.0 ms      376.5 ms

The FastMember method suggested in Marc's answer seemed to perform worse than Mary's answer which used reflection, but I rolled another method using a FastMember TypeAccessor and it performed much better. Nevertheless the ToDataTable package outperformed the lot.

ArrayList - How to modify a member of an object?

Without function here it is...it works fine with listArrays filled with Objects

example `

al.add(new Student(101,"Jack",23,'C'));//adding Student class object  
      al.add(new Student(102,"Evan",21,'A'));  
      al.add(new Student(103,"Berton",25,'B'));  
      al.add(0, new Student(104,"Brian",20,'D'));
      al.add(0, new Student(105,"Lance",24,'D'));
      for(int i = 101; i< 101+al.size(); i++) {  
              al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
          }

Java equivalent to C# extension methods

You can create a C# like extension/helper method by (RE) implementing the Collections interface and adding- example for Java Collection:

public class RockCollection<T extends Comparable<T>> implements Collection<T> {
private Collection<T> _list = new ArrayList<T>();

//###########Custom extension methods###########

public T doSomething() {
    //do some stuff
    return _list  
}

//proper examples
public T find(Predicate<T> predicate) {
    return _list.stream()
            .filter(predicate)
            .findFirst()
            .get();
}

public List<T> findAll(Predicate<T> predicate) {
    return _list.stream()
            .filter(predicate)
            .collect(Collectors.<T>toList());
}

public String join(String joiner) {
    StringBuilder aggregate = new StringBuilder("");
    _list.forEach( item ->
        aggregate.append(item.toString() + joiner)
    );
    return aggregate.toString().substring(0, aggregate.length() - 1);
}

public List<T> reverse() {
    List<T> listToReverse = (List<T>)_list;
    Collections.reverse(listToReverse);
    return listToReverse;
}

public List<T> sort(Comparator<T> sortComparer) {
    List<T> listToReverse = (List<T>)_list;
    Collections.sort(listToReverse, sortComparer);
    return listToReverse;
}

public int sum() {
    List<T> list = (List<T>)_list;
    int total = 0;
    for (T aList : list) {
        total += Integer.parseInt(aList.toString());
    }
    return total;
}

public List<T> minus(RockCollection<T> listToMinus) {
    List<T> list = (List<T>)_list;
    int total = 0;
    listToMinus.forEach(list::remove);
    return list;
}

public Double average() {
    List<T> list = (List<T>)_list;
    Double total = 0.0;
    for (T aList : list) {
        total += Double.parseDouble(aList.toString());
    }
    return total / list.size();
}

public T first() {
    return _list.stream().findFirst().get();
            //.collect(Collectors.<T>toList());
}
public T last() {
    List<T> list = (List<T>)_list;
    return list.get(_list.size() - 1);
}
//##############################################
//Re-implement existing methods
@Override
public int size() {
    return _list.size();
}

@Override
public boolean isEmpty() {
    return _list == null || _list.size() == 0;
}

PHP AES encrypt / decrypt

Please use an existing secure PHP encryption library

It's generally a bad idea to write your own cryptography unless you have experience breaking other peoples' cryptography implementations.

None of the examples here authenticate the ciphertext, which leaves them vulnerable to bit-rewriting attacks.

If you can install PECL extensions, libsodium is even better

<?php
// PECL libsodium 0.2.1 and newer

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    return base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    return \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
}    

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

This can be used in any situation where you are passing data to the client (e.g. encrypted cookies for sessions without server-side storage, encrypted URL parameters, etc.) with a reasonably high degree of certainty that the end user cannot decipher or reliably tamper with it.

Since libsodium is cross-platform, this also makes it easier to communicate with PHP from, e.g. Java applets or native mobile apps.


Note: If you specifically need to add encrypted cookies powered by libsodium to your app, my employer Paragon Initiative Enterprises is developing a library called Halite that does all of this for you.

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

In MySQL, how to copy the content of one table to another table within the same database?

If you want to create and copy the content in a single shot, just use the SELECT:

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

Controlling a USB power supply (on/off) with Linux

USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.

In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

New functionality in the framework and support libs allow exactly this. There are three 'pieces of the puzzle':

  1. Using Toolbar so that you can embed your action bar into your view hierarchy.
  2. Making DrawerLayout fitsSystemWindows so that it is layed out behind the system bars.
  3. Disabling Theme.Material's normal status bar coloring so that DrawerLayout can draw there instead.

I'll assume that you will use the new appcompat.

First, your layout should look like this:

<!-- The important thing to note here is the added fitSystemWindows -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Your normal content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- We use a Toolbar so that our drawer can be displayed
             in front of the action bar -->
        <android.support.v7.widget.Toolbar  
            android:id="@+id/my_awesome_toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

        <!-- The rest of your content view -->

    </LinearLayout>

    <!-- Your drawer view. This can be any view, LinearLayout
         is just an example. As we have set fitSystemWindows=true
         this will be displayed under the status bar. -->
    <LinearLayout
        android:layout_width="304dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:fitsSystemWindows="true">

        <!-- Your drawer content -->

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

Then in your Activity/Fragment:

public void onCreate(Bundled savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Your normal setup. Blah blah ...

    // As we're using a Toolbar, we should retrieve it and set it
    // to be our ActionBar
    Toolbar toolbar = (...) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);

    // Now retrieve the DrawerLayout so that we can set the status bar color.
    // This only takes effect on Lollipop, or when using translucentStatusBar
    // on KitKat.
    DrawerLayout drawerLayout = (...) findViewById(R.id.my_drawer_layout);
    drawerLayout.setStatusBarBackgroundColor(yourChosenColor);
}

Then you need to make sure that the DrawerLayout is visible behind the status bar. You do that by changing your values-v21 theme:

values-v21/themes.xml

<style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>

Note: If a <fragment android:name="fragments.NavigationDrawerFragment"> is used instead of

<LinearLayout
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true">

    <!-- Your drawer content -->

</LinearLayout>

the actual layout, the desired effect will be achieved if you call fitsSystemWindows(boolean) on a view that you return from onCreateView method.

@Override
public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View mDrawerListView = inflater.inflate(
        R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setFitsSystemWindows(true);
    return mDrawerListView;
}

Adding a new value to an existing ENUM Type

For those looking for an in-transaction solution, the following seems to work.

Instead of an ENUM, a DOMAIN shall be used on type TEXT with a constraint checking that the value is within the specified list of allowed values (as suggested by some comments). The only problem is that no constraint can be added (and thus neither modified) to a domain if it is used by any composite type (the docs merely says this "should eventually be improved"). Such a restriction may be worked around, however, using a constraint calling a function, as follows.

START TRANSACTION;

CREATE FUNCTION test_is_allowed_label(lbl TEXT) RETURNS BOOL AS $function$
    SELECT lbl IN ('one', 'two', 'three');
$function$ LANGUAGE SQL IMMUTABLE;

CREATE DOMAIN test_domain AS TEXT CONSTRAINT val_check CHECK (test_is_allowed_label(value));

CREATE TYPE test_composite AS (num INT, word test_domain);

CREATE TABLE test_table (val test_composite);
INSERT INTO test_table (val) VALUES ((1, 'one')::test_composite), ((3, 'three')::test_composite);
-- INSERT INTO test_table (val) VALUES ((4, 'four')::test_composite); -- restricted by the CHECK constraint

CREATE VIEW test_view AS SELECT * FROM test_table; -- just to show that the views using the type work as expected

CREATE OR REPLACE FUNCTION test_is_allowed_label(lbl TEXT) RETURNS BOOL AS $function$
    SELECT lbl IN ('one', 'two', 'three', 'four');
$function$ LANGUAGE SQL IMMUTABLE;

INSERT INTO test_table (val) VALUES ((4, 'four')::test_composite); -- allowed by the new effective definition of the constraint

SELECT * FROM test_view;

CREATE OR REPLACE FUNCTION test_is_allowed_label(lbl TEXT) RETURNS BOOL AS $function$
    SELECT lbl IN ('one', 'two', 'three');
$function$ LANGUAGE SQL IMMUTABLE;

-- INSERT INTO test_table (val) VALUES ((4, 'four')::test_composite); -- restricted by the CHECK constraint, again

SELECT * FROM test_view; -- note the view lists the restricted value 'four' as no checks are made on existing data

DROP VIEW test_view;
DROP TABLE test_table;
DROP TYPE test_composite;
DROP DOMAIN test_domain;
DROP FUNCTION test_is_allowed_label(TEXT);

COMMIT;

Previously, I used a solution similar to the accepted answer, but it is far from being good once views or functions or composite types (and especially views using other views using the modified ENUMs...) are considered. The solution proposed in this answer seems to work under any conditions.

The only disadvantage is that no checks are performed on existing data when some allowed values are removed (which might be acceptable, especially for this question). (A call to ALTER DOMAIN test_domain VALIDATE CONSTRAINT val_check ends up with the same error as adding a new constraint to the domain used by a composite type, unfortunately.)

Note that a slight modification such as CHECK (value = ANY(get_allowed_values())), where get_allowed_values() function returned the list of allowed values, would not work - which is quite strange, so I hope the solution proposed above works reliably (it does for me, so far...). (it works, actually - it was my error)

Selecting an element in iFrame jQuery

when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:

$(function() {
    $("#my-iframe").bind("load",function(){
        $(this).contents().find("[tokenid=" + token + "]").html();
    });
});

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

reset your mysql password on xampp security page. restart your mysql service and then access the phpmyadmin page using your password. i tried it. this is working fine for me.

Is it possible to send a variable number of arguments to a JavaScript function?

You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

var otherFunc = function() {
   alert(arguments.length); // Outputs: 10
}

var myFunc = function() {
  alert(arguments.length); // Outputs: 10
  otherFunc.apply(this, arguments);
}
myFunc(1,2,3,4,5,6,7,8,9,10);

How to write some data to excel file(.xlsx)

It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb. Using OleDb, it behaves as if you were writing to a table using sql.

Here is the code I used to create and write to an new excel file. No extra references are needed

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

How to make an ng-click event conditional?

I use the && expression which works perfectly for me.

For example,

<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>

If vm.slideOneValid is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.

Just remember to add ng-model to the element to make ng-disabled work.

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

Border around each cell in a range

xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid

Syntax for if/else condition in SCSS mixin

You could try this:

$width:auto;
@mixin clearfix($width) {

   @if $width == 'auto' {

    // if width is not passed, or empty do this

   } @else {
        display: inline-block;
        width: $width;
   }
}

I'm not sure of your intended result, but setting a default value should return false.

How to Set Opacity (Alpha) for View in Android

For a view you can set opacity by the following.

view_name.setAlpha(float_value);

The property view.setAlpha(int) is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f) is used.

JSON - Iterate through JSONArray

You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

How can I use iptables on centos 7?

I had the problem that rebooting wouldn't start iptables.

This fixed it:

yum install iptables-services
systemctl mask firewalld
systemctl enable iptables
systemctl enable ip6tables
systemctl stop firewalld
systemctl start iptables
systemctl start ip6tables

How do I use Notepad++ (or other) with msysgit?

Update 2010-2011:

zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.

As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config again.
But that is just me.


Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.


Original answer.

The following:

C:\prog\git>git config --global core.editor C:/prog/git/npp.sh

C:/prog/git/npp.sh:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh script.
(As Franky comments: "Remember to save your .sh file with Unix style line endings or receive mysterious error messages!")

More details on the SO question How can I set up an editor to work with Git on Windows?

Note the '-multiInst' option, for ensuring a new instance of notepad++ for each call from Git.

Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:

git is passing it a cygwin path and npp doesn't know what to do with it

So the script in that case would be:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"

Multiple lines for readability:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
  -nosession -noPlugin "$(cygpath -w "$*")"

With "$(cygpath -w "$*")" being the important part here.

Val commented (and then deleted) that you should not use -notabbar option:

It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since -notab becomes the default setting and you must Settings>Preferences>General>TabBar> Hide>uncheck every time you start notepad after rebase. This is hell. You recommended the hell.

So use rather:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"

That is:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
  -noPlugin "$(cygpath -w "$*")"

If you want to place the script 'npp.sh' in a path with spaces (as in 'c:\program files\...',), you have three options:

  • Either try to quote the path (single or double quotes), as in:

    git config --global core.editor 'C:/program files/git/npp.sh'
    
  • or try the shortname notation (not fool-proofed):

    git config --global core.editor C:/progra~1/git/npp.sh
    
  • or (my favorite) place 'npp.sh' in a directory part of your %PATH% environment variable. You would not have then to specify any path for the script.

    git config --global core.editor npp.sh
    
  • Steiny reports in the comments having to do:

    git config --global core.editor '"C:/Program Files (x86)/Git/scripts/npp.sh"'
    

React - How to get parameter value from query string?

React Router v4

Using component

<Route path="/users/:id" component={UserPage}/> 
this.props.match.params.id

The component is automatically rendered with the route props.


Using render

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
this.props.match.params.id

Route props are passed to the render function.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

How to keep a Python script output window open?

The simplest way:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

this will leave the code up for 1 minute then close it.

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])

Or, to sum over rows:

>>> a.sum(axis=1)
array([ 3, 12, 21, 30])

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

Remove title in Toolbar in appcompat-v7

toolbar.setTitle(null);// remove the title

How to pass values across the pages in ASP.net without using Session

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]

load scripts asynchronously

Several notes:

  • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)
  • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!

Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):

(function() {
    var prot = ("https:"===document.location.protocol?"https://":"http://");

    var scripts = [
        "path/to/first.js",
        "path/to/second.js",
        "path/to/third.js"
    ];

    function completed() { console.log('completed'); }  // FIXME: remove logs

    function checkStateAndCall(path, callback) {
        var _success = false;
        return function() {
            if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                _success = true;
                console.log(path, 'is ready'); // FIXME: remove logs
                callback();
            }
        };
    }

    function asyncLoadScripts(files) {
        function loadNext() { // chain element
            if (!files.length) completed();
            var path = files.shift();
            var scriptElm = document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = true;
            scriptElm.src = prot+path;
            scriptElm.onload = scriptElm.onreadystatechange = \
                checkStateAndCall(path, loadNext); // load next file in chain when
                                                   // this one will be ready 
            var headElm = document.head || document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
        loadNext(); // start a chain
    }

    asyncLoadScripts(scripts);
})();

How to prevent Right Click option using jquery

$(document).mousedown(function(e) {
    if( e.button == 2 ) {
         e.preventDefault();
        return false;
    } 
});

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

Getting values from query string in an url using AngularJS $location

First make the URL format correct for getting the query string use #?q=string that works for me

http://localhost/codeschool/index.php#?foo=abcd

Inject $location service into the controller

app.controller('MyController', [ '$location', function($location) { 

    var searchObject = $location.search();

    // $location.search(); reutrn object 
    // searchObject = { foo = 'abcd' };

    alert( searchObject.foo );

} ]);

So the out put should be abcd

Python, Pandas : write content of DataFrame into text File

Late to the party: Try this>

base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
    df.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

I ran into this issue when I use djangocms and added a plugin (in my case: djangocms-cascade). Of course I had to add the plugin to the INSTALLED_APPS. But the order is here important.

To place 'cmsplugin_cascade' before 'cms' solved the issue.

Failed to resolve version for org.apache.maven.archetypes

I simple use below steps:

Create Maven project -> check checkobox -> "Create a simple project (skip archetype selection)"

It works for me

How to place two forms on the same page?

Give the submit buttons for both forms different names and use PHP to check which button has submitted data.

Form one button - btn1 Form two button -btn2

PHP Code:

if($_POST['btn1']){
    //Login
}elseif($_POST['btn2']){
    //Register
}

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

How do I use floating-point division in bash?

** Injection-safe floating point math in bash/shell **

Note: The focus of this answer is provide ideas for injection-safe solution to performing math in bash (or other shells). Of course, same can be used, with minor adjustment to perform advanced string processing, etc.

Most of the solution that were by presented, construct small scriptlet on the fly, using external data (variables, files, command line, environment variables). The external input can be used to inject malicious code into the engine, many of them

Below is a comparison on using the various language to perform basic math calculation, where the result in floating point. It calculates A + B * 0.1 (as floating point).

All solution attempt avoid creating dynamic scriptlets, which are extremely hard to maintain, Instead they use static program, and pass parameters into designated variable. They will safely handle parameters with special characters - reducing the possibility of code injection. The exception is 'BC' which does not provide input/output facility

The exception is 'bc', which does not provide any input/output, all the data comes via programs in stdin, and all output goes to stdout. All calculation are executing in a sandbox, which does not allow side effect (opening files, etc.). In theory, injection safe by design!

A=5.2
B=4.3

# Awk: Map variable into awk
# Exit 0 (or just exit) for success, non-zero for error.
#
awk -v A="$A" -v B="$B" 'BEGIN { print A + B * 0.1 ; exit 0}'

# Perl
perl -e '($A,$B) = @ARGV ; print $A + $B * 0.1' "$A" "$B"

# Python 2
python -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print a+b*0.1' "$A" "$B"

# Python 3
python3 -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print(a+b*0.1)' "$A" "$B"

# BC
bc <<< "scale=1 ; $A + $B * 0.1"

How to center align the cells of a UICollectionView?

For those looking for a solution to center-aligned, dynamic-width collectionview cells, as I was, I ended up modifying Angel's answer for a left-aligned version to create a center-aligned subclass for UICollectionViewFlowLayout.

CenterAlignedCollectionViewFlowLayout

// NOTE: Doesn't work for horizontal layout!
class CenterAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
        // Copy each item to prevent "UICollectionViewFlowLayout has cached frame mismatch" warning
        guard let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil }
        
        // Constants
        let leftPadding: CGFloat = 8
        let interItemSpacing = minimumInteritemSpacing
        
        // Tracking values
        var leftMargin: CGFloat = leftPadding // Modified to determine origin.x for each item
        var maxY: CGFloat = -1.0 // Modified to determine origin.y for each item
        var rowSizes: [[CGFloat]] = [] // Tracks the starting and ending x-values for the first and last item in the row
        var currentRow: Int = 0 // Tracks the current row
        attributes.forEach { layoutAttribute in
            
            // Each layoutAttribute represents its own item
            if layoutAttribute.frame.origin.y >= maxY {
                
                // This layoutAttribute represents the left-most item in the row
                leftMargin = leftPadding
                
                // Register its origin.x in rowSizes for use later
                if rowSizes.count == 0 {
                    // Add to first row
                    rowSizes = [[leftMargin, 0]]
                } else {
                    // Append a new row
                    rowSizes.append([leftMargin, 0])
                    currentRow += 1
                }
            }
            
            layoutAttribute.frame.origin.x = leftMargin
            
            leftMargin += layoutAttribute.frame.width + interItemSpacing
            maxY = max(layoutAttribute.frame.maxY, maxY)
            
            // Add right-most x value for last item in the row
            rowSizes[currentRow][1] = leftMargin - interItemSpacing
        }
        
        // At this point, all cells are left aligned
        // Reset tracking values and add extra left padding to center align entire row
        leftMargin = leftPadding
        maxY = -1.0
        currentRow = 0
        attributes.forEach { layoutAttribute in
            
            // Each layoutAttribute is its own item
            if layoutAttribute.frame.origin.y >= maxY {
                
                // This layoutAttribute represents the left-most item in the row
                leftMargin = leftPadding
                
                // Need to bump it up by an appended margin
                let rowWidth = rowSizes[currentRow][1] - rowSizes[currentRow][0] // last.x - first.x
                let appendedMargin = (collectionView!.frame.width - leftPadding  - rowWidth - leftPadding) / 2
                leftMargin += appendedMargin
                
                currentRow += 1
            }
            
            layoutAttribute.frame.origin.x = leftMargin
            
            leftMargin += layoutAttribute.frame.width + interItemSpacing
            maxY = max(layoutAttribute.frame.maxY, maxY)
        }
        
        return attributes
    }
}

CenterAlignedCollectionViewFlowLayout

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

How to add a single item to a Pandas Series

How to add single item. This is not very effective but follows what you are asking for:

x = p.Series()
N = 4
for i in xrange(N):
   x = x.set_value(i, i**2)

produces x:

0    0
1    1
2    4
3    9

Obviously there are better ways to generate this series in only one shot.

For your second question check answer and references of SO question add one row in a pandas.DataFrame.

iOS - Calling App Delegate method from ViewController

If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

(Require using UIKit;)

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

Extract Month and Year From Date in R

Here's another solution using a package solely dedicated to working with dates and times in R:

library(tidyverse)
library(lubridate)

(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#>      ID Date      
#>   <int> <chr>     
#> 1     1 2004-02-06
#> 2     2 2006-03-14
#> 3     3 2007-07-16

df %>%
  mutate(
    Date = ymd(Date),
    Month_Yr = format_ISO8601(Date, precision = "ym")
  )
#> # A tibble: 3 x 3
#>      ID Date       Month_Yr
#>   <int> <date>     <chr>   
#> 1     1 2004-02-06 2004-02 
#> 2     2 2006-03-14 2006-03 
#> 3     3 2007-07-16 2007-07

Created on 2020-09-01 by the reprex package (v0.3.0)

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

If using cocoapods, try reinstalling the pods by running the following command.

pod install

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

How do you log all events fired by an element in jQuery?

function bindAllEvents (el) {
  for (const key in el) {
      if (key.slice(0, 2) === 'on') {
          el.addEventListener(key.slice(2), e => console.log(e.type));
      }
  }
}
bindAllEvents($('.yourElement'))

This uses a bit of ES6 for prettiness, but can easily be translated for legacy browsers as well. In the function attached to the event listeners, it's currently just logging out what kind of event occurred but this is where you could print out additional information, or using a switch case on the e.type, you could only print information on specific events

JQuery - Storing ajax response into global variable

There's no way around it except to store it. Memory paging should reduce potential issues there.

I would suggest instead of using a global variable called 'xml', do something more like this:

var dataStore = (function(){
    var xml;

    $.ajax({
      type: "GET",
      url: "test.xml",
      dataType: "xml",
      success : function(data) {
                    xml = data;
                }
    });

    return {getXml : function()
    {
        if (xml) return xml;
        // else show some error that it isn't loaded yet;
    }};
})();

then access it with:

$(dataStore.getXml()).find('something').attr('somethingElse');

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

How to set an environment variable in a running docker container

Use export VAR=Value

Then type printenv in terminal to validate it is set correctly.

Parsing jQuery AJAX response

Use parseJSON. Look at the doc

var obj = $.parseJSON(data);

Something like this:

$.ajax({     
    type: "POST",
    url: '/admin/systemgoalssystemgoalupdate?format=html',
    data: formdata,
    success: function (data) {

        console.log($.parseJSON(data)); //will log Object

    }
});

How to convert float to varchar in SQL Server

float only has a max. precision of 15 digits. Digits after the 15th position are therefore random, and conversion to bigint (max. 19 digits) or decimal does not help you.

PHP replacing special characters like à->a, è->e

CodeIgniter way:

$this->load->helper('text');

$string = convert_accented_characters($string);

This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities

High CPU Utilization in java application - why?

Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.

In short, the following are the steps to generate flame graphs

yum -y install perf

wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz

tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64

echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict

JAVA_PID=`pgrep java`

./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg

flame-graph.svg can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.

There are few other approaches to generating them

  • By introducing -XX:+PreserveFramePointer as the JVM options as described here
  • Using async-profiler with -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints as described here

But using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.

Their wiki provides details on how to leverage it. And more about flame graphs can be found here

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

What does 'URI has an authority component' mean?

After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.

Common elements in two lists

Some of the answers above are similar but not the same so posting it as a new answer.

Solution:
1. Use HashSet to hold elements which need to be removed
2. Add all elements of list1 to HashSet
3. iterate list2 and remove elements from a HashSet which are present in list2 ==> which are present in both list1 and list2
4. Now iterate over HashSet and remove elements from list1(since we have added all elements of list1 to set), finally, list1 has all common elements
Note: We can add all elements of list2 and in a 3rd iteration, we should remove elements from list2.

Time complexity: O(n)
Space Complexity: O(n)

Code:

import com.sun.tools.javac.util.Assert;
import org.apache.commons.collections4.CollectionUtils;

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);
    list1.add(3);
    list1.add(4);
    list1.add(5);

    List<Integer> list2 = new ArrayList<>();
    list2.add(1);
    list2.add(3);
    list2.add(5);
    list2.add(7);
    Set<Integer> toBeRemoveFromList1 = new HashSet<>(list1);
    System.out.println("list1:" + list1);
    System.out.println("list2:" + list2);
    for (Integer n : list2) {
        if (toBeRemoveFromList1.contains(n)) {
            toBeRemoveFromList1.remove(n);
        }
    }
    System.out.println("toBeRemoveFromList1:" + toBeRemoveFromList1);
    for (Integer n : toBeRemoveFromList1) {
        list1.remove(n);
    }
    System.out.println("list1:" + list1);
    System.out.println("collectionUtils:" + CollectionUtils.intersection(list1, list2));
    Assert.check(CollectionUtils.intersection(list1, list2).containsAll(list1));

output:

list1:[1, 2, 3, 4, 5]
list2:[1, 3, 5, 7]
toBeRemoveFromList1:[2, 4]
list1:[1, 3, 5]
collectionUtils:[1, 3, 5]

Making LaTeX tables smaller?

There is also the singlespace environment:

\begin{singlespace}
\end{singlespace}

How can I check if a Perl array contains a particular value?

Best general purpose - Especially short arrays (1000 items or less) and coders that are unsure of what optimizations best suit their needs.

# $value can be any regex. be safe
if ( grep( /^$value$/, @array ) ) {
  print "found it";
}

It has been mentioned that grep passes through all values even if the first value in the array matches. This is true, however grep is still extremely fast for most cases. If you're talking about short arrays (less than 1000 items) then most algorithms are going to be pretty fast anyway. If you're talking about very long arrays (1,000,000 items) grep is acceptably quick regardless of whether the item is the first or the middle or last in the array.

Optimization Cases for longer arrays:

If your array is sorted, use a "binary search".

If the same array is repeatedly searched many times, copy it into a hash first and then check the hash. If memory is a concern, then move each item from the array into the hash. More memory efficient but destroys the original array.

If same values are searched repeatedly within the array, lazily build a cache. (as each item is searched, first check if the search result was stored in a persisted hash. if the search result is not found in the hash, then search the array and put the result in the persisted hash so that next time we'll find it in the hash and skip the search).

Note: these optimizations will only be faster when dealing with long arrays. Don't over optimize.

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Remove empty strings from array while keeping record Without Loop?

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

How to insert text into the textarea at the current cursor position?

Posting modified function for own reference. This example inserts a selected item from <select> object and puts the caret between the tags:

//Inserts a choicebox selected element into target by id
function insertTag(choicebox,id) {
    var ta=document.getElementById(id)
    ta.focus()
    var ss=ta.selectionStart
    var se=ta.selectionEnd
    ta.value=ta.value.substring(0,ss)+'<'+choicebox.value+'>'+'</'+choicebox.value+'>'+ta.value.substring(se,ta.value.length)
    ta.setSelectionRange(ss+choicebox.value.length+2,ss+choicebox.value.length+2)
}

Fixed header table with horizontal scrollbar and vertical scrollbar on

The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.

You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.

Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/

The important parts: CSS use

.head {
  overflow-x: hidden;
  overflow-y: scroll;
  width: 500px;
}
.lower {
  overflow-x: auto;
  overflow-y: scroll;
  width: 500px;
  height: 400px;
}

Notice overflow-y must be the same on both head and lower.

And the Javascript...

var head = document.querySelector('.head');

var lower = document.querySelector('.lower');

lower.addEventListener('scroll', function (e) {
  console.log(lower.scrollLeft);
  head.scrollLeft = lower.scrollLeft;
});

Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

print data['places']['latitude']

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

print data['places'][0]['post code']

C: How to free nodes in the linked list?

struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

Git: How to remove proxy

This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these

unset HTTP_PROXY
unset HTTPS_PROXY

in some systems you may also have to do

unset http_proxy
unset https_proxy

if you want to permanantly remove proxy then

sudo gsettings set org.gnome.system.proxy mode 'none'

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

How to run Pip commands from CMD

Firstly make sure that you have installed python 2.7 or higher

Open Command Prompt as administrator and change directory to python and then change directory to Scripts by typing cd Scripts then type pip.exe and now you can install modules Step by Step:

  • Open Cmd

  • type in "cd \" and then enter

  • type in "cd python2.7" and then enter

Note that my python version is 2.7 so my directory is that so use your python folder here...

  • type in "cd Scripts" and enter

  • Now enter this "pip.exe"

  • Now it prompts you to install modules

How to get config parameters in Symfony2 Twig Templates

You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.yml
parameters:
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
twig:
    globals:
        ga_tracking: "%ga_tracking%"

Now, the variable ga_tracking is available in all Twig templates:

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:

$this->container->getParameter('ga_tracking');

You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.yml
twig:
    # ...
    globals:
        user_management: "@acme_user.user_management"

http://symfony.com/doc/current/templating/global_variables.html

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.

Finding current executable's path without /proc/self/exe

But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces.

You cannot do that (at least on Linux)

Since an executable could, during execution of a process running it, rename(2) its file path to a different directory (of the same file system). See also syscalls(2) and inode(7).

On Linux, an executable could even (in principle) remove(3) itself by calling unlink(2). The Linux kernel should then keep the file allocated till no process references it anymore. With proc(5) you could do weird things (e.g. rename(2) that /proc/self/exe file, etc...)

In other words, on Linux, the notion of a "current application's directory" does not make any sense.

Read also Advanced Linux Programming and Operating Systems: Three Easy Pieces for more.

Look also on OSDEV for several open source operating systems (including FreeBSD or GNU Hurd). Several of them provide an interface (API) close to POSIX ones.

Consider using (with permission) cross-platform C++ frameworks like Qt or POCO, perhaps contributing to them by porting them to your favorite OS.

javascript regular expression to not match a word

This is what you are looking for:

^((?!(abc|def)).)*$

the explanation is here: Regular expression to match a line that doesn't contain a word?

How to change the remote a branch is tracking?

the easiest way is to simply push to the new branch:

git push -u origin branch/name

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

Change event on select with knockout binding, how can I know if it is a real change?

Quick and dirty, utilizing a simple flag:

var bindingsApplied = false;

var ViewModel = function() {
    // ...

    this.permissionChanged = function() {
        // ignore, if flag not set
        if (!flag) return;

        // ...
    };
};

ko.applyBindings(new ViewModel());
bindingsApplied = true; // done with the initial population, set flag to true

If this doesn't work, try wrapping the last line in a setTimeout() - events are async, so maybe the last one is still pending when applyBindings() already returned.

show all tables in DB2 using the LIST command

Connect to the database:

db2 connect to <database-name>

List all tables:

db2 list tables for all

To list all tables in selected schema, use:

db2 list tables for schema <schema-name>

To describe a table, type:

db2 describe table <table-schema.table-name>

credit http://onewebsql.com/blog/list-all-tables

How to stop a thread created by implementing runnable interface?

Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.

This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter

 i=0;
            w_h = 0;
            w_m = 0;


            textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
                        hl.removeCallbacksAndMessages(null);
                        Thread.currentThread().isInterrupted();


                        }


                    });


                }`

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

JavaScript array to CSV

const escapeString = item => (typeof item === 'string') ? `"${item}"` : String(item)

const arrayToCsv = (arr, seperator = ';') => arr.map(escapeString).join(seperator)

const rowKeysToCsv = (row, seperator = ';') => arrayToCsv(Object.keys(row))

const rowToCsv = (row, seperator = ';') => arrayToCsv(Object.values(row))

const rowsToCsv = (arr, seperator = ';') => arr.map(row => rowToCsv(row, seperator)).join('\n')

const collectionToCsvWithHeading = (arr, seperator = ';') => `${rowKeysToCsv(arr[0], seperator)}\n${rowsToCsv(arr, seperator)}`


// Usage: 

collectionToCsvWithHeading([
  { title: 't', number: 2 },
  { title: 't', number: 1 }
])

// Outputs: 
"title";"number"
"t";2
"t";1

How do I insert values into a Map<K, V>?

There are two issues here.

Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

public class Data {
     public static void main(String[] args) {
         Map<String, String> data = new HashMap<String, String>();
         data.put("John", "Taxi Driver");
         data.put("Mark", "Professional Killer");
     }
 }

If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

public class Data {
    private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}

Before Java 9, you can use a static initializer block to accomplish the same thing:

public class Data {
    private static final Map<String, String> DATA = new HashMap<>();

    static {
        DATA.put("John", "Taxi Driver");
    }
}

C++ - Hold the console window open?

A more appropriate method is to use std::cin.ignore:

#include <iostream>

void Pause()
{
   std::cout << "Press Enter to continue...";
   std::cout.flush();
   std::cin.ignore(10000, '\n');
   return;
}

How to select true/false based on column value?

At least in Postgres you can use the following statement:

SELECT EntityID, EntityName, EntityProfile IS NOT NULL AS HasProfile FROM Entity

What is the maximum number of edges in a directed graph with n nodes?

If the graph is not a multi graph then it is clearly n * (n - 1), as each node can at most have edges to every other node. If this is a multigraph, then there is no max limit.

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

How can I get a JavaScript stack trace when I throw an exception?

one way to get a the real stack trace on Firebug is to create a real error like calling an undefined function:

function foo(b){
  if (typeof b !== 'string'){
    // undefined Error type to get the call stack
    throw new ChuckNorrisError("Chuck Norris catches you.");
  }
}

function bar(a){
  foo(a);
}

foo(123);

Or use console.error() followed by a throw statement since console.error() shows the stack trace.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

How to convert from []byte to int in Go Programming

Starting from a byte array you can use the binary package to do the conversions.

For example if you want to read ints :

buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)

The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.

MemoryStream - Cannot access a closed Stream

when it gets out from the using statement the Dispose method will be called automatically closing the stream

try the below:

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

grep a tab in UNIX

I never managed to make the '\t' metacharacter work with grep. However I found two alternate solutions:

  1. Using <Ctrl-V> <TAB> (hitting Ctrl-V then typing tab)
  2. Using awk: foo | awk '/\t/'

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

as described in Microsoft documentation:

Response caching in ASP.NET Core - NoStore and Location.None

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

how to read value from string.xml in android?

Update

  • You can use getString(R.string.some_string_id) in both Activity or Fragment.
  • You can use Context.getString(R.string.some_string_id) where you don't have direct access to getString() method. Like Dialog.

Problem is where you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

Now you will pass Context as a parameter in this method and use getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

What i do is

public void someMethod(){
    ...
    App.getRes().getString(R.string.some_id)
}

What? It is very simple to use anywhere in your app!

So here is a Bonus unique solution by which you can access resources from anywhere like Util class .

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

REACT - toggle class onclick

React has a concept of components state, so if you want to switch it, do a setState:

constructor(props) {
  super(props);

  this.addActiveClass= this.addActiveClass.bind(this);
  this.state = {
    isActive: false
  }
}

addActiveClass() {
  this.setState({
    isActive: true
  })
}

In your component use this.state.isActive to render what you need.

This gets more complicated when you want to set state in component#1 and use it in component#2. Just dig more into react unidirectional data flow and possibly redux that will help you handle it.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

Command for restarting all running docker containers?

To start all the containers:

  docker restart $(docker ps -a -q)

Use sudo if you don't have permission to perform this:

sudo docker restart $(sudo docker ps -a -q)

Set Background cell color in PHPExcel

This always running!

$sheet->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('FF0000');

Remove a string from the beginning of a string

function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}

iPhone app could not be installed at this time

For me Setting Build Active Architecture to NO... works and installed successfully

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

What's the difference between an argument and a parameter?

The use of the terms parameters and arguments have been misused somewhat among programmers and even authors. When dealing with methods, the term parameter is used to identify the placeholders in the method signature, whereas the term arguments are the actual values that you pass in to the method.

MCSD Cerfification Toolkit (Exam 70-483) Programming in C#, 1st edition, Wrox, 2013

Real-world case scenario

// Define a method with two parameters
int Sum(int num1, int num2)
{
   return num1 + num2;
}

// Call the method using two arguments
var ret = Sum(2, 3);

Regular expression to match non-ASCII characters?

I had a problem with \p working as expected, so I just used a different strategy like:

([^\t]+)\t

Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.

How to filter WooCommerce products by custom attribute

Try WooCommerce Product Filter, plugin developed by Mihajlovicnenad.com. You can filter your products by any criteria. Also, it integrates with your Shop and archive pages perfectly. Here is a screenshot. And this is just one of the layouts, you can customize and make your own. Look at demo site. Thanks! enter image description here