Programs & Examples On #Microsoft sync framework

The Microsoft Sync Framework enables data synchronization in .NET applications in a hub-and-spoke or peer-to-peer relation. It uses metadata to synchronize datasets from different sources and formats to subscribers.

Order of items in classes: Fields, Properties, Constructors, Methods

Usually I try to follow the next pattern:

  • static members (have usually an other context, must be thread-safe, etc.)
  • instance members

Each part (static and instance) consists of the following member types:

  • operators (are always static)
  • fields (initialized before constructors)
  • constructors
  • destructor (is a tradition to follow the constructors)
  • properties
  • methods
  • events

Then the members are sorted by visibility (from less to more visible):

  • private
  • internal
  • internal protected
  • protected
  • public

The order is not a dogma: simple classes are easier to read, however, more complex classes need context-specific grouping.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys

reload(sys)
sys.setdefaultencoding('utf8')

How to make a gap between two DIV within the same column

#firstDropContainer{
float: left; 
width: 40%; 
margin-right: 1.5em; 

}

#secondDropContainer{
float: left; 
width: 40%;
margin-bottom: 1em;
}



<div id="mainDrop">
    <div id="firstDropContainer"></div>
    <div id="secondDropContainer"></div>
</div>

Note: Adjust the width of the divs based on your req. 

Importing json file in TypeScript

Another way to go

const data: {[key: string]: any} = require('./data.json');

This was you still can define json type is you want and don't have to use wildcard.

For example, custom type json.

interface User {
  firstName: string;
  lastName: string;
  birthday: Date;
}
const user: User = require('./user.json');

How to bring an activity to foreground (top of stack)?

I think a combination of Intent flags should do the trick. In particular, Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK.

Add these flags to your intent before calling startActvity.

Can an abstract class have a constructor?

yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.

// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
    }
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
    }

class Main {
public static void main(String args[]) { 
   Derived d = new Derived();
    }

}

This is the output of the above code,

Base Constructor Called Derived Constructor Called

references: enter link description here

How can I find and run the keytool

Depending on your version of Eclipse ( I am using Kepler). Go to Windows> Preferences>Android> Build.

You'll find the location path of your debug keystore as well as the SHA1 fingerprint (which you can just copy and use)

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

How can I add numbers in a Bash script?

There are a thousand and one ways to do it. Here's one using dc (a reverse-polish desk calculator which supports unlimited precision arithmetic):

dc <<<"$num1 $num2 + p"

But if that's too bash-y for you (or portability matters) you could say

echo $num1 $num2 + p | dc

But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc is here for you:

bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc

That said, there are some unrelated improvements you could be making to your script:

#!/bin/bash

num=0
metab=0

for ((i=1; i<=2; i++)); do
    for j in output-$i-* ; do # 'for' can glob directly, no need to ls
            echo "$j"

             # 'grep' can read files, no need to use 'cat'
            metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
            num=$(( $num + $metab ))
    done
    echo "$num"
done

As described in Bash FAQ 022, Bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc or dc) is required.

In this case the solution would be

num=$(dc <<<"$num $metab + p")

To add accumulate possibly-floating-point numbers into num.

Gradle error: could not execute build using gradle distribution

I had the same issue and i solved it by deleteing gradle-wrapper.jar and gradle-wrapper.properties file of Gradle wrapper then clean rebuild work for me.

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;
}

MessageBodyWriter not found for media type=application/json

In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:

  1. you have jersey-media-json-jackson in you pom.xml if using maven or added to your build path;
  2. you have an empty constructor in the data type you are trying to de-/serialize;
  3. you have the relevant annotation at the class and field level for your custom data type (xmlelement and/or jsonproperty);

However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:

GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
return Response.status(httpCode).entity(entity).build();

This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain

So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.

Compare two objects with .equals() and == operator

It looks like equals2 is just calling equals, so it will give the same results.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

Access props inside quotes in React JSX

If you want to use the es6 template literals, you need braces around the tick marks as well:

<img className="image" src={`images/${this.props.image}`} />

How to for each the hashmap?

I generally do the same as cx42net, but I don't explicitly create an Entry.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
    HashMap<innerKey, String> boxHolder = selects.get(key);
    ComboBox cb = new ComboBox();
    for (InnerKey innerKey : boxHolder.keySet())
    {
        cb.items.add(boxHolder.get(innerKey));
    }
}

This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.

ESLint - "window" is not defined. How to allow global variables in package.json

There is a builtin environment: browser that includes window.

Example .eslintrc.json:

"env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },

More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments

Also see the package.json answer by chevin99 below.

The request was aborted: Could not create SSL/TLS secure channel

One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.

There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:

  • .NET Framework 4.5 and earlier - SSL 3.0, TLS 1.0
  • .NET Framework 4.6.x - TLS 1.0, 1.1, 1.2, 1.3
  • .NET Framework 4.7+ - System (OS) Defaults

(For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported)

Microsoft's documentation strongly advises using 4.7+ and the system defaults:

We recommend that you:

  • Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
  • Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
  • Perform a thorough code audit to verify you're not specifying a TLS or SSL version.

For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:

<httpRuntime targetFramework="4.5" />

Better:

<httpRuntime targetFramework="4.7" />

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

How to set layout_weight attribute dynamically from code?

You can pass it in as part of the LinearLayout.LayoutParams constructor:

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT,
    1.0f
);
YOUR_VIEW.setLayoutParams(param);

The last parameter is the weight.

Difference between spring @Controller and @RestController annotation

If you use @RestController you cannot return a view (By using Viewresolver in Spring/springboot) and yes @ResponseBody is not needed in this case.

If you use @Controller you can return a view in Spring web MVC.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Animate background image change with jQuery

I don't think this can be done using jQuery's animate function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)

I guess you would have to work around this by not using genuine background-images, but div elements containing the image, positioned using position: absolute (or fixed) and z-index for stacking. You would then animate those divs.

Given URL is not allowed by the Application configuration Facebook application error

I solved this issue by specifying correct site URL in my App Settings. It works fine now. You have to specify your website Url such as http://www.xyz.com/

How to check if a map contains a key in Go?

better way here

if _, ok := dict["foo"]; ok {
    //do something here
}

How does numpy.newaxis work and when to use it?

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

Here is a visual illustration which depicts promotion of 1D array to 2D arrays.

newaxis canva visualization


Scenario-1: np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.

Example:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)

Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.

Example:

Let's say you want to add the following two arrays:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError :

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that NumPy can broadcast.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])

Now, add:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])

Alternatively, you can also add new axis to the array x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])

Now, add:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).


Scenario-3: This is similar to scenario-1. But, you can use np.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

Example:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)

More background on np.newaxis vs np.reshape

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

Example

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)

In the above example, we inserted a temporary axis between the first and second axes of B (to use broadcasting). A missing axis is filled-in here using np.newaxis to make the broadcasting operation work.


General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

Not 100% sure what you mean:

Trusted_Connection=True;

IS using Windows credentials and is 100% equivalent to:

Integrated Security=SSPI;

or

Integrated Security=true;

If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection or Integrated Security)

server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret

Only in this case, the SQL Server authentication mode is used.

If any of these two settings is present (Trusted_Connection=true or Integrated Security=true/SSPI), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD= setting will be ignored and not used.

For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.

Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.


Summing up:

If you specify either Trusted_Connection=True; or Integrated Security=SSPI; or Integrated Security=true; in your connection string

==> THEN (and only then) you have Windows Authentication happening. Any user id= setting in the connection string will be ignored.


If you DO NOT specify either of those settings,

==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)


What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

How to represent empty char in Java Character class

If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

Convert Pandas Column to DateTime

Use the to_datetime function, specifying a format to match your data.

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

Plot smooth line with PyPlot

You could use scipy.interpolate.spline to smooth out your data yourself:

from scipy.interpolate import spline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)  

power_smooth = spline(T, power, xnew)

plt.plot(xnew,power_smooth)
plt.show()

spline is deprecated in scipy 0.19.0, use BSpline class instead.

Switching from spline to BSpline isn't a straightforward copy/paste and requires a little tweaking:

from scipy.interpolate import make_interp_spline, BSpline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300) 

spl = make_interp_spline(T, power, k=3)  # type: BSpline
power_smooth = spl(xnew)

plt.plot(xnew, power_smooth)
plt.show()

Before: screenshot 1

After: screenshot 2

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How do I make HttpURLConnection use a proxy?

The approved answer will work ... if you know your proxy host and port =) . But in case you are looking for the proxy host and port the steps below should help

if auto configured proxy is given: then

1> open IE(or any browser)

2> get the url address from your browser through IE->Tools->internet option->connections->LAN Settings-> get address and give in url eg: as http://autocache.abc.com/ and enter, a file will be downloaded with .pac format, save to desktop

3> open .pac file in textpad, identify PROXY:

In your editor, it will come something like:

return "PROXY web-proxy.ind.abc.com:8080; PROXY proxy.sgp.abc.com:8080";

kudos to bekur from maven in 5 min not working

Once you have the host and port just pop in into this and your good to go

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("web-proxy.ind.abc.com", 8080));
        URLConnection connection = new URL(url).openConnection(proxy);

How to add/subtract dates with JavaScript?

You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.

take a look at this object reference to learn more:

Date

Hope that helps!

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

Hide/Show Column in an HTML Table

you could use colgroups:

<table>
    <colgroup>
       <col class="visible_class"/>
       <col class="visible_class"/>
       <col class="invisible_class"/>  
    </colgroup>
    <thead>
        <tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr>
    </thead>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

your script then could change just the desire <col> class.

How to wait for async method to complete?

Avoid async void. Have your methods return Task instead of void. Then you can await them.

Like this:

private async Task RequestToSendOutputReport(List<byte[]> byteArrays)
{
    foreach (byte[] b in byteArrays)
    {
        while (condition)
        {
            // we'll typically execute this code many times until the condition is no longer met
            Task t = SendOutputReportViaInterruptTransfer();
            await t;
        }

        // read some data from device; we need to wait for this to return
        await RequestToGetInputReport();
    }
}

private async Task RequestToGetInputReport()
{
    // lots of code prior to this
    int bytesRead = await GetInputReportViaInterruptTransfer();
}

Where is Ubuntu storing installed programs?

Just for an addition reference to the above answers. I can not use dpkg -L to find the correct path for cuda. See the results I got from dpkg -L

$ dpkg -L cuda
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/cuda
/usr/share/doc/cuda/copyright
/usr/share/doc/cuda/changelog.Debian.gz

the correct path is /usr/local/cuda

$ ll /usr/local | grep cuda

lrwxrwxrwx  1 root root    8 Oct 20 18:45 cuda -> cuda-9.0/

drwxr-xr-x 15 root root 4096 Oct 20 18:44 cuda-9.0/

Btw, I did install cuda by the command of

dpkg -i xx_cuda_xxx.deb

Get loop counter/index using for…of syntax in JavaScript

Answer Given by rushUp Is correct but this will be more convenient

for (let [index, val] of array.entries() || []) {
   // your code goes here    
}

Check variable equality against a list of values

For posterity you might want to use regular expressions as an alternative. Pretty good browser support as well (ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Browser_compatibility)

Try this

if (foo.toString().match(/^(1|3|12)$/)) {
    document.write('Regex me IN<br>');
} else {
    document.write('Regex me OUT<br>');
}

Sorting a Python list by two fields

In ascending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))

or in descending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)

How to indent a few lines in Markdown markup?

To answer MengLu and @lifebalance's questions in response to SColvin's answer (which I much prefer to the accepted answer for the control it provides), it seems as though you could just target a parent element of the lists when setting the display to none, adding a surrounding element if necessary. So if we suppose we're doing this for a table of contents, we can extend SColvin's answer:

HTML

<nav class="table-of-contents">
  this is a normal line of text
  * this is the first level of bullet points, made up of <space><space>*<space>
    * this is more indented, composed of <space><space><space><space>*<space>
</nav>

CSS

.table-of-contents ul {
  list-style-type: none;
}

Python - List of unique dictionaries

This is the solution I found:

usedID = []

x = [
{'id':1,'name':'john', 'age':34},
{'id':1,'name':'john', 'age':34},
{'id':2,'name':'hanna', 'age':30},
]

for each in x:
    if each['id'] in usedID:
        x.remove(each)
    else:
        usedID.append(each['id'])

print x

Basically you check if the ID is present in the list, if it is, delete the dictionary, if not, append the ID to the list

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Implementing IDisposable correctly

I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:

https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About

The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

What is the difference between java and core java?

"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.

Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:

static const char __func__[] = "function-name ";

where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__ and __PRETTY_FUNCTION__. Despite their uppercasing, they aren't macros. Although __func__ is an addition to C++0x

g++ -std=c++98 ....

will still compile code using __func__.

__PRETTY_FUNCTION__ and __FUNCTION__ are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__ is just another name for __func__. __PRETTY_FUNCTION__ is the same as __func__ in C but in C++ it contains the type signature as well.

How to check if a String contains another String in a case insensitive manner in Java?

One problem with the answer by Dave L. is when s2 contains regex markup such as \d, etc.

You want to call Pattern.quote() on s2:

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();

How to change a text with jQuery

Pretty straight forward to do:

$(function() {
  $('#toptitle').html('New word');
});

The html function accepts html as well, but its straight forward for replacing text.

How to convert text to binary code in JavaScript?

var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};

This is a small minified JavaScript Code to convert UTF8 to Binary and Vice versa.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

Import SQL file into mysql

For those of you struggling with getting this done trying every possible answer you can find on SO. Here's what worked for me on a VPS running Windows 2012 R2 :

  1. Place your sql file wherever the bin is for me it is located at C:\Program Files\MySQL\MySQL Server 8.0\bin

  2. Open windows command prompt (cmd)

  3. Run C:\Program Files\MySQL\MySQL Server 8.0\bin > mysql -u [username] -p
  4. Enter your password
  5. Run command use [database_name];
  6. Import your file with command source C://Program Files//MySQL//MySQL Server 8.0//bin//mydatabasename.sql

It did it for me as everything else had failed. It might help you too.

Compute a confidence interval from sample data

Here a shortened version of shasan's code, calculating the 95% confidence interval of the mean of array a:

import numpy as np, scipy.stats as st

st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))

But using StatsModels' tconfint_mean is arguably even nicer:

import statsmodels.stats.api as sms

sms.DescrStatsW(a).tconfint_mean()

The underlying assumptions for both are that the sample (array a) was drawn independently from a normal distribution with unknown standard deviation (see MathWorld or Wikipedia).

For large sample size n, the sample mean is normally distributed, and one can calculate its confidence interval using st.norm.interval() (as suggested in Jaime's comment). But the above solutions are correct also for small n, where st.norm.interval() gives confidence intervals that are too narrow (i.e., "fake confidence"). See my answer to a similar question for more details (and one of Russ's comments here).

Here an example where the correct options give (essentially) identical confidence intervals:

In [9]: a = range(10,14)

In [10]: mean_confidence_interval(a)
Out[10]: (11.5, 9.4457397432391215, 13.554260256760879)

In [11]: st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))
Out[11]: (9.4457397432391215, 13.554260256760879)

In [12]: sms.DescrStatsW(a).tconfint_mean()
Out[12]: (9.4457397432391197, 13.55426025676088)

And finally, the incorrect result using st.norm.interval():

In [13]: st.norm.interval(0.95, loc=np.mean(a), scale=st.sem(a))
Out[13]: (10.23484868811834, 12.76515131188166)

How can I specify system properties in Tomcat configuration on startup?

It's also possible letting a ServletContextListener set the System properties:

import java.util.Enumeration;
import javax.servlet.*;

public class SystemPropertiesHelper implements
        javax.servlet.ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        Enumeration<String> params = context.getInitParameterNames();

        while (params.hasMoreElements()) {
          String param = (String) params.nextElement();
          String value = 
            context.getInitParameter(param);
          if (param.startsWith("customPrefix.")) {
              System.setProperty(param, value);
          }
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}

And then put this into your web.xml (should be possible for context.xml too)

<context-param>
        <param-name>customPrefix.property</param-name>
        <param-value>value</param-value>
        <param-type>java.lang.String</param-type>
</context-param>

<listener>
    <listener-class>servletUtils.SystemPropertiesHelper</listener-class>    
</listener>

It worked for me.

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

How to generate the whole database script in MySQL Workbench?

In the top menu of MySQL Workbench click on database and then on forward engineer. In the options menu with which you will be presented, make sure to have "generate insert statements for tables" set.

How to properly add cross-site request forgery (CSRF) token using PHP

For security code, please don't generate your tokens this way: $token = md5(uniqid(rand(), TRUE));

Try this out:

Generating a CSRF Token

PHP 7

session_start();
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];

Sidenote: One of my employer's open source projects is an initiative to backport random_bytes() and random_int() into PHP 5 projects. It's MIT licensed and available on Github and Composer as paragonie/random_compat.

PHP 5.3+ (or with ext-mcrypt)

session_start();
if (empty($_SESSION['token'])) {
    if (function_exists('mcrypt_create_iv')) {
        $_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } else {
        $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
    }
}
$token = $_SESSION['token'];

Verifying the CSRF Token

Don't just use == or even ===, use hash_equals() (PHP 5.6+ only, but available to earlier versions with the hash-compat library).

if (!empty($_POST['token'])) {
    if (hash_equals($_SESSION['token'], $_POST['token'])) {
         // Proceed to process the form data
    } else {
         // Log this as a warning and keep an eye on these attempts
    }
}

Going Further with Per-Form Tokens

You can further restrict tokens to only be available for a particular form by using hash_hmac(). HMAC is a particular keyed hash function that is safe to use, even with weaker hash functions (e.g. MD5). However, I recommend using the SHA-2 family of hash functions instead.

First, generate a second token for use as an HMAC key, then use logic like this to render it:

<input type="hidden" name="token" value="<?php
    echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
?>" />

And then using a congruent operation when verifying the token:

$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
if (hash_equals($calc, $_POST['token'])) {
    // Continue...
}

The tokens generated for one form cannot be reused in another context without knowing $_SESSION['second_token']. It is important that you use a separate token as an HMAC key than the one you just drop on the page.

Bonus: Hybrid Approach + Twig Integration

Anyone who uses the Twig templating engine can benefit from a simplified dual strategy by adding this filter to their Twig environment:

$twigEnv->addFunction(
    new \Twig_SimpleFunction(
        'form_token',
        function($lock_to = null) {
            if (empty($_SESSION['token'])) {
                $_SESSION['token'] = bin2hex(random_bytes(32));
            }
            if (empty($_SESSION['token2'])) {
                $_SESSION['token2'] = random_bytes(32);
            }
            if (empty($lock_to)) {
                return $_SESSION['token'];
            }
            return hash_hmac('sha256', $lock_to, $_SESSION['token2']);
        }
    )
);

With this Twig function, you can use both the general purpose tokens like so:

<input type="hidden" name="token" value="{{ form_token() }}" />

Or the locked down variant:

<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />

Twig is only concerned with template rendering; you still must validate the tokens properly. In my opinion, the Twig strategy offers greater flexibility and simplicity, while maintaining the possibility for maximum security.


Single-Use CSRF Tokens

If you have a security requirement that each CSRF token is allowed to be usable exactly once, the simplest strategy regenerate it after each successful validation. However, doing so will invalidate every previous token which doesn't mix well with people who browse multiple tabs at once.

Paragon Initiative Enterprises maintains an Anti-CSRF library for these corner cases. It works with one-use per-form tokens, exclusively. When enough tokens are stored in the session data (default configuration: 65535), it will cycle out the oldest unredeemed tokens first.

Understanding generators in Python

A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.

>>> def myGenerator():
...     yield 'These'
...     yield 'words'
...     yield 'come'
...     yield 'one'
...     yield 'at'
...     yield 'a'
...     yield 'time'

>>> myGeneratorInstance = myGenerator()
>>> next(myGeneratorInstance)
These
>>> next(myGeneratorInstance)
words

and so on. The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem. Generators, just like lists, are iterable, so they can be used in the same ways:

>>> for word in myGeneratorInstance:
...     print word
These
words
come
one
at 
a 
time

Note that generators provide another way to deal with infinity, for example

>>> from time import gmtime, strftime
>>> def myGen():
...     while True:
...         yield strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())    
>>> myGeneratorInstance = myGen()
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:17:15 +0000
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:18:02 +0000   

The generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.

How to check size of a file using Bash?

If your find handles this syntax, you can use it:

find -maxdepth 1 -name "file.txt" -size -90k

This will output file.txt to stdout if and only if the size of file.txt is less than 90k. To execute a script script if file.txt has a size less than 90k:

find -maxdepth 1 -name "file.txt" -size -90k -exec script \;

g++ undefined reference to typeinfo

This occurs when declared (non-pure) virtual functions are missing bodies. In your class definition, something like:

virtual void foo();

Should be defined (inline or in a linked source file):

virtual void foo() {}

Or declared pure virtual:

virtual void foo() = 0;

How do I get an Excel range using row and column numbers in VSTO / C#?

UsedRange work fine with "virgins" cells, but if your cells are filled in the past, then UsedRange will deliver to you the old value.

For example:

"Think in a Excel sheet that have cells A1 to A5 filled with text". In this scenario, UsedRange must be implemented as:

Long SheetRows;
SheetRows = ActiveSheet.UsedRange.Rows.Count;

A watch to SheetRows variable must display a value of 5 after the execution of this couple of lines.

Q1: But, what happen if the value of A5 is deleted?

A1: The value of SheetRows would be 5

Q2: Why this?

A2: Because MSDN define UsedRange property as:

Gets a Microsoft.Office.Interop.Excel.Range object that represents all the cells that have contained a value at any time.


So, the question is: Exist some/any workaround for this behavior?

I think in 2 alternatives:

  1. Avoid deleting the content of the cell, preferring deletion of the whole row (right click in the row number, then "delete row".
  2. Use CurrentRegion instead of UsedRange property as follow:

Long SheetRows;
SheetRows = ActiveSheet.Range("A1").CurrentRegion.Rows.Count;

How to delete a remote tag?

git tag -d your_tag_name
git push origin :refs/tags/your_tag_name

The first line deletes your_tag_name from local repo and second line deletes your_tag_name from remote repo.

For those who use GitHub, one more step is needed: discarding draft. enter image description here

Making a mocked method return an argument that was passed to it

You might want to use verify() in combination with the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mock).myFunction(argument.capture());
assertEquals("the expected value here", argument.getValue());

The argument's value is obviously accessible via the argument.getValue() for further manipulation / checking /whatever.

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

push_back vs emplace_back

A nice code for the push_back and emplace_back is shown here.

http://en.cppreference.com/w/cpp/container/vector/emplace_back

You can see the move operation on push_back and not on emplace_back.

How to get visitor's location (i.e. country) using geolocation?

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you
};

geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...

how to put image in center of html page?

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }

Changing Node.js listening port

you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me

backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number 
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};

In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port. For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts

Start thread with member function

@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:

#include <thread>
#include <iostream>

class CFoo {
  public:
    int m_i = 0;
    void bar() {
      ++m_i;
    }
};

int main() {
  CFoo foo;
  std::thread t1(&CFoo::bar, &foo);
  t1.join();
  std::thread t2(&CFoo::bar, &foo);
  t2.join();
  std::cout << foo.m_i << std::endl;
  return 0;
}

outputs

2

Rewritten sample from this answer would be then:

#include <thread>
#include <iostream>

class Wrapper {
  public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread(&Wrapper::member1, this);
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread(&Wrapper::member2, this, arg1, arg2);
      }
};

int main() {
  Wrapper *w = new Wrapper();
  std::thread tw1 = w->member1Thread();
  tw1.join();
  std::thread tw2 = w->member2Thread("hello", 100);
  tw2.join();
  return 0;
}

How do I get ruby to print a full backtrace instead of a truncated one?

This produces the error description and nice clean, indented stacktrace:

begin               
 # Some exception throwing code
rescue => e
  puts "Error during processing: #{$!}"
  puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
end

Android Studio installation on Windows 7 fails, no JDK found

This problem has been fixed in Android Studio v0.1.1, so just update Android Studio and it should work.

How do I subscribe to all topics of a MQTT broker

Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

mosquitto_sub -h test.mosquitto.org -t "#" -v

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of irisys/V4D-19230005/ to the test MQTT broker , then you could filter the messages:

mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v

Options:

  • -h the hostname (default MQTT port = 1883)
  • -t precedes the topic

How do I use Maven through a proxy?

I run cntlm localy, configured with NTLMv2 password hashes to authenticate with the corporate proxy, and use

export MAVEN_OPTS="-DproxyHost=127.0.0.1 -DproxyPort=3128"

to use that proxy from maven. Of course the proxy you use should support cntlm/NTLMv2.

Removing element from array in component state

You could make the code more readable with a one line helper function:

const removeElement = (arr, i) => [...arr.slice(0, i), ...arr.slice(i+1)];

then use it like so:

this.setState(state => ({ places: removeElement(state.places, index) }));

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

How to style SVG with external CSS?

"I am actually going to change the colors of these images based on what color scheme the user has chosen for my site." - Jordan 10 hours ago

I suggest you to use PHP for this. There's really no better way to do this without icon fonts, and if you resist using them, you could try this:

<?php

    header('Content-Type: image/svg+xml');
    echo '<?xml version="1.0" encoding="utf-8"?>';
    $color = $_GET['color'];

?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
    <g>
        <path fill="<?php echo $color; ?>" d="M28.44..."/>
    </g>
</svg>

And later you could use this file as filename.php?color=#ffffff to get the svg file in the desired color.

Calling one Activity from another in Android

The following code demonstrates how you can start another activity via an intent.

Start the activity with an intent connected to the specified class

Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);

Activities which are started by other Android activities are called sub-activities. This wording makes it easier to describe which activity is meant.

Javascript return number of days,hours,minutes,seconds between two dates

here is an code to find difference between two dates in Days,Hours,Minutes,Seconds (assuming the future date is new year date).

var one_day = 24*60*60*1000;              // total milliseconds in one day

var today = new Date();
var new_year = new Date("01/01/2017");    // future date

var today_time = today.getTime();         // time in miliiseconds
var new_year_time = new_year.getTime();                         

var time_diff = Math.abs(new_year_time - today_time);  //time diff in ms  
var days = Math.floor(time_diff / one_day);            // no of days

var remaining_time = time_diff - (days*one_day);      // remaining ms  

var hours = Math.floor(remaining_time/(60*60*1000));   
remaining_time = remaining_time - (hours*60*60*1000);  

var minutes = Math.floor(remaining_time/(60*1000));        
remaining_time = remaining_time - (minutes * 60 * 1000);   

var seconds = Math.ceil(remaining_time / 1000);   

Can I have an onclick effect in CSS?

you can use :target

or to filter by class name, use .classname:target

or filter by id name using #idname:target

_x000D_
_x000D_
#id01:target {      
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.msg {
    display:none;
}

.close {        
    color:white;        
    width: 2rem;
    height: 2rem;
    background-color: black;
    text-align:center;
    margin:20px;
}
_x000D_
  
<a href="#id01">Open</a>

<div id="id01" class="msg">    
    <a href="" class="close">&times;</a>
    <p>Some text. Some text. Some text.</p>
    <p>Some text. Some text. Some text.</p>
</div>
_x000D_
_x000D_
_x000D_

Chaining multiple filter() in Django, is this a bug?

Saw this in a comment and I thought it was the simplest explanation.

filter(A, B) is the AND filter(A).filter(B) is OR

How can I create an object based on an interface file definition in TypeScript?

Here is another approach:

You can simply create an ESLint friendly object like this

const modal: IModal = {} as IModal;

Or a default instance based on the interface and with sensible defaults, if any

const defaultModal: IModal = {
    content: "",
    form: "",
    href: "",
    $form: {} as JQuery,
    $message: {} as JQuery,
    $modal: {} as JQuery,
    $submits: {} as JQuery
};

Then variations of the default instance simply by overriding some properties

const confirmationModal: IModal = {
    ...defaultModal,     // all properties/values from defaultModal
    form: "confirmForm"  // override form only
}

What is the difference between dim and set in vba

According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.

Dim newObj as Object
Set var1=Object1(same type as Object)
Set var2=Object1(same type as Object)
Set var3=Object1(same type as Object)
Set var4=Object1(same type as Object)
Var1.property1=NewPropertyValue

the other Vars properties also changes,so:

Var1.property1=Var2.property1=Var3.property1=Var4.property1=Object1.Property1=NewpropertyValue`

actualy all vars are the same!

Pass parameter to controller from @Html.ActionLink MVC 4

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value

Find all files in a directory with extension .txt in Python

Something like this will work:

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

The difference between BCNF and 3NF

Using the BCNF definition

If and only if for every one of its dependencies X ? Y, at least one of the following conditions hold:

  • X ? Y is a trivial functional dependency (Y ? X), or
  • X is a super key for schema R

and the 3NF definition

If and only if, for each of its functional dependencies X ? A, at least one of the following conditions holds:

  • X contains A (that is, X ? A is trivial functional dependency), or
  • X is a superkey, or
  • Every element of A-X, the set difference between A and X, is a prime attribute (i.e., each attribute in A-X is contained in some candidate key)

We see the following difference, in simple terms:

  • In BCNF: Every partial key (prime attribute) can only depend on a superkey,

whereas

  • In 3NF: A partial key (prime attribute) can also depend on an attribute that is not a superkey (i.e. another partial key/prime attribute or even a non-prime attribute).

Where

  1. A prime attribute is an attribute found in a candidate key, and
  2. A candidate key is a minimal superkey for that relation, and
  3. A superkey is a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set.Equivalently a superkey can also be defined as a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent. (A superkey always contains a candidate key/a candidate key is always a subset of a superkey. You can add any attribute in a relation to obtain one of the superkeys.)

That is, no partial subset (any non trivial subset except the full set) of a candidate key can be functionally dependent on anything other than a superkey.

A table/relation not in BCNF is subject to anomalies such as the update anomalies mentioned in the pizza example by another user. Unfortunately,

  • BNCF cannot always be obtained, while
  • 3NF can always be obtained.

3NF Versus BCNF Example

An example of the difference can currently be found at "3NF table not meeting BCNF (Boyce–Codd normal form)" on Wikipedia, where the following table meets 3NF but not BCNF because "Tennis Court" (a partial key/prime attribute) depends on "Rate Type" (a partial key/prime attribute that is not a superkey), which is a dependency we could determine by asking the clients of the database, the tennis club:

Today's Tennis Court Bookings (3NF, not BCNF)

Court   Start Time  End Time    Rate Type
------- ----------  --------    ---------
1       09:30       10:30       SAVER
1       11:00       12:00       SAVER
1       14:00       15:30       STANDARD
2       10:00       11:30       PREMIUM-B
2       11:30       13:30       PREMIUM-B
2       15:00       16:30       PREMIUM-A

The table's superkeys are:

S1 = {Court, Start Time}
S2 = {Court, End Time}
S3 = {Rate Type, Start Time}
S4 = {Rate Type, End Time}
S5 = {Court, Start Time, End Time}
S6 = {Rate Type, Start Time, End Time}
S7 = {Court, Rate Type, Start Time}
S8 = {Court, Rate Type, End Time}
ST = {Court, Rate Type, Start Time, End Time}, the trivial superkey

The 3NF problem: The partial key/prime attribute "Court" is dependent on something other than a superkey. Instead, it is dependent on the partial key/prime attribute "Rate Type". This means that the user must manually change the rate type if we upgrade a court, or manually change the court if wanting to apply a rate change.

  • But what if the user upgrades the court but does not remember to increase the rate? Or what if the wrong rate type is applied to a court?

(In technical terms, we cannot guarantee that the "Rate Type" -> "Court" functional dependency will not be violated.)

The BCNF solution: If we want to place the above table in BCNF we can decompose the given relation/table into the following two relations/tables (assuming we know that the rate type is dependent on only the court and membership status, which we could discover by asking the clients of our database, the owners of the tennis club):

Rate Types (BCNF and the weaker 3NF, which is implied by BCNF)

Rate Type   Court   Member Flag
---------   -----   -----------
SAVER       1       Yes
STANDARD    1       No
PREMIUM-A   2       Yes
PREMIUM-B   2       No

Today's Tennis Court Bookings (BCNF and the weaker 3NF, which is implied by BCNF)

Member Flag     Court     Start Time   End Time
-----------     -----     ----------   --------
Yes             1         09:30        10:30
Yes             1         11:00        12:00
No              1         14:00        15:30
No              2         10:00        11:30
No              2         11:30        13:30
Yes             2         15:00        16:30

Problem Solved: Now if we upgrade the court we can guarantee the rate type will reflect this change, and we cannot charge the wrong price for a court.

(In technical terms, we can guarantee that the functional dependency "Rate Type" -> "Court" will not be violated.)

How to add screenshot to READMEs in github repository?

I googled a few similar questions and did not see any answers with my problem and its quite simple/easy solution.

Google Cloud Storage - a slightly different approach to images in READMEs

Here goes: like the OP, I wanted an image in my Github README, and, knowing the Markdown syntax for doing so, typed it in:

![My Image](https://storage.cloud.google.com/${MY_BUCKET}/${MY_IMAGE}

You need to complete the actual substitutions above (e.g. MY_IMAGE=image.jpg) for this to work.

But, wait...failure--there's no actual rendered photo! And the link is exactly as given by Google Storage!

screenshot of failed Github image upload

Github camo - Anonymous Images

Github hosts your images anonymously, yay! However, this presents an issue for Google storage assets. You need to get the generated url from your Google Cloud Console.

I'm sure there's a smoother way, however, simply visit your given URL endpoint and copy the long URL. Details:

Instructions

  1. Visit your storage console: https://console.cloud.google.com/storage/browser/${MY_BUCKET}?project=${MY_PROJECT}
  2. Click on the image you'd like to display in Github (this brings up the "Object Details" page)
  3. Copy pasta that URL (the one starting with https not gs) into a new browser tab/window
  4. Copy pasta the new generated URL -- it should be longer -- from your new browser tab/window into your Github README file

Hopefully this helps speed up and clarify this issue for anyone else.

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.

Eclipse error: R cannot be resolved to a variable

Try to delete the import line import com.your.package.name.app.R, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name); will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:

  • android.R
  • your.package.name.R

Select the R corresponding to your package name, and you should be good to go. Hope that helps.

Plot two graphs in same plot in R

lines() or points() will add to the existing graph, but will not create a new window. So you'd need to do

plot(x,y1,type="l",col="red")
lines(x,y2,col="green")

JavaScript OOP in NodeJS: how?

As Node.js community ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner.

You can take a look at JavaScript classes. MDN link to JS classes In the ECMAScript 6 JavaScript classes are introduced, this method provide easier way to model OOP concepts in Javascript.

Note : JS classes will work in only strict mode.

Below is some skeleton of class,inheritance written in Node.js ( Used Node.js Version v5.0.0 )

Class declarations :

'use strict'; 
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

var a1 = new Animal('Dog');

Inheritance :

'use strict';
class Base{

 constructor(){
 }
 // methods definitions go here
}

class Child extends Base{
 // methods definitions go here
 print(){ 
 }
}

var childObj = new Child();

Android: failed to convert @drawable/picture into a drawable

If re-starting Eclipse does not correct the problem, make sure that the image name begins with an alpha character (non-numeric).

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

How can I pass POST parameters in a URL?

I would like to share my implementation as well. It does require some JavaScript code though.

<form action="./index.php" id="homePage" method="post" style="display: none;">
    <input type="hidden" name="action" value="homePage" />
</form>

<a href="javascript:;" onclick="javascript:
document.getElementById('homePage').submit()">Home</a>

The nice thing about this is that, contrary to GET requests, it doesn't show the parameters in the URL, which is safer.

How to set width of mat-table column in angular?

You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

.mat-column-yourFieldName {
    flex: none;
    width: 100px;
}

So we can give fixed width for column as per our requirement.

Hope this helps for someone.

FlutterError: Unable to load asset

Don't struggle to add the path to each image asset, instead just specify the path to your images directory.
just make sure you use proper indentations as the pubspec.yaml is indent sensitive.

flutter:

  uses-material-design: true
  assets:
    - images/

and you can simply access each image as

  new Image.asset('images/pizza1.png',width:300,height:100)

How do I find out my root MySQL password?

I'm going to make a bit of an assumption here because I'm not sure. I don't think my MySQL (running on latest 20.04 upgraded) even has a root. I have tried setting one and I remember having problems. I suspect there is not a root user and it will automatically log you in as the MySQL root user if you're logged in as root.

Why do I think this? Because when I do MySQL -u root -p, it will accept any password and log me in as the MySQL root user when I am logged in as root.

I have confirmed that trying that on a non root user doesn't work.

I like this model.

EDIT 2020.12.19: It is no longer a mystery to me why if you are logged in as the root user you get logged into MySQL as the root user. It has to do with the authentication type. Later versions of MySQL are configured with the MySQL plugin 'auth_socket' (maybe you've noticed the /run/mysqld/mysqld.sock file on your system and wondered about it). The plugin uses the SO_PEERCRED option provided by the library auth_socket.so.

You can revert back to password authentication if desired simply by create/update of the password. Showing both ways and options below to make clear.

CREATE USER 'valerie'@'localhost' IDENTIFIED WITH auth_socket;
CREATE USER 'valerie'@'localhost' IDENTIFIED BY 'password';

Changing git commit message after push (given that no one pulled from remote)

git commit --amend

then edit and change the message in the current window. After that do

git push --force-with-lease

How to select distinct rows in a datatable and store into an array

DataTable dtbs = new DataTable(); 
DataView dvbs = new DataView(dt); 
dvbs.RowFilter = "ColumnName='Filtervalue'"; 
dtbs = dvbs.ToTable();

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

SQL Server Installation - What is the Installation Media Folder?

Check in Administration Tools\Services (or type services.msc in the console if you a service named SQL Server (SQLEXPRESS). If you do then it is installed.

From Visual Studio open Server Explorer (menu View\Server Explorer or CTRL + W, L). Right click Data Connections and choose Create New SQL Server Database. After that create tables and stuff...

If you want the Management Studio to manage the server you must download and install it from:

http://www.microsoft.com/downloads/en/details.aspx?FamilyId=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en

How do I rotate the Android emulator display?

You can use Numpad-9 and Numpad-7 to rotate on Windows and Ubuntu.

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Find stored procedure by name

This will work for tables and views (among other things) as well, not just sprocs:

SELECT
    '[' + s.name + '].[' + o.Name + ']',
    o.type_desc
FROM
    sys.objects o
    JOIN sys.schemas s ON s.schema_id = o.schema_id
WHERE
    o.name = 'CreateAllTheThings' -- if you are certain of the exact name
    OR o.name LIKE '%CreateAllThe%' -- if you are not so certain

It also gives you the schema name which will be useful in any non-trivial database (e.g. one where you need a query to find a stored procedure by name).

How to change css property using javascript

Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.

How to use an arraylist as a prepared statement parameter

If you have ArrayList then convert into Array[Object]

ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt = 
            conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

How to detect orientation change?

Check if rotation had changed with: viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)

With the coordinator.animateAlongsideTransition(nil) { (UIViewControllerTransitionCoordinatorContext) you can check if the transition is finished.

See code below:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    coordinator.animateAlongsideTransition(nil) { (UIViewControllerTransitionCoordinatorContext) in
        // if you want to execute code after transition finished
        print("Transition finished")
    }

    if size.height < size.width {
        // Landscape
        print("Landscape")
    } else {
        // Portrait
        print("Portrait")
    }

}

How to easily duplicate a Windows Form in Visual Studio?

First of all, if you're duplicating a lot of forms with cut and paste, consider a common base class for your forms (or for a category of your forms) that implements shared/common functionality or look & feel elements. You can also create a template for new forms that meet your needs and create new forms from that template.

Personally I just cut and paste then fix any lingering name errors. Since I abstract out common functionality, I have not felt enough pain to look for a better way ;-)

How to list all Git tags?

To list tags I prefer:

git tag -n

The -n flag displays the first line of the annotation message along with the tag, or the first commit message line if the tag is not annotated.

You can also do git tag -n5 to show the first 5 lines of the annotation.

php $_GET and undefined index

You should check wheter the index exists before use it (compare it)

if (isset($_GET['s']) AND $_GET['s'] == 'foobar') {
    echo "foo";
}

Use E_ALL | E_STRICT while developing!

How to trigger ngClick programmatically

Simple sample:

HTML

<div id='player'>
    <div id="my-button" ng-click="someFuntion()">Someone</div>
</div>

JavaScript

$timeout(function() {
    angular.element('#my-button').triggerHandler('click');
}, 0);

What this does is look for the button's id and perform a click action. Voila.

Source: https://techiedan.com/angularjs-how-to-trigger-click/

How to focus on a form input text field on page load using jQuery?

place after input

<script type="text/javascript">document.formname.inputname.focus();</script>

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Function overloading in Javascript - Best practices

I just tried this, maybe it suits your needs. Depending on the number of the arguments, you can access a different function. You initialize it the first time you call it. And the function map is hidden in the closure.

TEST = {};

TEST.multiFn = function(){
    // function map for our overloads
    var fnMap = {};

    fnMap[0] = function(){
        console.log("nothing here");
        return this;    //    support chaining
    }

    fnMap[1] = function(arg1){
        //    CODE here...
        console.log("1 arg: "+arg1);
        return this;
    };

    fnMap[2] = function(arg1, arg2){
        //    CODE here...
        console.log("2 args: "+arg1+", "+arg2);
        return this;
    };

    fnMap[3] = function(arg1,arg2,arg3){
        //    CODE here...
        console.log("3 args: "+arg1+", "+arg2+", "+arg3);
        return this;
    };

    console.log("multiFn is now initialized");

    //    redefine the function using the fnMap in the closure
    this.multiFn = function(){
        fnMap[arguments.length].apply(this, arguments);
        return this;
    };

    //    call the function since this code will only run once
    this.multiFn.apply(this, arguments);

    return this;    
};

Test it.

TEST.multiFn("0")
    .multiFn()
    .multiFn("0","1","2");

'typeid' versus 'typeof' in C++

typeid can operate at runtime, and return an object describing the run time type of the object, which must be a pointer to an object of a class with virtual methods in order for RTTI (run-time type information) to be stored in the class. It can also give the compile time type of an expression or a type name, if not given a pointer to a class with run-time type information.

typeof is a GNU extension, and gives you the type of any expression at compile time. This can be useful, for instance, in declaring temporary variables in macros that may be used on multiple types. In C++, you would usually use templates instead.

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to add a border to a widget in Flutter?

Here, as the Text widget does not have a property that allows us to define a border, we should wrap it with a widget that allows us to define a border. There are several solutions.
But the best solution is the use of BoxDecoration in the Container widget.

Why choose to use BoxDecoration ?
Because BoxDecoration offers more customization like the possibility to define :
First, the border and also define:

  • border Color
  • border width
  • border radius
  • shape
  • and more ...

An example :

   Container(
     child:Text(' Hello Word '),
     decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(
                color: Colors.red ,
                width: 2.0 ,
              ),
          borderRadius: BorderRadius.circular(15),
            ),
          ),

Output :

enter image description here

How does Facebook disable the browser's integrated Developer Tools?

I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false
});

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    }
    throw "Console is disabled";
}

var l, n = {
        set: function (o) {
            l = o;
        },
        get: function () {
            showWarningAndThrow();
            return l;
        }
    };
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).

References:

How to get the date from the DatePicker widget in Android?

I manged to set the MinDate & the MaxDate programmatically like this :

    final Calendar c = Calendar.getInstance();

    int maxYear = c.get(Calendar.YEAR) - 20; // this year ( 2011 ) - 20 = 1991
    int maxMonth = c.get(Calendar.MONTH);
    int maxDay = c.get(Calendar.DAY_OF_MONTH);

    int minYear = 1960;
    int minMonth = 0; // january
    int minDay = 25;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_account);
        BirthDateDP = (DatePicker) findViewById(R.id.create_account_BirthDate_DatePicker);
        BirthDateDP.init(maxYear - 10, maxMonth, maxDay, new OnDateChangedListener()
        {

        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            if (year < minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (monthOfYear < minMonth && year == minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
                view.updateDate(minYear, minMonth, minDay);


                if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }}); // BirthDateDP.init()
    } // activity

it works fine for me, enjoy :)

Java NIO: What does IOException: Broken pipe mean?

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

Microsoft.ACE.OLEDB.12.0 is not registered

There is a alter way. Open the excel file in Microsoft office Excel, and save it as "Excel 97-2003 Workbook". Then, use the new saved excel file in your file connection.

How to change values in a tuple?

i did this:

list = [1,2,3,4,5]
tuple = (list)

and to change, just do

list[0]=6

and u can change a tuple :D

here is it copied exactly from IDLE

>>> list=[1,2,3,4,5,6,7,8,9]

>>> tuple=(list)

>>> print(tuple)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[0]=6

>>> print(tuple)

[6, 2, 3, 4, 5, 6, 7, 8, 9]

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}

Body of Http.DELETE request in Angular2

deleteInsurance(insuranceId: any) {
    const insuranceData = {
      id : insuranceId
    }
    var reqHeader = new HttpHeaders({
            "Content-Type": "application/json",
        });
        const httpOptions = {
            headers: reqHeader,
            body: insuranceData,
        };
    return this.http.delete<any>(this.url + "users/insurance", httpOptions);
    }

Trigger a Travis-CI rebuild without pushing a commit?

If the build never occurred (perhaps you didn't get the Pull-Request build switch set to on in time), you can mark the Pull Request on Github as closed then mark it as opened and a new build will be triggered.

How to run a script at a certain time on Linux?

Look at the following:

echo "ls -l" | at 07:00

This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:

http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html

Hope it helps!

How do I print debug messages in the Google Chrome JavaScript Console?

console.debug("");

Using this method prints out the text in a bright blue color in the console.

enter image description here

Remove NA values from a vector

Trying ?max, you'll see that it actually has a na.rm = argument, set by default to FALSE. (That's the common default for many other R functions, including sum(), mean(), etc.)

Setting na.rm=TRUE does just what you're asking for:

d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)

If you do want to remove all of the NAs, use this idiom instead:

d <- d[!is.na(d)]

A final note: Other functions (e.g. table(), lm(), and sort()) have NA-related arguments that use different names (and offer different options). So if NA's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.

How should we manage jdk8 stream for null values

Current thinking seems to be to "tolerate" nulls, that is, to allow them in general, although some operations are less tolerant and may end up throwing NPE. See the discussion of nulls on the Lambda Libraries expert group mailing list, specifically this message. Consensus around option #3 subsequently emerged (with a notable objection from Doug Lea). So yes, the OP's concern about pipelines blowing up with NPE is valid.

It's not for nothing that Tony Hoare referred to nulls as the "Billion Dollar Mistake." Dealing with nulls is a real pain. Even with classic collections (without considering lambdas or streams) nulls are problematic. As fge mentioned in a comment, some collections allow nulls and others do not. With collections that allow nulls, this introduces ambiguities into the API. For example, with Map.get(), a null return indicates either that the key is present and its value is null, or that the key is absent. One has to do extra work to disambiguate these cases.

The usual use for null is to denote the absence of a value. The approach for dealing with this proposed for Java SE 8 is to introduce a new java.util.Optional type, which encapsulates the presence/absence of a value, along with behaviors of supplying a default value, or throwing an exception, or calling a function, etc. if the value is absent. Optional is used only by new APIs, though, everything else in the system still has to put up with the possibility of nulls.

My advice is to avoid actual null references to the greatest extent possible. It's hard to see from the example given how there could be a "null" Otter. But if one were necessary, the OP's suggestions of filtering out null values, or mapping them to a sentinel object (the Null Object Pattern) are fine approaches.

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

What is std::move(), and when should it be used?

std::move itself does nothing rather than a static_cast. According to cppreference.com

It is exactly equivalent to a static_cast to an rvalue reference type.

Thus, it depends on the type of the variable you assign to after the move, if the type has constructors or assign operators that takes a rvalue parameter, it may or may not steal the content of the original variable, so, it may leave the original variable to be in an unspecified state:

Unless otherwise specified, all standard library objects that have been moved from being placed in a valid but unspecified state.

Because there is no special move constructor or move assign operator for built-in literal types such as integers and raw pointers, so, it will be just a simple copy for these types.

Mail not sending with PHPMailer over SSL using SMTP

Firstly, use these settings for Google:

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; //edited from tsl
$mail->Username = "myEmail";
$mail->Password = "myPassword";
$mail->Port = "587";

But also, what firewall have you got set up?

If you're filtering out TCP ports 465/995, and maybe 587, you'll need to configure some exceptions or take them off your rules list.

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Read environment variables in Node.js

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });

How to test if a DataSet is empty?

You should loop through all tables and test if table.Rows.Count is 0

bool IsEmpty(DataSet dataSet)
{
    foreach(DataTable table in dataSet.Tables)
        if (table.Rows.Count != 0) return false;

    return true;
}

Update: Since a DataTable could contain deleted rows RowState = Deleted, depending on what you want to achive, it could be a good idea to check the DefaultView instead (which does not contain deleted rows).

bool IsEmpty(DataSet dataSet)
{
    return !dataSet.Tables.Cast<DataTable>().Any(x => x.DefaultView.Count > 0);
}

HTML5 record audio to file

Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer

This streams PCM data but you could modify the code to stream mp3 or Speex

How to use vagrant in a proxy environment?

In PowerShell, you could set the http_proxy and https_proxy environment variables like so:

$env:http_proxy="http://proxy:3128"
$env:https_proxy="http://proxy:3128"

How to make a window always stay on top in .Net?

What is the other application you are trying to suppress the visibility of? Have you investigated other ways of achieving your desired effect? Please do so before subjecting your users to such rogue behaviour as you are describing: what you are trying to do sound rather like what certain naughty sites do with browser windows...

At least try to adhere to the rule of Least Surprise. Users expect to be able to determine the z-order of most applications themselves. You don't know what is most important to them, so if you change anything, you should focus on pushing the other application behind everything rather than promoting your own.

This is of course trickier, since Windows doesn't have a particularly sophisticated window manager. Two approaches suggest themselves:

  1. enumerating top-level windows and checking which process they belong to, dropping their z-order if so. (I'm not sure if there are framework methods for these WinAPI functions.)
  2. Fiddling with child process permissions to prevent it from accessing the desktop... but I wouldn't try this until the othe approach failed, as the child process might end up in a zombie state while requiring user interaction.

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I got the same same error.

I was using gmail account and Google's SMTP server to send emails. The problem was due to SMTP server refusing to authorize as it considered my web host (through whom I sent email) as an intruder.

I followed Google's process to identify my web host as an valid entity to send email through my account and problem was solved.

How to force a checkbox and text on the same line?

You can wrap the label around the input:

 **<label for="a"><input type="checkbox" id="a">a</label>**

This worked for me.

What are the differences between json and simplejson Python modules?

I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

How do I convert a String to an int in Java?

Apart from all these answer i found one new way, although it uses internally Integer.parseInt(),

By using

import javafx.util.converter.IntegerStringConverter;

new IntegerStringConverter().fromString("1234").intValue()

or

new IntegerStringConverter().fromString("1234")

Although it is a little bit costly as new objects get created, I just wanted to add as I learned a new way.

Just go through javafx.util.StringConverter<T> class it helps to convert any wrapper class value to a string or vice versa.

Android toolbar center title and custom font

I use this solution:

static void centerToolbarTitle(@NonNull final Toolbar toolbar) {
    final CharSequence title = toolbar.getTitle();
    final ArrayList<View> outViews = new ArrayList<>(1);
    toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
    if (!outViews.isEmpty()) {
        final TextView titleView = (TextView) outViews.get(0);
        titleView.setGravity(Gravity.CENTER);
        final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        toolbar.requestLayout();
        //also you can use titleView for changing font: titleView.setTypeface(Typeface);
    }
}

How do you create a Distinct query in HQL

Suppose you have a Customer Entity mapped to CUSTOMER_INFORMATION table and you want to get list of distinct firstName of customer. You can use below snippet to get the same.

Query distinctFirstName = session.createQuery("select ci.firstName from Customer ci group by ci.firstName");
Object [] firstNamesRows = distinctFirstName.list();

I hope it helps. So here we are using group by instead of using distinct keyword.

Also previously I found it difficult to use distinct keyword when I want to apply it to multiple columns. For example I want of get list of distinct firstName, lastName then group by would simply work. I had difficulty in using distinct in this case.

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

How to enable directory listing in apache web server

This one solved my issue which is SELinux setting:

chcon -R -t httpd_sys_content_t /home/*

Using jQuery to compare two arrays of Javascript objects

I was also looking for this today and found: http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD

Don't know if that's a good solution though they do mention some performance considerations taken into account.

I like the idea of a jQuery helper method. @David I'd rather see your compare method to work like:

jQuery.compare(a, b)

I doesn't make sense to me to be doing:

$(a).compare(b)

where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.

Also regarding sorting and 'caching' the sorted arrays:

  • I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
  • for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
  • More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.

It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)

In which case I think the code for it would be:

jQuery.extend({
    compare: function (arrayA, arrayB) {
        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        var a = jQuery.extend(true, [], arrayA);
        var b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] !== b[i]) { 
                return false;
            }
        }
        return true;
    }
});

var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];

jQuery.compare(a, b);
// false

jQuery.compare(b, c);
// true

// c is still unsorted [3, 4, 2]

RegEx to exclude a specific string constant

Try this regular expression:

^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$

It describes three cases:

  1. less than three arbitrary character
  2. exactly three characters, while either
    • the first is not A, or
    • the first is A but the second is not B, or
    • the first is A, the second B but the third is not C
  3. more than three arbitrary characters

Can I access constants in settings.py from templates in Django?

The example above from bchhun is nice except that you need to explicitly build your context dictionary from settings.py. Below is an UNTESTED example of how you could auto-build the context dictionary from all upper-case attributes of settings.py (re: "^[A-Z0-9_]+$").

At the end of settings.py:

_context = {} 
local_context = locals()
for (k,v) in local_context.items():
    if re.search('^[A-Z0-9_]+$',k):
        _context[k] = str(v)

def settings_context(context):
    return _context

TEMPLATE_CONTEXT_PROCESSORS = (
...
'myproject.settings.settings_context',
...
)

C - The %x format specifier

From http://en.wikipedia.org/wiki/Printf_format_string

use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

How to pass boolean parameter value in pipeline to downstream jobs?

Assuming

value: update_composer

was the issue, try

value: Boolean.valueOf(update_composer)

is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job

Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

How to get the first and last date of the current year?

Every year has the 1 st as First date and 31 as the last date what you have to do is only attach the year to that day and month for example:-

 SELECT '01/01/'+cast(year(getdate()) as varchar(4)) as [First Day],
 '12/31/'+cast(year(getdate()) as varchar(4)) as [Last Day]

Regex match entire words only

Use word boundaries:

/\b($word)\b/i

Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

How to convert JSON to CSV format and store in a variable

Write Csv.

function writeToCsv(dataToWrite, callback) {
    var dataToWrite;
    var fs = require('fs');
    dataToWrite = convertToCSV(dataToWrite);
    fs.writeFile('assets/distanceInfo.csv', dataToWrite, 'utf8', function (err) {
      if (err) {
        console.log('Some error occured - file either not saved or corrupted file saved.');
      } else{
        console.log('It\'s saved!');
      }
      callback("data_saved | assets/distanceInfo.csv")
    });
}

function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return str;
}

How to scroll UITableView to specific position

[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This will take your tableview to the first row.

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

Issue with background color and Google Chrome

I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.

IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.

PHP Fatal error: Using $this when not in object context

It seems to me to be a bug in PHP. The error

'Fatal error: Uncaught Error: Using $this when not in object context in'

appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:

Class_Name
{
    function foo()
    {
        $this->do_something(); // The error appears there.
    }
    function do_something()
    {
        ///
    }
}

While the error is here:

Class_Name::foo();

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

Foreign keys in mongo?

The purpose of ForeignKey is to prevent the creation of data if the field value does not match its ForeignKey. To accomplish this in MongoDB, we use Schema middlewares that ensure the data consistency.

Please have a look at the documentation. https://mongoosejs.com/docs/middleware.html#pre

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

Using UPDATE in stored procedure with optional parameters

ALTER PROCEDURE LN
    (
    @Firstname nvarchar(200)
)

AS
BEGIN

    UPDATE tbl_Students1
    SET Firstname=@Firstname 

    WHERE Studentid=3
END


exec LN 'Thanvi'

Recording video feed from an IP camera over a network

Motion is an alternative to Zoneminder. It has a steeper setup curve as everything is configured via config files.However, the config files are nicely commented and it's easier than it sounds. It's very reliable once running as well.

To add a Foscam camera (mentioned above) use the following syntax to stream the video from the camera.

netcam_url http://<IPADDRESS>/videostream.cgi?user=admin?pwd=

Where the user is admin with a blank password (the default for Foscam cameras).

For really high uptime/reliablity consider using a monitoring tool such as Monit. This works well with Motion.

NameError: name 'reduce' is not defined in Python

Or if you use the six library

from six.moves import reduce

Should I use alias or alias_method?

Apart from the syntax, the main difference is in the scoping:

# scoping with alias_method
class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias_method :name, :full_name
  end

end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Geeky geek'

In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.

class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias name full_name
  end
end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Johnnie Walker'

With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.

This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

'ls' in CMD on Windows is not recognized

enter image description here

First

Make a dir c:\command

Second Make a ll.bat

ll.bat

dir

Third Add to Path C:/commands enter image description here

How to make an app's background image repeat

Ok, here's what I've got in my app. It includes a hack to prevent ListViews from going black while scrolling.

drawable/app_background.xml:

<?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/actual_pattern_image"
        android:tileMode="repeat" />

values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="app_theme" parent="android:Theme">
    <item name="android:windowBackground">@drawable/app_background</item>
    <item name="android:listViewStyle">@style/TransparentListView</item>
    <item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
  </style>

  <style name="TransparentListView" parent="@android:style/Widget.ListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

  <style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

</resources>

AndroidManifest.xml:

//
<application android:theme="@style/app_theme">
//

Date formatting in WPF datagrid

Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

How do you make an anchor link non-clickable or disabled?

Try this:

$('a').contents().unwrap();

Remove empty strings from array while keeping record Without Loop?

arr = arr.filter(v => v);

as returned v is implicity converted to truthy

Activity restart on rotation Android

Put this below code in your Activity in Android Manifest.

android:configChanges="orientation"

This will not restart your activity when you would change orientation.

How to get full path of a file?

fp () {
PHYS_DIR=`pwd -P`
RESULT=$PHYS_DIR/$1
echo $RESULT | pbcopy
echo $RESULT
}

Copies the text to your clipboard and displays the text on the terminal window.

:)

(I copied some of the code from another stack overflow answer but cannot find that answer anymore)

Initial bytes incorrect after Java AES/CBC decryption

Here a solution without Apache Commons Codec's Base64:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AdvancedEncryptionStandard
{
    private byte[] key;

    private static final String ALGORITHM = "AES";

    public AdvancedEncryptionStandard(byte[] key)
    {
        this.key = key;
    }

    /**
     * Encrypts the given plain text
     *
     * @param plainText The plain text to encrypt
     */
    public byte[] encrypt(byte[] plainText) throws Exception
    {
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return cipher.doFinal(plainText);
    }

    /**
     * Decrypts the given byte array
     *
     * @param cipherText The data to decrypt
     */
    public byte[] decrypt(byte[] cipherText) throws Exception
    {
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return cipher.doFinal(cipherText);
    }
}

Usage example:

byte[] encryptionKey = "MZygpewJsCpRrfOr".getBytes(StandardCharsets.UTF_8);
byte[] plainText = "Hello world!".getBytes(StandardCharsets.UTF_8);
AdvancedEncryptionStandard advancedEncryptionStandard = new AdvancedEncryptionStandard(
        encryptionKey);
byte[] cipherText = advancedEncryptionStandard.encrypt(plainText);
byte[] decryptedCipherText = advancedEncryptionStandard.decrypt(cipherText);

System.out.println(new String(plainText));
System.out.println(new String(cipherText));
System.out.println(new String(decryptedCipherText));

Prints:

Hello world!
?;??LA+??b*
Hello world!

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

How do I turn off the mysql password validation?

You can configure this in mysql configuration file open /etc/my.cnf file In this file all the lines which is configuring the password policy make those commented like

#validate-password=FORCE_PLUS_PERMANENT
#validate_password_length=10
#validate_password_mixed_case_count=1
#validate_password_number_count=1
#validate_password_policy=MEDIUM

Uncomment and change the value of the properties you want to change.

How can I iterate over an enum?

If you knew that the enum values were sequential, for example the Qt:Key enum, you could:

Qt::Key shortcut_key = Qt::Key_0;
for (int idx = 0; etc...) {
    ....
    if (shortcut_key <= Qt::Key_9) {
        fileMenu->addAction("abc", this, SLOT(onNewTab()),
                            QKeySequence(Qt::CTRL + shortcut_key));
        shortcut_key = (Qt::Key) (shortcut_key + 1);
    }
}

It works as expected.

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

php date validation

Not sure if this answer the question or going to help....

$dt = '6/26/1970' ; // or // '6.26.1970' ;

$dt = preg_replace("([.]+)", "/", $dt);

$test_arr  = explode('/', $dt);

if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))

     { echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }

   else

     { echo "no good...format must be in mm/dd/yyyy"; }

Reading a binary file with python

In general, I would recommend that you look into using Python's struct module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for struct.unpack().

Do note that if there's "invisible" padding between/around the fields, you will need to figure that out and include it in the unpack() call, or you will read the wrong bits.

Reading the contents of the file in order to have something to unpack is pretty trivial:

import struct

data = open("from_fortran.bin", "rb").read()

(eight, N) = struct.unpack("@II", data)

This unpacks the first two fields, assuming they start at the very beginning of the file (no padding or extraneous data), and also assuming native byte-order (the @ symbol). The Is in the formatting string mean "unsigned integer, 32 bits".