Programs & Examples On #Winmail.dat

How to get 0-padded binary representation of an integer in java?

Here a new answer for an old post.

To pad a binary value with leading zeros to a specific length, try this:

Integer.toBinaryString( (1 << len) | val ).substring( 1 )

If len = 4 and val = 1,

Integer.toBinaryString( (1 << len) | val )

returns the string "10001", then

"10001".substring( 1 )

discards the very first character. So we obtain what we want:

"0001"

If val is likely to be negative, rather try:

Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

For most browsers released after 2017:

You can use the position: sticky. See https://caniuse.com/#feat=css-sticky.

There is no need for a fixed width column.

Run the code snippet below to see how it works.

_x000D_
_x000D_
.tscroll {_x000D_
  width: 400px;_x000D_
  overflow-x: scroll;_x000D_
  margin-bottom: 10px;_x000D_
  border: solid black 1px;_x000D_
}_x000D_
_x000D_
.tscroll table td:first-child {_x000D_
  position: sticky;_x000D_
  left: 0;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.tscroll td, .tscroll th {_x000D_
  border-bottom: dashed #888 1px;_x000D_
}
_x000D_
<html>_x000D_
<div class="tscroll">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th></th>_x000D_
        <th colspan="5">Heading 1</th>_x000D_
        <th colspan="8">Heading 2</th>_x000D_
        <th colspan="4">Heading 3</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>9:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>10:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>11:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>12:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>13:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>14:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>15:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>16:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>17:00</td>_x000D_
        <td>AAA</td>_x000D_
        <td>BBB</td>_x000D_
        <td>CCC</td>_x000D_
        <td>DDD</td>_x000D_
        <td>EEE</td>_x000D_
        <td>FFF</td>_x000D_
        <td>GGG</td>_x000D_
        <td>HHH</td>_x000D_
        <td>III</td>_x000D_
        <td>JJJ</td>_x000D_
        <td>KKK</td>_x000D_
        <td>LLL</td>_x000D_
        <td>MMM</td>_x000D_
        <td>NNN</td>_x000D_
        <td>OOO</td>_x000D_
        <td>PPP</td>_x000D_
        <td>QQQ</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
    </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

I just want to add my solution:

I use german umlauts like ö, ü, ä and got the same error.
@Jarek Zmudzinski just told you how it works, but here is mine:

Add this code to the top of your Controller: # encoding: UTF-8
(for example to use flash message with umlauts)

example of my Controller:

# encoding: UTF-8
class UserController < ApplicationController

Now you can use ö, ä ,ü, ß, "", etc.

Casting a number to a string in TypeScript

Use the "+" symbol to cast a string to a number.

window.location.hash = +page_number;

Can't accept license agreement Android SDK Platform 24

You can also follow the "official" way. Run "sdkmanager --licenses" within tools/bin folder of Android SDK installation and accept all licenses. Done!

c:\android-sdk\tools\bin>sdkmanager --licenses

For macOS or Linux it's the same command.

How to change the MySQL root account password on CentOS7?

Use the below Steps to reset the password.

$ sudo systemctl start mysqld

Reset the MySql server root password.

$sudo grep 'temporary password' /var/log/mysqld.log

Output Something like-:

 10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa

Use the above password during reset mysql_secure_installation process.

<pre>
    $ sudo mysql_secure_installation
</pre>
   Securing the MySQL server deployment.

   Enter password for user root: 

You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.

$ mysql -u root -p

http://gotechnies.com/install-latest-mysql-5-7-rhelcentos-7/

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

How can I plot with 2 different y-axes?

Another alternative which is similar to the accepted answer by @BenBolker is redefining the coordinates of the existing plot when adding a second set of points.

Here is a minimal example.

Data:

x  <- 1:10
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)

Plot:

par(mar=c(5,5,5,5)+0.1, las=1)

plot.new()
plot.window(xlim=range(x), ylim=range(y1))
points(x, y1, col="red", pch=19)
axis(1)
axis(2, col.axis="red")
box()

plot.window(xlim=range(x), ylim=range(y2))
points(x, y2, col="limegreen", pch=19)
axis(4, col.axis="limegreen")

example

Getting a map() to return a list in Python 3.x

In addition to above answers in Python 3, we may simply create a list of result values from a map as

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

We may generalize by another example where I was struck, operations on map can also be handled in similar fashion like in regex problem, we can write function to obtain list of items to map and get result set at the same time. Ex.

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

PHP cURL HTTP PUT

Using Postman for Chrome, selecting CODE you get this... And works

_x000D_
_x000D_
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
  CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
  CURLOPT_RETURNTRANSFER => true,_x000D_
  CURLOPT_ENCODING => "",_x000D_
  CURLOPT_MAXREDIRS => 10,_x000D_
  CURLOPT_TIMEOUT => 30,_x000D_
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
  CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"[email protected]\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
  CURLOPT_HTTPHEADER => array(_x000D_
    "cache-control: no-cache",_x000D_
    "content-type: application/json",_x000D_
    "x-api-key: whateveriyouneedinyourheader"_x000D_
  ),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
  echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
  echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter id set to user instance id attribute.

How to create dictionary and add key–value pairs dynamically?

var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with 2 properties (called key and value) and inserting it (using push()) into the array.


Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties. Don't ask me why that structure was required, but it's the one that was asked for.

But, but, if what you want in a plain JS object - and not the structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names. You can just do this:

// object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

var dict = {};

// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// but this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Date object gets converted to its string representation:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]" which doesn't make for a non-unique key. So be wary of something like:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]".

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. And you can do the same:

// a simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString.)

So when trying to use objects as keys, JS will use the object's own toString implementation, if any, or use the default string representation.

how to run python files in windows command prompt?

First set path of python https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows

and run python file

python filename.py

command line argument with python

python filename.py command-line argument

Is it possible to get an Excel document's row count without loading the entire document into memory?

https://pythonhosted.org/pyexcel/iapi/pyexcel.sheets.Sheet.html see : row_range() Utility function to get row range

if you use pyexcel, can call row_range get max rows.

python 3.4 test pass.

An existing connection was forcibly closed by the remote host

For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
{
    var buffer = new byte[1024];
    int read;

    while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
    {
        await content.WriteAsync(buffer, 0, read);
        await content.FlushAsync();
    }
}

After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:

using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
{
    await remoteStream.CopyToAsync(content);
}

CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

"Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."

The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

ReactJS map through Object

I am not sure why Aleksey Potapov marked the answer for deletion but it did solve my problem. Using Object.keys(subjects).map gave me an array of strings containing the name of each object, while Object.entries(subjects).map gave me an array with all data inside witch it's what I wanted being able to do this:

const dataInfected = Object.entries(dataDay).map((day, i) => {
    console.log(day[1].confirmed);
});

I hope it helps the owner of the post or someone else passing by.

Can I convert a C# string value to an escaped string literal

There's a method for this in Roslyn's Microsoft.CodeAnalysis.CSharp package on nuget :

    private static string ToLiteral(string valueTextForCompiler)
    {
        return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
    }

Obviously this didn't exist at the time of the original question, but might help people who end up here from Google.

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

How to install a plugin in Jenkins manually

Yes, you can. Download the plugin (*.hpi file) and put it in the following directory:

<jenkinsHome>/plugins/

Afterwards you will need to restart Jenkins.

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

Try running fuser command

[root@guest2 ~]# fuser -mv /home

USER PID ACCESS COMMAND

/home: root 2919 f.... automount

[root@guest2 ~]# kill -9 2919

autofs service is known to cause this issue.

You can use command

#service autofs stop

And try again.

How to get N rows starting from row M from sorted table in T-SQL

Find id for row N Then get the top M rows that have an id greater than or equal to that

declare @N as int
set @N = 2
declare @M as int
set @M = 3

declare @Nid as int

set @Nid = max(id)
from
  (select top @N *
from MyTable
order by id)

select top @M *
from MyTable
where id >= @Nid
order by id

Something like that ... but I've made some assumptions here (e.g. you want to order by id)

How to connect to a docker container from outside the host (same network) [Windows]

TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.

For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.

However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.

Is it .yaml or .yml?

EDIT:

So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?

This question could be:

  1. A request for advice; or

  2. A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.

People differ in their predilection for following:

  1. Official advice; or

  2. The preponderance of practice.

Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!

In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.

By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.

Whatever your personal inclination, be it to follow one path or the other, I do not object.

(End of edit.)

The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).

As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.

As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.

Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."

Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."

As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.

The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.

Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!

Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?

Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).

Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.

Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.

Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.

Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".

The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.

".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.

Batch file. Delete all files and folders in a directory

Use

set dir="Your Folder Path Here"
rmdir /s %dir%
mkdir %dir%

This version deletes without asking:

set dir="Your Folder Here"
rmdir /s /q %dir%
mkdir %dir%

Example:

set dir="C:\foo1\foo\foo\foo3"
rmdir /s /q %dir%
mkdir %dir%

This will clear C:\foo1\foo\foo\foo3.

(I would like to mention Abdullah Sabouin's answer. There was a mix up about me copying him. I did not notice his post. I would like to thank you melpomene for pointing out errors!)

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

Bootstrap visible and hidden classes not working properly

No CSS required, visible class should like this: visible-md-block not just visible-md and the code should be like this:

<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">

        </div>
    </div>
</div>

<div class="mobile hidden-md hidden-lg ">
    test
</div>

Extra css is not required at all.

Determine number of pages in a PDF file

One Line:

int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;

Recommended: ITEXTSHARP

ImportError: No module named PytQt5

pip install pyqt5 for python3 for ubuntu

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I would recommend giving the LI a background-image and padding-left. The list-style-image attribute is flakey in cross-browser environments, and adding an extra element, such as a span, is unneccessary. So your code would end up looking something like this:

li {
  background:url(../images/bullet.png) 0 0 no-repeat;
  list-style:none;
  padding-left:10px;
}

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

What is the difference between Bootstrap .container and .container-fluid classes?

From a display perspective .container gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs, .col-sm, .col, and .col-lg.

What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.

When using .container-fluid because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.

Why I got " cannot be resolved to a type" error?

for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...

But thank you for your response:)

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Android 6.0 at least, the ARM Translation thing is apparently unnecessary.

Just grab an x86 + Android 6.0 package (nano is fine) from OpenGApps and install by dragging-and-dropping and telling it to flash.

It seems the ARM translation thing was previously required, before the x86 package was available. You might still need the ARM translation if you want to install ARM-only apps though.

Positioning <div> element at center of screen

If you have a fixed div just absolute position it at 50% from the top and 50% left and negative margin top and left of half the height and width respectively. Adjust to your needs:

div {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 500px;
    height: 300px;
    margin-left: -250px;
    margin-top: -150px;
}

'python' is not recognized as an internal or external command

i solved this by running CMD in administration mode, so try this.

How to evaluate a math expression given in string form?

The correct way to solve this is with a lexer and a parser. You can write simple versions of these yourself, or those pages also have links to Java lexers and parsers.

Creating a recursive descent parser is a really good learning exercise.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Xcode variables

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

Writing JSON object to a JSON file with fs.writeFileSync

Make the json human readable by passing a third argument to stringify:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));

Python, add items from txt file into a list

This should be a good case for map and lambda

with open ('names.txt','r') as f :
   Names = map (lambda x : x.strip(),f_in.readlines())

I stand corrected (or at least improved). List comprehensions is even more elegant

with open ('names.txt','r') as f :
    Names = [name.rstrip() for name in f]

iOS: set font size of UILabel Programmatically

In Swift 3.0, you could use this code below:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView

Server.Transfer Vs. Response.Redirect

Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.

Server.Transfer() does not change the address bar. You cannot hit back.

I use Server.Transfer() when I don't want the user to see where I am going. Sometimes on a "loading" type page.

Otherwise I'll always use Response.Redirect().

How to remove line breaks from a file in Java?

Linebreaks are not the same under windows/linux/mac. You should use System.getProperties with the attribute line.separator.

How can I send mail from an iPhone application

Heres a Swift version:

import MessageUI

class YourVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if MFMailComposeViewController.canSendMail() {
            var emailTitle = "Vea Software Feedback"
            var messageBody = "Vea Software! :) "
            var toRecipents = ["[email protected]"]
            var mc:MFMailComposeViewController = MFMailComposeViewController()
            mc.mailComposeDelegate = self
            mc.setSubject(emailTitle)
            mc.setMessageBody(messageBody, isHTML: false)
            mc.setToRecipients(toRecipents)
            self.presentViewController(mc, animated: true, completion: nil)
        } else {
            println("No email account found")
        }
    }
}

extension YourVC: MFMailComposeViewControllerDelegate {
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
        switch result.value {
        case MFMailComposeResultCancelled.value:
            println("Mail Cancelled")
        case MFMailComposeResultSaved.value:
            println("Mail Saved")
        case MFMailComposeResultSent.value:
            println("Mail Sent")
        case MFMailComposeResultFailed.value:
            println("Mail Failed")
        default:
            break
        }
        self.dismissViewControllerAnimated(false, completion: nil)
    }
}

Source

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

How do I add items to an array in jQuery?

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

Constants in Kotlin -- what's a recommended way to create them?

Like val, variables defined with the const keyword are immutable. The difference here is that const is used for variables that are known at compile-time.

Declaring a variable const is much like using the static keyword in Java.

Let's see how to declare a const variable in Kotlin:

const val COMMUNITY_NAME = "wiki"

And the analogous code written in Java would be:

final static String COMMUNITY_NAME = "wiki";

Adding to the answers above -

@JvmField an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.

 @JvmField
 val COMMUNITY_NAME: "Wiki"

Static fields

Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.

Usually these fields are private but they can be exposed in one of the following ways:

  • @JvmField annotation;
  • lateinit modifier;
  • const modifier.

More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields

Is it possible to ping a server from Javascript?

You can't directly "ping" in javascript. There may be a few other ways:

  • Ajax
  • Using a java applet with isReachable
  • Writing a serverside script which pings and using AJAX to communicate to your serversidescript
  • You might also be able to ping in flash (actionscript)

What does 'synchronized' mean?

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo, you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo, or worse, it may only be half changed. This would not be what you logically expect.

Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:

Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.

You must enable the openssl extension to download files via https

Verify you are editing the correct php.ini file.

Reference: https://github.com/composer/composer/issues/1440

"WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-X.Y.Z\php.ini to enable it for the CLI."

Setting up JUnit with IntelliJ IDEA

Basically, you only need junit.jar on the classpath - and here's a quick way to do it:

  1. Make sure you have a source folder (e.g. test) marked as a Test Root.

  2. Create a test, for example like this:

    public class MyClassTest {
        @Test
        public void testSomething() {
    
        }
    }
    
  3. Since you haven't configured junit.jar (yet), the @Test annotation will be marked as an error (red), hit f2 to navigate to it.

  4. Hit alt-enter and choose Add junit.jar to the classpath

There, you're done! Right-click on your test and choose Run 'MyClassTest' to run it and see the test results.

Maven Note: Altervatively, if you're using maven, at step 4 you can instead choose the option Add Maven Dependency..., go to the Search for artifact pane, type junit and take whichever version (e.g. 4.8 or 4.9).

Calculating the sum of two variables in a batch script

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

In vb.net, how to get the column names from a datatable

This is how to retrieve a Column Name from a DataColumn:

MyDataTable.Columns(1).ColumnName 

To get the name of all DataColumns within your DataTable:

Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
  name(i) = column.ColumnName
  i += 1
Next

References

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

How do I split a string with multiple separators in JavaScript?

I use regexp:

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';

var strNew = str.match(/\w+/g);

// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

PSEXEC, access denied errors

You can try the command

net use \\computername\ipc$ /user:adminname password

to get admin permissions on remote PC before use psexec.

How to zoom in/out an UIImage object when user pinches screen?

Shafali and JRV's answers extended to include panning and pinch to zoom:

#define MINIMUM_SCALE 0.5
#define MAXIMUM_SCALE 6.0
@property CGPoint translation;


- (void)pan:(UIPanGestureRecognizer *)gesture {
    static CGPoint currentTranslation;
    static CGFloat currentScale = 0;
    if (gesture.state == UIGestureRecognizerStateBegan) {
        currentTranslation = _translation;
        currentScale = self.view.frame.size.width / self.view.bounds.size.width;
    }
    if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateChanged) {

        CGPoint translation = [gesture translationInView:self.view];

        _translation.x = translation.x + currentTranslation.x;
        _translation.y = translation.y + currentTranslation.y;
        CGAffineTransform transform1 = CGAffineTransformMakeTranslation(_translation.x , _translation.y);
        CGAffineTransform transform2 = CGAffineTransformMakeScale(currentScale, currentScale);
        CGAffineTransform transform = CGAffineTransformConcat(transform1, transform2);
        self.view.transform = transform;
    }
}


- (void)pinch:(UIPinchGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateChanged) {
//        NSLog(@"gesture.scale = %f", gesture.scale);

        CGFloat currentScale = self.view.frame.size.width / self.view.bounds.size.width;
        CGFloat newScale = currentScale * gesture.scale;

        if (newScale < MINIMUM_SCALE) {
            newScale = MINIMUM_SCALE;
        }
        if (newScale > MAXIMUM_SCALE) {
            newScale = MAXIMUM_SCALE;
        }

        CGAffineTransform transform1 = CGAffineTransformMakeTranslation(_translation.x, _translation.y);
        CGAffineTransform transform2 = CGAffineTransformMakeScale(newScale, newScale);
        CGAffineTransform transform = CGAffineTransformConcat(transform1, transform2);
        self.view.transform = transform;
        gesture.scale = 1;
    }
}

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How to concatenate two MP4 files using FFmpeg?

Here is a script (works for an arbitrary number of specified files (not just all in the working directory), without additional files, also works for .mov; tested on macOS):

#!/bin/bash

if [ $# -lt 1 ]; then
    echo "Usage: `basename $0` input_1.mp4 input_2.mp4 ... output.mp4"
    exit 0
fi

ARGS=("$@") # determine all arguments
output=${ARGS[${#ARGS[@]}-1]} # get the last argument (output file)
unset ARGS[${#ARGS[@]}-1] # drop it from the array
(for f in "${ARGS[@]}"; do echo "file '$f'"; done) | ffmpeg -protocol_whitelist file,pipe -f concat -safe 0 -i pipe: -vcodec copy -acodec copy $output

How to calculate the median of an array?

And nobody paying attention when list contains only one element (list.size == 1). All your answers will crash with index out of bound exception, because integer division returns zero (1 / 2 = 0). Correct answer (in Kotlin):

MEDIAN("MEDIAN") {

        override fun calculate(values: List<BigDecimal>): BigDecimal? {
            if (values.size == 1) {
                return values.first()
            }
            if (values.size > 1) {
                val valuesSorted = values.sorted()
                val mid = valuesSorted.size / 2
                return if (valuesSorted.size % 2 != 0) {
                    valuesSorted[mid]
                } else {
                    AVERAGE.calculate(listOf(valuesSorted[mid - 1], valuesSorted[mid]))
                }
            }
            return null
        }
    },

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

SDK Manager.exe doesn't work

I add new environment variable "ANDROID_SDK_HOME" and set it, like my path to android SDK folder (c:/Android) and it's work!

There is no tracking information for the current branch

$ git branch --set-upstream-to=heroku/master master and

$ git pull

worked for me!

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

You can't use {{}} when using angular directives for binding with ng-model but for binding non-angular attributes you would have to use {{}}..

Eg:

ng-show="my-model"
title = "{{my-model}}"

Where can I get a list of Ansible pre-defined variables?

I use this simple playbook:

---
# vars.yml
#
# Shows the value of all variables/facts.
#
# Example:
#
#   ansible-playbook vars.yml -e 'hosts=localhost'
#
- hosts: localhost
  tasks:
    - fail: "You must specify a value for `hosts` variable - e.g.: ansible-playbook vars.yml -e 'hosts=localhost'"
      when: hosts is not defined

- hosts: "{{ hosts }}"
  tasks:
    - debug: var=vars
    - debug: var=hostvars[inventory_hostname]

Java Programming: call an exe from Java and passing parameters

import java.io.IOException;
import java.lang.ProcessBuilder;

public class handlingexe {
    public static void main(String[] args) throws IOException {
        ProcessBuilder p = new ProcessBuilder();
        System.out.println("Started EXE");
        p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");   

        p.start();
        System.out.println("Started EXE"); 
    }
}

Delete item from state array in react

I also had a same requirement to delete an element from array which is in state.

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

Fastest method of screen capturing on Windows

In my Impression, the GDI approach and the DX approach are different in its nature. painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.

  1. WHY DX quicker? in DX (or graphics world), a more mature method called double buffer rendering is applied, where two buffers are present, when present the front buffer to the hardware, you can render to the other buffer as well, then after the frame 1 is finished rendering, the system swap to the other buffer( locking it for presenting to hardware , and release the previous buffer ), in this way the rendering inefficiency is greatly improved.
  2. WHY turning down hardware acceleration quicker? although with double buffer rendering, the FPS is improved, but the time for rendering is still limited. modern graphic hardware usually involves a lot of optimization during rendering typically like anti-aliasing, this is very computation intensive, if you don't require that high quality graphics, of course you can just disable this option. and this will save you some time.

I think what you really need is a replay system, which I totally agree with what people discussed.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had a similar error on my side when I was using JDBC in Java code.

According to this website (the second awnser) it suggest that you are trying to execute the query with a missing parameter.

For instance :

exec SomeStoredProcedureThatReturnsASite( :L_kSite );

You are trying to execute the query without the last parameter.

Maybe in SQLPlus it doesn't have the same requirements, so it might have been a luck that it worked there.

Can't connect to MySQL server on 'localhost' (10061) after Installation

This is the easiest solution and worked for me.

  • Go to where you downloaded "mysql-installer-web-community-8.0.19.0.msi", file for installing mysql.
  • Run this by double clicking on it. (No need to uninstall anything)
  • Click on "reconfigure" beside the MySql server.
  • Agree everything which comes in middle, provide password for root where asked.
  • Finish. That's it you're good to go.

Checking if a list of objects contains a property with a specific value

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

Create list of single item repeated N times

>>> [5] * 4
[5, 5, 5, 5]

Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list!

>>> x=[5]
>>> y=[x] * 4
>>> y
[[5], [5], [5], [5]]
>>> y[0][0] = 6
>>> y
[[6], [6], [6], [6]]

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

Javascript ajax call on page onload

You can use jQuery to do that for you.

 $(document).ready(function() {
   // put Ajax here.
 });

Check it here:

http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29

Create a file if it doesn't exist

Here's a quick two-liner that I use to quickly create a file if it doesn't exists.

if not os.path.exists(filename):
    open(filename, 'w').close()

Regex pattern to match at least 1 number and 1 character in a string

While the accepted answer is correct, I find this regex a lot easier to read:

REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"

Is there 'byte' data type in C++?

Using C++11 there is a nice version for a manually defined byte type:

enum class byte : std::uint8_t {};

That's at least what the GSL does.

Starting with C++17 (almost) this very version is defined in the standard as std::byte (thanks Neil Macintosh for both).

How can I reset or revert a file to a specific revision?

First Reset Head For Target File

git reset HEAD path_to_file

Second Checkout That File

git checkout -- path_to_file

Android: keep Service running when app is killed

All the answers seem correct so I'll go ahead and give a complete answer here.

Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart following that.

Now lets jump into code.


Create your Service in YourService.java

Note the onCreate() method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.

The this.sendBroadcast(broadcastIntent); in the onDestroy() method is the statement which asynchronously sends a broadcast with the action name "restartservice". We'll be using this later as a trigger to restart our service.

Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log while incrementing itself every time it prints.

public class YourService extends Service {
public int counter=0;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stoptimertask();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
    }



    private Timer timer;
    private TimerTask timerTask;
    public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                Log.i("Count", "=========  "+ (counter++));
            }
        };
        timer.schedule(timerTask, 1000, 1000); //
    }

    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java

The broadcast with the action name "restartservice" which you just defined in YourService.java is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver in Android.

We override the built-in onRecieve() method in BroadcastReceiver to add the statement which will restart the service. The startService() will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService() for higher versions and show a continuous notification to keep the service running.

public class Restarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Broadcast Listened", "Service tried to stop");
        Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, YourService.class));
        } else {
            context.startService(new Intent(context, YourService.class));
        }
    }
}

Define your MainActivity.java to call the service on app start.

Here we define a separate isMyServiceRunning() method to check the current status of the background service. If the service is not running, we start it by using startService().

Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.

Note that in onDestroy() we are dedicatedly calling stopService(), so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy() method in YourService.java

public class MainActivity extends AppCompatActivity {
    Intent mServiceIntent;
    private YourService mYourService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mYourService = new YourService();
        mServiceIntent = new Intent(this, mYourService.getClass());
        if (!isMyServiceRunning(mYourService.getClass())) {
            startService(mServiceIntent);
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                Log.i ("Service status", "Running");
                return true;
            }
        }
        Log.i ("Service status", "Not running");
        return false;
    }


    @Override
    protected void onDestroy() {
        //stopService(mServiceIntent);
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        super.onDestroy();
    }
}

Finally register them in your AndroidManifest.xml

All of the above three classes need to be separately registered in AndroidManifest.xml.

Note that we define an intent-filter with the action name as "restartservice" where the Restarter.java is registered as a receiver. This ensures that our custom BroadcastReciever is called whenever the system encounters a broadcast with the given action name.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <receiver
        android:name="Restarter"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="restartservice" />
        </intent-filter>
    </receiver>

    <activity android:name="MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="YourService"
        android:enabled="true" >
    </service>
</application>

This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop the app from Application Settings.

UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy() of the service is called, which might not be the case certain times, which I was unaware of. Thanks.

How to study design patterns?

I recommend HeadFirst DesignPattern. Reading the book is not enough, after assimilating the concepts you need to findout the answers for lot of questions arise in your mind and try to findout the real life applications where in these patterns can be used. I am doing the same and started asking questions even those questions look silly.

python dictionary sorting in descending order based on values

Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

How to list all available Kafka brokers in a cluster?

On MacOS, can try:

brew tap let-us-go/zkcli
brew install zkcli

zkcli ls /brokers/ids
zkcli get /brokers/ids/1

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Rails 4 - passing variable to partial

Either

render partial: 'user', locals: {size: 30}

Or

render 'user', size: 30

To use locals, you need partial. Without the partial argument, you can just list variables directly (not within locals)

how to rotate text left 90 degree and cell size is adjusted according to text in html

You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>.

Also make sure you change your id #rotate to a class since you have multiple.

A 4x3 table with the headers in the first column rotated by 90 degrees

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
  visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
  /* FF3.5+ */_x000D_
  -moz-transform: rotate(-90.0deg);_x000D_
  /* Opera 10.5 */_x000D_
  -o-transform: rotate(-90.0deg);_x000D_
  /* Saf3.1+, Chrome */_x000D_
  -webkit-transform: rotate(-90.0deg);_x000D_
  /* IE6,IE7 */_x000D_
  filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
  /* IE8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
  /* Standard */_x000D_
  transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>10kg</div>_x000D_
    </td>_x000D_
    <td>B</td>_x000D_
    <td>C</td>_x000D_
    <td>D</td>_x000D_
    <td>E</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>20kg</div>_x000D_
    </td>_x000D_
    <td>G</td>_x000D_
    <td>H</td>_x000D_
    <td>I</td>_x000D_
    <td>J</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>30kg</div>_x000D_
    </td>_x000D_
    <td>L</td>_x000D_
    <td>M</td>_x000D_
    <td>N</td>_x000D_
    <td>O</td>_x000D_
  </tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

JavaScript

The equivalent to the above in pure JavaScript is as follows:

jsFiddle

window.addEventListener('load', function () {
    var rotates = document.getElementsByClassName('rotate');
    for (var i = 0; i < rotates.length; i++) {
        rotates[i].style.height = rotates[i].offsetWidth + 'px';
    }
});

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

html <input type="text" /> onchange event not working

try onpropertychange. it only works for IE.

How do browser cookie domains work?

The previous answers are a little outdated.

RFC 6265 was published in 2011, based on the browser consensus at that time. Since then, there has been some complication with public suffix domains. I've written an article explaining the current situation - http://bayou.io/draft/cookie.domain.html

To summarize, rules to follow regarding cookie domain:

  • The origin domain of a cookie is the domain of the originating request.

  • If the origin domain is an IP, the cookie's domain attribute must not be set.

  • If a cookie's domain attribute is not set, the cookie is only applicable to its origin domain.

  • If a cookie's domain attribute is set,

    • the cookie is applicable to that domain and all its subdomains;
    • the cookie's domain must be the same as, or a parent of, the origin domain
    • the cookie's domain must not be a TLD, a public suffix, or a parent of a public suffix.

It can be derived that a cookie is always applicable to its origin domain.

The cookie domain should not have a leading dot, as in .foo.com - simply use foo.com

As an example,

  • x.y.z.com can set a cookie domain to itself or parents - x.y.z.com, y.z.com, z.com. But not com, which is a public suffix.
  • a cookie with domain=y.z.com is applicable to y.z.com, x.y.z.com, a.x.y.z.com etc.

Examples of public suffixes - com, edu, uk, co.uk, blogspot.com, compute.amazonaws.com

How to align text below an image in CSS?

Instead of images i choose background option:

HTML:

  <div class="class1">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>    
  <div class="class2">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>
  <div class="class3">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>        

CSS:

  .class1 {

    background: url("Some.png") no-repeat top center;
    text-align: center;

   }

  .class2 {

    background: url("Some2.png") no-repeat top center;
    text-align: center;

   }

  .class3 {

    background: url("Some3.png") no-repeat top center;
    text-align: center;

   }

How can I force a hard reload in Chrome for Android

How to reset all data for a given URL / Website on Chrome Mobile for android:

1 - Open the Chrome menu, and tap on the "i (info)" icon

one

2 - tap "Site settings"

two

3 - Tap the trashcan icon

three

That's it, even the most deeply ensconsed service worker for that URL will now die.

How to split an integer into an array of digits?

like @nd says but using the built-in function of int to convert to a different base

>>> [ int(i,16) for i in '0123456789ABCDEF' ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> [int(i,2) for i in "100 010 110 111".split()]
[4, 2, 6, 7]

I don't know what is the final objective but take a look also inside the decimal module of python for doing stuff like

>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


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

My Custom Toolbar XML

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

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

  1. Delete early created devices.
  2. Close Android studio.
  3. Open: Control panel -> System & security -> System -> Advanced system settings -> Environment variables.
  4. Create New variable "ANDROID_SDK_HOME" and set new path(in my case it was F:\Coding2019\Android\AVDdevices). Push 'ok'.
  5. Open Android Studio.
  6. Create new device. After creating in drop-down menu click "View Details" to see new path of new AVD.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

How to use a WSDL

Use WSDL.EXE utility to generate a Web Service proxy from WSDL.

You'll get a long C# source file that contains a class that looks like this:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
    ...
}

In your client-side, Web-service-consuming code:

  1. instantiate MyService.
  2. set its Url property
  3. invoke Web methods

How to create a zip archive of a directory in Python?

You probably want to look at the zipfile module; there's documentation at http://docs.python.org/library/zipfile.html.

You may also want os.walk() to index the directory structure.

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

When to use margin vs padding in CSS

It's good to know the differences between margin and padding. Here are some differences:

  • Margin is outer space of an element, while padding is inner space of an element.

  • Margin is the space outside the border of an element, while padding is the space inside the border of it.

  • Margin accepts the value of auto: margin: auto, but you can't set padding to auto.

  • Margin can be set to any number, but padding must be non-negative.

  • When you style an element, padding will also be affected (e.g. background color), but not margin.

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Illegal Escape Character "\"

You can use:

\\

That's ok, for example:

if (invName.substring(j,k).equals("\\")) {
    copyf=invName.substring(0,j);
}

running a command as a super user from a python script

Another way is to make your user a password-less sudo user.

Type the following on command line:

sudo visudo

Then add the following and replace the <username> with yours:

<username> ALL=(ALL) NOPASSWD: ALL

This will allow the user to execute sudo command without having to ask for password (including application launched by the said user. This might be a security risk though

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

I handle the ajax request by using Selenium and the Firefox web driver. It is not that fast if you need the crawler as a daemon, but much better than any manual solution. I wrote a short tutorial here for reference

How can I list all foreign keys referencing a given table in SQL Server?

The most Simplest one is by using sys.foreign_keys_columns in SQL. Here the table contains the Object ids of all the foreign keys wrt their Referenced column ID Referenced Table ID as well as the Referencing Columns and Tables. As the Id's remains constant the result will be reliable for further modifications in Schema as well as tables.

Query:

SELECT    
OBJECT_NAME(fkeys.constraint_object_id) foreign_key_name
,OBJECT_NAME(fkeys.parent_object_id) referencing_table_name
,COL_NAME(fkeys.parent_object_id, fkeys.parent_column_id) referencing_column_name
,OBJECT_SCHEMA_NAME(fkeys.parent_object_id) referencing_schema_name
,OBJECT_NAME (fkeys.referenced_object_id) referenced_table_name
,COL_NAME(fkeys.referenced_object_id, fkeys.referenced_column_id) 
referenced_column_name
,OBJECT_SCHEMA_NAME(fkeys.referenced_object_id) referenced_schema_name
FROM sys.foreign_key_columns AS fkeys

We can also add filter by using 'where'

WHERE OBJECT_NAME(fkeys.parent_object_id) = 'table_name' AND 
OBJECT_SCHEMA_NAME(fkeys.parent_object_id) = 'schema_name'

Add text at the end of each line

Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.

sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

As far as I am aware of, YOU CANNOT. CSS is about style and image's src is content.

contenteditable change events

To avoid timers and "save" buttons, you may use blur event wich fires when the element loses focus. but to be sure that the element was actually changed (not just focused and defocused), its content should be compared against its last version. or use keydown event to set some "dirty" flag on this element.

Succeeded installing but could not start apache 2.4 on my windows 7 system

if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.

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

Apart from the previous answers, I would like to add several functions. These are results while you use them:

public static void main(String[] args) {
  System.out.println(parseIntOrDefault("123", 0)); // 123
  System.out.println(parseIntOrDefault("aaa", 0)); // 0
  System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
  System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}

Implementation:

public static int parseIntOrDefault(String value, int defaultValue) {
  int result = defaultValue;
  try {
    result = Integer.parseInt(value);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex, endIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

How to fix 'android.os.NetworkOnMainThreadException'?

Android Jetpack introduced WorkManager,which fixes the problem of background service restriction in Oreo and use of Alarm Manager below Lolipop and JobScheduler above Lolipop.

Please use WorkManager to run tasks on background thread and it's continue to run even after user closes the app.

How to compile Tensorflow with SSE4.2 and AVX instructions?

To compile TensorFlow with SSE4.2 and AVX, you can use directly

bazel build --config=mkl --config="opt" --copt="-march=broadwell" --copt="-O3" //tensorflow/tools/pip_package:build_pip_package

Source: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/docker/Dockerfile.devel-cpu-mkl

How to stop EditText from gaining focus at Activity startup in Android

using the information provided by other posters, I used the following solution:

in the layout XML

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"/>

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

in onCreate()

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

and finally, in onResume()

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

How should I log while using multiprocessing in Python?

I just now wrote a log handler of my own that just feeds everything to the parent process via a pipe. I've only been testing it for ten minutes but it seems to work pretty well.

(Note: This is hardcoded to RotatingFileHandler, which is my own use case.)


Update: @javier now maintains this approach as a package available on Pypi - see multiprocessing-logging on Pypi, github at https://github.com/jruere/multiprocessing-logging


Update: Implementation!

This now uses a queue for correct handling of concurrency, and also recovers from errors correctly. I've now been using this in production for several months, and the current version below works without issue.

from logging.handlers import RotatingFileHandler
import multiprocessing, threading, logging, sys, traceback

class MultiProcessingLog(logging.Handler):
    def __init__(self, name, mode, maxsize, rotate):
        logging.Handler.__init__(self)

        self._handler = RotatingFileHandler(name, mode, maxsize, rotate)
        self.queue = multiprocessing.Queue(-1)

        t = threading.Thread(target=self.receive)
        t.daemon = True
        t.start()

    def setFormatter(self, fmt):
        logging.Handler.setFormatter(self, fmt)
        self._handler.setFormatter(fmt)

    def receive(self):
        while True:
            try:
                record = self.queue.get()
                self._handler.emit(record)
            except (KeyboardInterrupt, SystemExit):
                raise
            except EOFError:
                break
            except:
                traceback.print_exc(file=sys.stderr)

    def send(self, s):
        self.queue.put_nowait(s)

    def _format_record(self, record):
        # ensure that exc_info and args
        # have been stringified.  Removes any chance of
        # unpickleable things inside and possibly reduces
        # message size sent over the pipe
        if record.args:
            record.msg = record.msg % record.args
            record.args = None
        if record.exc_info:
            dummy = self.format(record)
            record.exc_info = None

        return record

    def emit(self, record):
        try:
            s = self._format_record(record)
            self.send(s)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def close(self):
        self._handler.close()
        logging.Handler.close(self)

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

Android splash screen image sizes to fit all devices

PORTRAIT

LDPI: 200x320px

MDPI: 320x480px

HDPI: 480x800px

XHDPI: 720px1280px

LANDSCAPE

LDPI: 320x200px

MDPI: 480x320px

HDPI: 800x480px

XHDPI: 1280x720px

How do I properly compare strings in C?

Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>

Try this code:

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

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

How do I pass multiple parameter in URL?

This

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);

must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.

Using a compound parameter like

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);

would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).


1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I ran into this issue due to a silly mistake. Make sure the date actually exists!

For example:

September 31, 2015 does not exist.

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931'

So this fails with the message:

Error converting data type varchar to datetime.

To fix it, input a valid date:

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930'

And it executes just fine.

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Passing Objects By Reference or Value in C#

When you pass the the System.Drawing.Image type object to a method you are actually passing a copy of reference to that object.

So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.

YourMethod(System.Drawing.Image image)
{
    //now this image is a new reference
    //if you load a new image 
    image = new Image()..
    //you are not changing the original reference you are just changing the copy of original reference
}

send bold & italic text on telegram bot with html

To Send bold,italic,fixed width code you can use this :

# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname, 
             text="*boldtext* _italictext_ `fixed width font` [link]   (http://google.com).", 
             parse_mode=telegram.ParseMode.MARKDOWN)

make sure you have enabled the bot as your admin .Then only it can send message

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

Setting up maven dependency for SQL Server

There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:

http://jtds.sourceforge.net/

From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.3.1</version>
</dependency>

UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

I think amazon definition is straight and simple to understand.

"Continuous delivery is a software development methodology where the release process is automated. Every software change is automatically built, tested, and deployed to production. Before the final push to production, a person, an automated test, or a business rule decides when the final push should occur. Although every successful software change can be immediately released to production with continuous delivery, not all changes need to be released right away.

Continuous integration is a software development practice where members of a team use a version control system and integrate their work frequently to the same location, such as a master branch. Each change is built and verified by tests and other verifications in order to detect any integration errors as quickly as possible. Continuous integration is focused on automatically building and testing code, as compared to continuous delivery, which automates the entire software release process up to production."

Please check out http://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

ssh: connect to host github.com port 22: Connection timed out

The reason could be the firewall modification as you are under a network.(In which case they may deliberately block some ports)
To double check if this is the reason ... do

ssh -T [email protected]

this should timeout. If that's the case use http protocol instead of ssh this way
just change your url in the config file to http.
Here is how :-

git config --local -e

change entry of

 url = [email protected]:username/repo.git

to

url = https://github.com/username/repo.git

How to grep and replace

Here is what I would do:

find /path/to/dir -type f -iname "*filename*" -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

this will look for all files containing filename in the file's name under the /path/to/dir, than for every file found, search for the line with searchstring and replace old with new.

Though if you want to omit looking for a specific file with a filename string in the file's name, than simply do:

find /path/to/dir -type f -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

This will do the same thing above, but to all files found under /path/to/dir.

How do you monitor network traffic on the iPhone?

Depending on what you want to do runnning it via a Proxy is not ideal. A transparent proxy might work ok as long as the packets do not get tampered with.

I am about to reverse the GPS data that gets transferred from the iPhone to the iPad on iOS 4.3.x to get to the the vanilla data the best way to get a clean Network Dump is to use "tcpdump" and/or "pirni" as already suggested.

In this particular case where we want the Tethered data it needs to be as transparent as possible. Obviously you need your phone to be JailBroken for this to work.

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

To ensure that JQuery isn't caching the results, on your ajax methods, put the following:

$.ajax({
    cache: false
    //rest of your ajax setup
});

Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:

[NoCache]
public class ControllerBase : Controller, IControllerBase

You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.

If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).

Using ls to list directories and their total sizes

This is one I like

update: I didnt like the previous one because it didn't show files in the current directory, it only listed directories.

Example output for /var on ubuntu:

sudo du -hDaxd1 /var | sort -h | tail -n10

4.0K    /var/lock
4.0K    /var/run
4.0K    /var/www
12K     /var/spool
3.7M    /var/backups
33M     /var/log
45M     /var/webmin
231M    /var/cache
1.4G    /var/lib
1.7G    /var

Move top 1000 lines from text file to a new file using Unix shell commands

Perl approach:

perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in

What is a CSRF token? What is its importance and how does it work?

The site generates a unique token when it makes the form page. This token is required to post/get data back to the server.

Since the token is generated by your site and provided only when the page with the form is generated, some other site can't mimic your forms -- they won't have the token and therefore can't post to your site.

Can not find module “@angular-devkit/build-angular”

I struggled with the same problem just a minute ago. My project was generated using the v 1.6.0 of angular-cli.

npm update -g @angular/cli editing my package.json changing the line "@angular/cli": "1.6.0", to "@angular/cli": "^1.6.0", npm update did the trick.

jquery mobile background image

I found this answer works for me

<style type="text/css">
#background{ 
position: fixed; 
top: 0; 
left: 0; 
width: 100% !important; 
height: 100% !important; 
background: url(mobile-images/limo-service.jpg) no-repeat center center fixed !important; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover; 
z-index: -1; 
} 
.ui-page{ 
background:none; 
}
</style>    

also add id="background" to the div for your content section

<div data-role="page" data-theme="a">
  <div data-role="main" class="ui-content" id="background">
  </div>
</div>

How to deep watch an array in angularjs?

There are performance consequences to deep-diving an object in your $watch. Sometimes (for example, when changes are only pushes and pops), you might want to $watch an easily calculated value, such as array.length.

textarea's rows, and cols attribute in CSS

<textarea rows="4" cols="50"></textarea>

It is equivalent to:

textarea {
    height: 4em;
    width: 50em;
}

where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.

Return array in a function

As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.

in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.

int* func()
{
  int* Arr = new int[100];
  return Arr;
}

int main()
{
  int* ArrResult = func();
  cout << ArrResult[0] << " " << ArrResult[1] << endl;
  return 0;
} 




Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

For windows platform, You must check if redis-server is running on given ip:port. you can find redis configuration at installation directory /conf/redis.conf. by default client accept 127.0.0.1:6379.

Simplest way to serve static data from outside the application server in a Java web application

If you want to work with JAX-RS (e.g. RESTEasy) try this:

@Path("/pic")
public Response get(@QueryParam("url") final String url) {
    String picUrl = URLDecoder.decode(url, "UTF-8");

    return Response.ok(sendPicAsStream(picUrl))
            .header(HttpHeaders.CONTENT_TYPE, "image/jpg")
            .build();
}

private StreamingOutput sendPicAsStream(String picUrl) {
    return output -> {
        try (InputStream is = (new URL(picUrl)).openStream()) {
            ByteStreams.copy(is, output);
        }
    };
}

using javax.ws.rs.core.Response and com.google.common.io.ByteStreams

Creating custom function in React component

You can try this.

// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)

import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';

class HtmlComponents extends React.Component {

    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }

    rippleClickFunction(){
        //do stuff. 
        // foo==bar
    }

    render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Yhe only concern is you have to bind the context to the function

How do I print the content of httprequest request?

This should be more helpful for debug. Answer from @Juned Ahsan will not specify full URL and will not print multiple headers/parameters.

private String httpServletRequestToString(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();

    sb.append("Request Method = [" + request.getMethod() + "], ");
    sb.append("Request URL Path = [" + request.getRequestURL() + "], ");

    String headers =
        Collections.list(request.getHeaderNames()).stream()
            .map(headerName -> headerName + " : " + Collections.list(request.getHeaders(headerName)) )
            .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Request headers: NONE,");
    } else {
        sb.append("Request headers: ["+headers+"],");
    }

    String parameters =
        Collections.list(request.getParameterNames()).stream()
            .map(p -> p + " : " + Arrays.asList( request.getParameterValues(p)) )
            .collect(Collectors.joining(", "));             

    if (parameters.isEmpty()) {
        sb.append("Request parameters: NONE.");
    } else {
        sb.append("Request parameters: [" + parameters + "].");
    }

    return sb.toString();
}

Moment JS - check if a date is today or in the future

invert isBefore method of moment to check if a date is same as today or in future like this:

!moment(yourDate).isBefore(moment(), "day");

How do I call a function twice or more times consecutively?

from itertools import repeat, starmap

results = list(starmap(do, repeat((), 3)))

See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:

for _ in starmap(do, repeat((), 3)): pass

but that's getting ugly.

How to add MVC5 to Visual Studio 2013?

Visual Studio 2013 no longer has separate project types for different ASP.Net features.

You must select .NET Framework 4.5 (or higher) in order to see the ASP.NET Web Application template (For ASP.NET One).
So just select Visual C# > Web > ASP.NET Web Application, then select the MVC checkbox in the next step.

Note: Make sure not to select the C# > Web > Visual Studio 2012 sub folder.

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

Full Screen Theme for AppCompat

This theme only works after API 21(included). And make both the StatusBar and NavigationBar transparent.

<style name="TransparentAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <item name="windowActionBar">false</item>
  <item name="windowNoTitle">true</item>
  <item name="android:statusBarColor">@android:color/transparent</item>
  <item name="android:windowBackground">@android:color/transparent</item>
  <item name="android:navigationBarColor">@android:color/transparent</item>
  <item name="android:windowIsTranslucent">true</item>
  <item name="android:windowContentOverlay">@null</item>
</style>

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Check if two unordered lists are equal

Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)

functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)

Example:

>>> from functools import reduce
>>> def compvecs(a,b):
...     return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
... 
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>> 

AndroidStudio gradle proxy

In my case I am behind a proxy with dynamic settings.

I had to download the settings script by picking the script address from internet settings at
Chrome > Settings > Show Advanced Settings > Change proxy Settings > Internet Properties > Connections > LAN Settings > Use automatic configuration script > Address

Opening this URL in a browser downloads a PAC file which I opened in a text editor

  • Look for a PROXY string, it should contain a hostname and port
  • Copy values into gradle.properties

systemProp.https.proxyHost=blabla.domain.com
systemProp.https.proxyPort=8081

  • I didn't have to specify a user not password.

Java System.out.print formatting

Something likes this

public void testPrintOut() {
    int val1 = 8;
    String val2 = "$951.23";
    String val3 = "$215.92";
    String val4 = "$198,301.22";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

    val1 = 9;
    val2 = "$950.19";
    val3 = "$216.95";
    val4 = "$198,084.26";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}

new DateTime() vs default(DateTime)

If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

The following line will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will compile:

    private void MyMethod(DateTime syncedTime = default(DateTime))

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

How to Use UTF-8 Collation in SQL Server database?

UTF-8 is not a character set, it's an encoding. The character set for UTF-8 is Unicode. If you want to store Unicode text you use the nvarchar data type.

If the database would use UTF-8 to store text, you would still not get the text out as encoded UTF-8 data, you would get it out as decoded text.

You can easily store UTF-8 encoded text in the database, but then you don't store it as text, you store it as binary data (varbinary).

How can I use a batch file to write to a text file?

@echo off Title Writing using Batch Files color 0a

echo Example Text > Filename.txt echo Additional Text >> Filename.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

Getting a better understanding of callback functions in JavaScript

There are 3 main possibilities to execute a function:

var callback = function(x, y) {
    // "this" may be different depending how you call the function
    alert(this);
};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

How do I debug Node.js applications?

node-debug -p 8888 scriptFileName.js

Delete duplicate records from a SQL table without a primary key

delete sub from (select ROW_NUMBER() OVer(Partition by empid order by empid)cnt from employee)sub where sub.cnt>1

How to calculate the bounding box for a given lat/lng location?

It is very simple just go to panoramio website and then open World Map from panoramio website.Then go to specified location whichs latitude and longitude required.

Then you found latitude and longitude in address bar for example in this address.

http://www.panoramio.com/map#lt=32.739485&ln=70.491211&z=9&k=1&a=1&tab=1&pl=all

lt=32.739485 =>latitude ln=70.491211 =>longitude

this Panoramio JavaScript API widget create a bounding box around a lat/long pair and then returning all photos with in those bounds.

Another type of Panoramio JavaScript API widget in which you can also change background color with example and code is here.

It does not show in composing mood.It show after publishing.

<div dir="ltr" style="text-align: center;" trbidi="on">
<script src="https://ssl.panoramio.com/wapi/wapi.js?v=1&amp;hl=en"></script>
<div id="wapiblock" style="float: right; margin: 10px 15px"></div>
<script type="text/javascript">
var myRequest = {
  'tag': 'kahna',
  'rect': {'sw': {'lat': -30, 'lng': 10.5}, 'ne': {'lat': 50.5, 'lng': 30}}
};
  var myOptions = {
  'width': 300,
  'height': 200
};
var wapiblock = document.getElementById('wapiblock');
var photo_widget = new panoramio.PhotoWidget('wapiblock', myRequest, myOptions);
photo_widget.setPosition(0);
</script>
</div>

How to save a list to a file and read it as a list type?

If you don't want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header.

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

What is the difference between Bower and npm?

TL;DR: The biggest difference in everyday use isn't nested dependencies... it's the difference between modules and globals.

I think the previous posters have covered well some of the basic distinctions. (npm's use of nested dependencies is indeed very helpful in managing large, complex applications, though I don't think it's the most important distinction.)

I'm surprised, however, that nobody has explicitly explained one of the most fundamental distinctions between Bower and npm. If you read the answers above, you'll see the word 'modules' used often in the context of npm. But it's mentioned casually, as if it might even just be a syntax difference.

But this distinction of modules vs. globals (or modules vs. 'scripts') is possibly the most important difference between Bower and npm. The npm approach of putting everything in modules requires you to change the way you write Javascript for the browser, almost certainly for the better.

The Bower Approach: Global Resources, Like <script> Tags

At root, Bower is about loading plain-old script files. Whatever those script files contain, Bower will load them. Which basically means that Bower is just like including all your scripts in plain-old <script>'s in the <head> of your HTML.

So, same basic approach you're used to, but you get some nice automation conveniences:

  • You used to need to include JS dependencies in your project repo (while developing), or get them via CDN. Now, you can skip that extra download weight in the repo, and somebody can do a quick bower install and instantly have what they need, locally.
  • If a Bower dependency then specifies its own dependencies in its bower.json, those'll be downloaded for you as well.

But beyond that, Bower doesn't change how we write javascript. Nothing about what goes inside the files loaded by Bower needs to change at all. In particular, this means that the resources provided in scripts loaded by Bower will (usually, but not always) still be defined as global variables, available from anywhere in the browser execution context.

The npm Approach: Common JS Modules, Explicit Dependency Injection

All code in Node land (and thus all code loaded via npm) is structured as modules (specifically, as an implementation of the CommonJS module format, or now, as an ES6 module). So, if you use NPM to handle browser-side dependencies (via Browserify or something else that does the same job), you'll structure your code the same way Node does.

Smarter people than I have tackled the question of 'Why modules?', but here's a capsule summary:

  • Anything inside a module is effectively namespaced, meaning it's not a global variable any more, and you can't accidentally reference it without intending to.
  • Anything inside a module must be intentionally injected into a particular context (usually another module) in order to make use of it
  • This means you can have multiple versions of the same external dependency (lodash, let's say) in various parts of your application, and they won't collide/conflict. (This happens surprisingly often, because your own code wants to use one version of a dependency, but one of your external dependencies specifies another that conflicts. Or you've got two external dependencies that each want a different version.)
  • Because all dependencies are manually injected into a particular module, it's very easy to reason about them. You know for a fact: "The only code I need to consider when working on this is what I have intentionally chosen to inject here".
  • Because even the content of injected modules is encapsulated behind the variable you assign it to, and all code executes inside a limited scope, surprises and collisions become very improbable. It's much, much less likely that something from one of your dependencies will accidentally redefine a global variable without you realizing it, or that you will do so. (It can happen, but you usually have to go out of your way to do it, with something like window.variable. The one accident that still tends to occur is assigning this.variable, not realizing that this is actually window in the current context.)
  • When you want to test an individual module, you're able to very easily know: exactly what else (dependencies) is affecting the code that runs inside the module? And, because you're explicitly injecting everything, you can easily mock those dependencies.

To me, the use of modules for front-end code boils down to: working in a much narrower context that's easier to reason about and test, and having greater certainty about what's going on.


It only takes about 30 seconds to learn how to use the CommonJS/Node module syntax. Inside a given JS file, which is going to be a module, you first declare any outside dependencies you want to use, like this:

var React = require('react');

Inside the file/module, you do whatever you normally would, and create some object or function that you'll want to expose to outside users, calling it perhaps myModule.

At the end of a file, you export whatever you want to share with the world, like this:

module.exports = myModule;

Then, to use a CommonJS-based workflow in the browser, you'll use tools like Browserify to grab all those individual module files, encapsulate their contents at runtime, and inject them into each other as needed.

AND, since ES6 modules (which you'll likely transpile to ES5 with Babel or similar) are gaining wide acceptance, and work both in the browser or in Node 4.0, we should mention a good overview of those as well.

More about patterns for working with modules in this deck.


EDIT (Feb 2017): Facebook's Yarn is a very important potential replacement/supplement for npm these days: fast, deterministic, offline package-management that builds on what npm gives you. It's worth a look for any JS project, particularly since it's so easy to swap it in/out.


EDIT (May 2019) "Bower has finally been deprecated. End of story." (h/t: @DanDascalescu, below, for pithy summary.)

And, while Yarn is still active, a lot of the momentum for it shifted back to npm once it adopted some of Yarn's key features.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I have the same error I was replacing my Set with a new one get from Jackson.

To solve this I keep the existing set, I remove from the old set the element unknown into the new list with retainAll. Then I add the new ones with addAll.

    this.oldSet.retainAll(newSet);
    this.oldSet.addAll(newSet);

No need to have the Session and manipulate it.

Numpy first occurrence of value greater than existing value

I was also interested in this and I've compared all the suggested answers with perfplot. (Disclaimer: I'm the author of perfplot.)

If you know that the array you're looking through is already sorted, then

numpy.searchsorted(a, alpha)

is for you. It's O(log(n)) operation, i.e., the speed hardly depends on the size of the array. You can't get faster than that.

If you don't know anything about your array, you're not going wrong with

numpy.argmax(a > alpha)

Already sorted:

enter image description here

Unsorted:

enter image description here

Code to reproduce the plot:

import numpy
import perfplot


alpha = 0.5
numpy.random.seed(0)


def argmax(data):
    return numpy.argmax(data > alpha)


def where(data):
    return numpy.where(data > alpha)[0][0]


def nonzero(data):
    return numpy.nonzero(data > alpha)[0][0]


def searchsorted(data):
    return numpy.searchsorted(data, alpha)


perfplot.save(
    "out.png",
    # setup=numpy.random.rand,
    setup=lambda n: numpy.sort(numpy.random.rand(n)),
    kernels=[argmax, where, nonzero, searchsorted],
    n_range=[2 ** k for k in range(2, 23)],
    xlabel="len(array)",
)

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

Google Chrome Full Black Screen

Same thing just happened to me on Google Chrome v22.0.1221.1 (Nvidia GPU). The workaround was to disable GPU compositing on all pages (setting available on chrome://flags/)

If it happens in Chrome version > 45.x, See answer https://stackoverflow.com/a/32955808/293023 by @detale.

Use google-chrome -disable-gpu from the command line to temporary disable gpu.

Adding a splash screen to Flutter apps

Adding a page like below and routing might help

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutkart/utils/flutkart.dart';
import 'package:flutkart/utils/my_navigator.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Timer(Duration(seconds: 5), () => MyNavigator.goToIntro(context));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(color: Colors.redAccent),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Expanded(
                flex: 2,
                child: Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 50.0,
                        child: Icon(
                          Icons.shopping_cart,
                          color: Colors.greenAccent,
                          size: 50.0,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 10.0),
                      ),
                      Text(
                        Flutkart.name,
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 24.0),
                      )
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    CircularProgressIndicator(),
                    Padding(
                      padding: EdgeInsets.only(top: 20.0),
                    ),
                    Text(
                      Flutkart.store,
                      softWrap: true,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18.0,
                          color: Colors.white),
                    )
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}

If you want to follow through, see: https://www.youtube.com/watch?v=FNBuo-7zg2Q

How do I limit the number of results returned from grep?

The -m option is probably what you're looking for:

grep -m 10 PATTERN [FILE]

From man grep:

-m NUM, --max-count=NUM
        Stop reading a file after NUM matching lines.  If the  input  is
        standard  input  from a regular file, and NUM matching lines are
        output, grep ensures that the standard input  is  positioned  to
        just  after the last matching line before exiting, regardless of
        the presence of trailing context lines.  This enables a  calling
        process  to resume a search.

Note: grep stops reading the file once the specified number of matches have been found!

Can HTML checkboxes be set to readonly?

This presents a bit of a usability issue.

If you want to display a checkbox, but not let it be interacted with, why even a checkbox then?

However, my approach would be to use disabled (The user expects a disabled checkbox to not be editable, instead of using JS to make an enabled one not work), and add a form submit handler using javascript that enables checkboxes right before the form is submitted. This way you you do get your values posted.

ie something like this:

var form = document.getElementById('yourform');
form.onSubmit = function () 
{ 
    var formElems = document.getElementsByTagName('INPUT');
    for (var i = 0; i , formElems.length; i++)
    {  
       if (formElems[i].type == 'checkbox')
       { 
          formElems[i].disabled = false;
       }
    }
}

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

Jinja2 template not rendering if-elif-else statement properly

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

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

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

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

Other corrections I made:

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

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

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

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

Cannot access wamp server on local network

I had the same problem but mine worked fine. Turn off your firewall, antivirus. Make sure your port 80 is enabled and both pcs are set to be remotely accessed. In each pc under users, add new user using the host ip address of the other pc. Restart all services. Put your wampserver online. It should connect

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

How does a hash table work?

All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.

As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.

Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.

In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.