Programs & Examples On #Memoir

Django Cookies, how can I set them?

UPDATE : check Peter's answer below for a builtin solution :

This is a helper to set a persistent cookie:

import datetime

def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

Use the following code before sending a response.

def view(request):
    response = HttpResponse("hello")
    set_cookie(response, 'name', 'jujule')
    return response

UPDATE : check Peter's answer below for a builtin solution :

Hibernate: "Field 'id' doesn't have a default value"

When your field is not nullable it requires a default value to be specified on table creation. Recreate a table with AUTO_INCREMENT properly initialized so DB will not require default value since it will generate it by itself and never put NULL there.

CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)

);

https://www.w3schools.com/sql/sql_autoincrement.asp

What's the valid way to include an image with no src?

I personally use an about:blank src and deal with the broken image icon by setting the opacity of the img element to 0.

How to input a path with a white space?

You can escape the "space" char by putting a \ right before it.

How can I force a long string without any blank to be wrapped?

In a case where the table isnt of fixed size, below line worked for me:

style="width:110px; word-break: break-all;"

Converting Date and Time To Unix Timestamp

Seems like getTime is not function on above answer.

Date.parse(currentDate)/1000

nvm keeps "forgetting" node in new terminal session

I was facing the same issue while using the integrated terminal in VS Code editor. Restarting VS Code after changing the node version using nvm fixed the issue for me.

How to generate random float number in C

If you want to generate a random float in a range, try a next solution.

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


float
random_float(const float min, const float max)
{
    if (max == min) return min;
    else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;

    // return 0 if min > max
    return 0;
}


int
main (const int argc, const char *argv[])
{
    srand(time(NULL));

    char line[] = "-------------------------------------------";

    float data[10][2] = {
        {-10, 10},
        {-5., 5},
        {-1, 1},
        {-0.25, -0.15},
        {1.5, 1.52},
        {-1700, 8000},
        {-0.1, 0.1},
        {-1, 0},
        {-1, -2},
        {1.2, 1.1}
    };

    puts(line);
    puts("     From    |    Result    |      To");
    puts(line);


    int i;
    for (i = 0; i < 10; ++i) {
        printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
    }

    puts(line);

    return 0;
}

A result (values is fickle)

-------------------------------------------
     From    |    Result    |      To
-------------------------------------------
  -10.000000 |     2.330828 |    10.000000
   -5.000000 |    -4.945523 |     5.000000
   -1.000000 |     0.004242 |     1.000000
   -0.250000 |    -0.203197 |    -0.150000
    1.500000 |     1.513431 |     1.520000
-1700.000000 |  3292.941895 |  8000.000000
   -0.100000 |    -0.021541 |     0.100000
   -1.000000 |    -0.148299 |     0.000000
   -1.000000 |     0.000000 |    -2.000000
    1.200000 |     0.000000 |     1.100000
-------------------------------------------

Integrate ZXing in Android Studio

I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.

There is a real handy git repository that provides the zxing android library project as an AAR archive.

All you have to do is add this to your build.gradle

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    implementation 'com.google.zxing:core:3.2.0'
}

and Gradle does all the magic to compile the code and makes it accessible in your app.

To start the Scanner afterwards, use this class/method: From the Activity:

new IntentIntegrator(this).initiateScan(); // `this` is the current Activity

From a Fragment:

IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.

There are several customizing options:

IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0);  // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();

They have a sample-project and are providing several integration examples:

If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

How to set a border for an HTML div tag

In bootstrap 4, you can use border utilities like so.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style>_x000D_
  .border-5 {_x000D_
    border-width: 5px !important;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<textarea class="border border-dark border-5">some content</textarea>
_x000D_
_x000D_
_x000D_

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

PHP code to convert a MySQL query to CSV

An update to @jrgns (with some slight syntax differences) solution.

$result = mysql_query('SELECT * FROM `some_table`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="export.csv"');
       header('Pragma: no-cache');    
       header('Expires: 0');
       fputcsv($fp, $headers); 
       while ($row = mysql_fetch_row($result)) 
       {
          fputcsv($fp, array_values($row)); 
       }
die; 
} 

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

Meaning of "[: too many arguments" error from if [] (square brackets)

Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:

  • I used -e thinking it means "empty" at first; but that means "file exists" - use -z for testing empty variable (string)
  • String variables need to be quoted
  • For compound logical AND comparison, either:
    • use two tests and && them: [ ... ] && [ ... ]
    • or use the -a operator in a single test: [ ... -a ... ]

Here is a working command (searching through all txt files in a directory, and dumping those that grep finds contain both of two words):

find /usr/share/doc -name '*.txt' | while read file; do \
  a1=$(grep -H "description" $file); \
  a2=$(grep -H "changes" $file); \
  [ ! -z "$a1" -a ! -z "$a2"  ] && echo -e "$a1 \n $a2" ; \
done

Edit 12 Aug 2013: related problem note:

Note that when checking string equality with classic test (single square bracket [), you MUST have a space between the "is equal" operator, which in this case is a single "equals" = sign (although two equals' signs == seem to be accepted as equality operator too). Thus, this fails (silently):

$ if [ "1"=="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi 
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi 
A

... but add the space - and all looks good:

$ if [ "1" = "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi 
B

Android Studio not showing modules in project structure

Had similar issue when running version control on a project in Android Studio (0.4.2). When pulling it down to a new location and importing the modules, only the "Android SDK" were showing in the Project Structure.

I removed the .idea/ folder from the version control, by adding it to .gitignore file, and did a fresh pull and imported the modules. Now all the settings appeared correctly in the Project Settings and Platform Settings for the Project Structure.

How to add AUTO_INCREMENT to an existing column?

This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:

1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
...et viola

Getting JavaScript object key list

For a comma-delineated string listing the keys of a JSON Object, try the following:

function listKeys(jObj){
    var keyString = '';
    for(var k in jObj){
        keyString+=(','+k);
    }
    return keyString.slice(1);
}



/* listKeys({'a' : 'foo', 'b' : 'foo', 'c' : 'foo'}) -> 'a,b,c' */

How to locate the Path of the current project directory in Java (IDE)?

This is the new way to do it:

Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);

Or even better:

Path root = Paths.get(".").normalize().toAbsolutePath();

But I would take it one step further:

public String getUsersProjectRootDirectory() {
    String envRootDir = System.getProperty("user.dir");
    Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
    if ( rootDir.startsWith(envRootDir) ) {
        return rootDir;
    } else {
        throw new RuntimeException("Root dir not found in user directory.");
    }
}

PHP read and write JSON from file

The sample for reading and writing JSON in PHP:

$json = json_decode(file_get_contents($file),TRUE);

$json[$user] = array("first" => $first, "last" => $last);

file_put_contents($file, json_encode($json));

Twitter Bootstrap: Print content of modal window

This is a revised solution that will also work for modal windows rendered using a Grails template, where you can have the same modal template called multiple times (with different values) in the same body. This thread helped me immensely, so I thought I'd share it in case other Grails users found their way here.

For those who are curious, the accepted solution didn't work for me because I am rendering a table; each row has a button that opens a modal window with more details about the record. This led to multiple printSection divs being created and printed on top of each other. Therefore I had to revise the js to clean up the div after it was done printing.

CSS

I added this CSS directly to my modal gsp, but adding it to the parent has the same effect.

<style type="text/css">
   @media screen {
        #printSection {
           display: none;
        }
   }

   @media print {
        body > *:not(#printSection) {
           display: none;
        }
        #printSection, #printSection * {
            visibility: visible;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;
        }
   }
</style>

Adding it to the site-wide CSS killed the print functionality in other parts of the site. I got this from ComFreak's accepted answer (based on Bennett McElwee answer), but it is revised using ':not' functionality from fanfavorite's answer on Print <div id=printarea></div> only? . I opted for 'display' rather than 'visibility' because my invisible body content was creating extra blank pages, which was unacceptable to my users.

js

And this to my javascript, revised from ComFreak's accepted answer to this question.

function printDiv(div) {    
    // Create and insert new print section
    var elem = document.getElementById(div);
    var domClone = elem.cloneNode(true);
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    $printSection.appendChild(domClone);
    document.body.insertBefore($printSection, document.body.firstChild);

    window.print(); 

    // Clean up print section for future use
    var oldElem = document.getElementById("printSection");
    if (oldElem != null) { oldElem.parentNode.removeChild(oldElem); } 
                          //oldElem.remove() not supported by IE

    return true;
}

I had no need for appending elements, so I removed that aspect and changed the function to specifically print a div.

HTML (gsp)

And the modal template. This prints the modal header & body and excludes the footer, where the buttons were located.

<div class="modal-content">
    <div id="print-me"> <!-- This is the div that is cloned and printed -->
        <div class="modal-header">
            <!-- HEADER CONTENT -->
        </div>
        <div class="modal-body">
             <!-- BODY CONTENT -->
        </div>
    </div>
    <div class="modal-footer">
                                 <!-- This is where I specify the div to print -->
        <button type="button" class="btn btn-default" onclick="printDiv('print-me')">Print</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
</div>

I hope that helps someone!

AJAX cross domain call

Here is an easy way of how you can do it, without having to use anything fancy, or even JSON.

First, create a server side script to handle your requests. Something like http://www.example.com/path/handler.php

You will call it with parameters, like this: .../handler.php?param1=12345&param2=67890

Inside it, after processing the recieved data, output:

document.serverResponse('..all the data, in any format that suits you..');
// Any code could be used instead, because you dont have to encode this data
// All your output will simply be executed as normal javascript

Now, in the client side script, use the following:

document.serverResponse = function(param){ console.log(param) }

var script = document.createElement('script');
script.src='http://www.example.com/path/handler.php?param1=12345&param2=67890';
document.head.appendChild(script);

The only limit of this approach, is the max length of parameters that you can send to the server. But, you can always send multiple requests.

Module not found: Error: Can't resolve 'core-js/es6'

The imports have changed for core-js version 3.0.1 - for example

import 'core-js/es6/array'; and import 'core-js/es7/array';

can now be provided simply by the following

import 'core-js/es/array';

if you would prefer not to bring in the whole of core-js

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

Java word count program

public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");


    int wordCount = 1,count=1;
 BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
            String str2 = "", str1 = "";

            while ((str1 = br.readLine()) != null) {

                    str2 += str1;

            }


    for (int i = 0; i < str2.length(); i++) 
    {
        if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 


        }

    System.out.println("Word count is = " +(wordCount));
}

}

month name to month number and vice versa in python

def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))

SQL: how to select a single id ("row") that meets multiple criteria from a single column

This question is some years old but i came via a duplicate to it. I want to suggest a more general solution too. If you know you always have a fixed number of ancestors you can use some self joins as already suggested in the answers. If you want a generic approach go on reading.

What you need here is called Quotient in relational Algebra. The Quotient is more or less the reversal of the Cartesian Product (or Cross Join in SQL).

Let's say your ancestor set A is (i use a table notation here, i think this is better for understanding)

ancestry
-----------
'England'
'France'
'Germany'

and your user set U is

user_id
--------
   1
   2
   3

The cartesian product C=AxU is then:

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'
   2     | 'Germany'
   3     | 'England'
   3     | 'France'
   3     | 'Germany'

If you calculate the set quotient U=C/A then you get

user_id
--------
   1
   2
   3

If you redo the cartesian product UXA you will get C again. But note that for a set T, (T/A)xA will not necessarily reproduce T. For example, if T is

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'

then (T/A) is

user_id
--------
   1

(T/A)xA will then be

user_id  |  ancestry
---------+------------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'

Note that the records for user_id=2 have been eliminated by the Quotient and Cartesian Product operations.

Your question is: Which user_id has ancestors from all countries in your ancestor set? In other words you want U=T/A where T is your original set (or your table).

To implement the quotient in SQL you have to do 4 steps:

  1. Create the Cartesian Product of your ancestry set and the set of all user_ids.
  2. Find all records in the Cartesian Product which have no partner in the original set (Left Join)
  3. Extract the user_ids from the resultset of 2)
  4. Return all user_ids from the original set which are not included in the result set of 3)

So let's do it step by step. I will use TSQL syntax (Microsoft SQL server) but it should easily be adaptable to other DBMS. As a name for the table (user_id, ancestry) i choose ancestor

CREATE TABLE ancestry_set (ancestry nvarchar(25))
INSERT INTO ancestry_set (ancestry) VALUES ('England')
INSERT INTO ancestry_set (ancestry) VALUES ('France')
INSERT INTO ancestry_set (ancestry) VALUES ('Germany')

CREATE TABLE ancestor ([user_id] int, ancestry nvarchar(25))
INSERT INTO ancestor ([user_id],ancestry) VALUES (1,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(1,'Ireland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(2,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Poland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'Germany')

1) Create the Cartesian Product of your ancestry set and the set of all user_ids.

SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry

2) Find all records in the Cartesian Product which have no partner in the original set (Left Join) and

3) Extract the user_ids from the resultset of 2)

SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
      FROM ancestor a, ancestry_set s
      GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null

4) Return all user_ids from the original set which are not included in the result set of 3)

SELECT DISTINCT [user_id]
FROM ancestor
WHERE [user_id] NOT IN (
   SELECT DISTINCT cp.[user_id]
   FROM (SELECT a.[user_id],s.ancestry
         FROM ancestor a, ancestry_set s
         GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
   WHERE a.[user_id] is null
   )

How to push object into an array using AngularJS

Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview

Controller-

var app= angular.module('app', []);

app.controller('TestController', function($scope) {
    this.arrayText = [{text:'Hello',},{text: 'world'}];

    this.addText = function(text) {

      if(text) {
        var obj = {
          text: text
        };
          this.arrayText.push(obj);
          this.myText = '';
          console.log(this.arrayText);
        }
      } 
 });

HTML

<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
        <input type="text" ng-model="testCtrl.myText" value="Lets go">
        <button type="submit">Add</button>
        <div ng-repeat="item in testCtrl.arrayText">
            <span>{{item}}</span>
        </div>
</form>

What is a "thread" (really)?

This was taken from a Yahoo Answer:

A thread is a coding construct unaffect by the architecture of an application. A single process frequently may contain multiple threads. Threads can also directly communicate with each other since they share the same variables.

Processes are independent execution units with their own state information. They also use their own address spaces and can only interact with other processes through interprocess communication mechanisms.

However, to put in simpler terms threads are like different "tasks". So think of when you are doing something, for instance you are writing down a formula on one paper. That can be considered one thread. Then another thread is you writing something else on another piece of paper. That is where multitasking comes in.

Intel processors are said to have "hyper-threading" (AMD has it too) and it is meant to be able to perform multiple "threads" or multitask much better.

I am not sure about the logistics of how a thread is handled. I do recall hearing about the processor going back and forth between them, but I am not 100% sure about this and hopefully somebody else can answer that.

C# static class constructor

A static constructor looks like this

static class Foo
{
    static Foo()
    {
         // Static initialization code here
    }
}

It is executed only once when the type is first used. All classes can have static constructors, not just static classes.

"No such file or directory" but it exists

This error may also occur if trying to run a script and the shebang is misspelled. Make sure it reads #!/bin/sh, #!/bin/bash, or whichever interpreter you're using.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
        {
            if (i.Selected == true)
            {
                items += i.Text + ",";
            }
        }
        Response.Write("selected items"+ items);

Does HTTP use UDP?

http over udp is used by some torrent tracker implementations (and supporteb by all main clients)

How to convert a String into an ArrayList?

You could use:

List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());

You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:

// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);

Where should I put the log4j.properties file?

My IDE is NetBeans. I put log4j.property file as shown in the pictures

Root

project's root folder

Web

web folder

WEB-INF

WEB-INF folder

To use this property file you should to write this code:

package example;

import java.io.File;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import javax.servlet.*;
public class test {

public static ServletContext context;
static Logger log = Logger.getLogger("example/test");

public test() {

        String homeDir = context.getRealPath("/");
        File propertiesFile = new File(homeDir, "WEB-INF/log4j.properties");
        PropertyConfigurator.configure(propertiesFile.toString());
        log.info("This is a test");
    }
}

You can define static ServletContext context from another JSP file. Example:

test.context = getServletContext(); 
test sample = new test(); 

Now you can use log4j.property file in your projects.

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

What is the best way to create a string array in python?

The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.

"unable to locate adb" using Android Studio

open Studio settings-->System settings --> Android SDK --> select SDK tool tab -->> select "Android SDK platform tool" and install

How to reset the bootstrap modal when it gets closed and open it fresh again?

Just reset any content manually when modal is hidden:

$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

There is more events. More about them here

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".modal").on("hidden.bs.modal", function() {_x000D_
    $(".modal-body1").html("Where did he go?!?!?!");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class='modal-body1'>_x000D_
          <h3>Close and open, I will be gone!</h3>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

How do I make an Event in the Usercontrol and have it handled in the Main Form?

one of the easy way to do that is use landa function without any problem like

userControl_Material1.simpleButton4.Click += (s, ee) =>
            {
                Save_mat(mat_global);
            };

Resource interpreted as Document but transferred with MIME type application/zip

The problem

I had similar problem. Got message in js

Resource interpreted as Document but transferred with MIME type text/csv

But I also got message in chrome console

Mixed Content: The site at 'https://my-site/' was loaded over a secure connection, but the file at 'https://my-site/Download?id=99a50c7b' was redirected through an insecure connection. This file should be served over HTTPS. This download has been blocked

It says here that you need to use an secure connection (but scheme is https in message already, strangely...).

The problem is that href for file downloading builded on server side. And this href used http in my case.

The solution

So I changed scheme to https when build href for file downloading.

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

html5: display video inside canvas

var canvas = document.getElementById('canvas');
var ctx    = canvas.getContext('2d');
var video  = document.getElementById('video');

video.addEventListener('play', function () {
    var $this = this; //cache
    (function loop() {
        if (!$this.paused && !$this.ended) {
            ctx.drawImage($this, 0, 0);
            setTimeout(loop, 1000 / 30); // drawing at 30fps
        }
    })();
}, 0);

I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code

Edit :
here's an online example, just for you :)
Demo

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
  canvas.width = video.videoWidth;_x000D_
  canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
  var $this = this; //cache_x000D_
  (function loop() {_x000D_
    if (!$this.paused && !$this.ended) {_x000D_
      ctx.drawImage($this, 0, 0);_x000D_
      setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
    }_x000D_
  })();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
  <video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
  <canvas id="canvas"></canvas>_x000D_
  <label>_x000D_
    <br />Try to play me :)</label>_x000D_
  <br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

m2eclipse not finding maven dependencies, artifacts not found

Okay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

SQL Query to search schema of all tables

Same thing but in ANSI way

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CreateDate' )

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

How do I get the entity that represents the current user in Symfony2?

Symfony 4+, 2019+ Approach

In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security service via auto-wiring in the controller like this:

<?php

use Symfony\Component\Security\Core\Security;

class SomeClass
{
    /**
     * @var Security
     */
    private $security;

    public function __construct(Security $security)
    {
       $this->security = $security;
    }

    public function privatePage() : Response
    {
        $user = $this->security->getUser(); // null or UserInterface, if logged in
        // ... do whatever you want with $user
    }
}

Symfony 2- Approach

As @ktolis says, you first have to configure your /app/config/security.yml.

Then with

$user = $this->get('security.token_storage')->getToken()->getUser();
$user->getUsername();

should be enougth!

$user is your User Object! You don't need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!

How to check if pytorch is using the GPU?

Create a tensor on the GPU as follows:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

Do not quit, open another terminal and check if the python process is using the GPU using:

$ nvidia-smi

What is the difference between const int*, const int * const, and int const *?

The general rule is that the const keyword applies to what precedes it immediately. Exception, a starting const applies to what follows.

  • const int* is the same as int const* and means "pointer to constant int".
  • const int* const is the same as int const* const and means "constant pointer to constant int".

Edit: For the Dos and Don'ts, if this answer isn't enough, could you be more precise about what you want?

Anaconda Navigator won't launch (windows 10)

You need to update Anaconda using:

conda update

and

conda update anaconda-navigator

Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:

anaconda-navigator

If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.

Changing Vim indentation behavior by file type

edit your ~/.vimrc, and add different file types for different indents,e.g. I want html/rb indent for 2 spaces, and js/coffee files indent for 4 spaces:

" by default, the indent is 2 spaces. 
set shiftwidth=2
set softtabstop=2
set tabstop=2

" for html/rb files, 2 spaces
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab

" for js/coffee/jade files, 4 spaces
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab

refer to: Setting Vim whitespace preferences by filetype

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

use context.Database.BeginTransaction.

From MSDN:

using (var context = new BloggingContext()) 
{ 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
        try 
        { 
            context.Database.ExecuteSqlCommand( 
                @"UPDATE Blogs SET Rating = 5" + 
                    " WHERE Name LIKE '%Entity Framework%'" 
                ); 

            var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
            foreach (var post in query) 
            { 
                post.Title += "[Cool Blog]"; 
            } 

            context.SaveChanges(); 

            dbContextTransaction.Commit(); 
        } 
        catch (Exception) 
        { 
            dbContextTransaction.Rollback(); //Required according to MSDN article 
            throw; //Not in MSDN article, but recommended so the exception still bubbles up
        } 
    } 
} 

Could not load file or assembly 'System.Web.Mvc'

I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.


EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

Python != operation vs "is not"

First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".

Definitions

Object identity: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.

>>> button = Button()
>>> cancel = button
>>> close = button
>>> dismiss = button
>>> print(cancel is close)
True

In this case, cancel, close, and dismiss all refer to the same object in memory. You only created one Button object, and all three variables refer to this one object. We say that cancel, close, and dismiss all refer to identical objects; that is, they refer to one single object.

Object equality: When you compare two objects, you usually don't care that it refers to the exact same object in memory. With object equality, you can define your own rules for how two objects compare. When you write if a == b:, you are essentially saying if a.__eq__(b):. This lets you define a __eq__ method on a so that you can use your own comparison logic.

Rationale for equality comparisons

Rationale: Two objects have the exact same data, but are not identical. (They are not the same object in memory.) Example: Strings

>>> greeting = "It's a beautiful day in the neighbourhood."
>>> a = unicode(greeting)
>>> b = unicode(greeting)
>>> a is b
False
>>> a == b
True

Note: I use unicode strings here because Python is smart enough to reuse regular strings without creating new ones in memory.

Here, I have two unicode strings, a and b. They have the exact same content, but they are not the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the unicode object has implemented the __eq__ method.

class unicode(object):
    # ...

    def __eq__(self, other):
        if len(self) != len(other):
            return False

        for i, j in zip(self, other):
            if i != j:
                return False

        return True

Note: __eq__ on unicode is definitely implemented more efficiently than this.

Rationale: Two objects have different data, but are considered the same object if some key data is the same. Example: Most types of model data

>>> import datetime
>>> a = Monitor()
>>> a.make = "Dell"
>>> a.model = "E770s"
>>> a.owner = "Bob Jones"
>>> a.warranty_expiration = datetime.date(2030, 12, 31)
>>> b = Monitor()
>>> b.make = "Dell"
>>> b.model = "E770s"
>>> b.owner = "Sam Johnson"
>>> b.warranty_expiration = datetime.date(2005, 8, 22)
>>> a is b
False
>>> a == b
True

Here, I have two Dell monitors, a and b. They have the same make and model. However, they neither have the same data nor are the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the Monitor object implemented the __eq__ method.

class Monitor(object):
    # ...

    def __eq__(self, other):
        return self.make == other.make and self.model == other.model

Answering your question

When comparing to None, always use is not. None is a singleton in Python - there is only ever one instance of it in memory.

By comparing identity, this can be performed very quickly. Python checks whether the object you're referring to has the same memory address as the global None object - a very, very fast comparison of two numbers.

By comparing equality, Python has to look up whether your object has an __eq__ method. If it does not, it examines each superclass looking for an __eq__ method. If it finds one, Python calls it. This is especially bad if the __eq__ method is slow and doesn't immediately return when it notices that the other object is None.

Did you not implement __eq__? Then Python will probably find the __eq__ method on object and use that instead - which just checks for object identity anyway.

When comparing most other things in Python, you will be using !=.

Adjust UILabel height to text

I create this extension if you want

extension UILabel {
    func setSizeFont (sizeFont: CGFloat) {
        self.font =  UIFont(name: self.font.fontName, size: sizeFont)!
        self.sizeToFit()
    }
}

Image is not showing in browser?

You put inside img tag physical path you your image. Instead of that you should put virtual path (according to root of web application) to your image. This value depends on location of your image and your html page.

for example if you have:

/yourDir
-page.html
-66.jpg

in your page.html it should be something like that:

<img  src="66.jpg" width="400" height="400" ></img>

second scenario:

/images
-66.jpg
/html
page.html

So your img should look like:

<img  src="../images/66.jpg" width="400" height="400" ></img>

View HTTP headers in Google Chrome?

My favorite way in Chrome is clicking on a bookmarklet:

javascript:(function(){function read(url){var r=new XMLHttpRequest();r.open('HEAD',url,false);r.send(null);return r.getAllResponseHeaders();}alert(read(window.location))})();

Put this code in your developer console pad.

Source: http://www.danielmiessler.com/blog/a-bookmarklet-that-displays-http-headers

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

Installed Java 7 on Mac OS X but Terminal is still using version 6

Update

brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk/openjdk/adoptopenjdk8

https://stackoverflow.com/a/28635465

Old version For me the easiest and cleanest way to go is to install Java using homebrew like described here:

https://stackoverflow.com/a/28635465

brew update
brew cask install java

How to check if a symlink exists

  1. first you can do with this style:

    mda="/usr/mda"
    if [ ! -L "${mda}" ]; then
      echo "=> File doesn't exist"
    fi
    
  2. if you want to do it in more advanced style you can write it like below:

    #!/bin/bash
    mda="$1"
    if [ -e "$1" ]; then
        if [ ! -L "$1" ]
        then
            echo "you entry is not symlink"
        else
            echo "your entry is symlink"
        fi
    else
      echo "=> File doesn't exist"
    fi
    

the result of above is like:

root@linux:~# ./sym.sh /etc/passwd
you entry is not symlink
root@linux:~# ./sym.sh /usr/mda 
your entry is symlink
root@linux:~# ./sym.sh 
=> File doesn't exist

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

WCF Service , how to increase the timeout?

The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.

Using reCAPTCHA on localhost

As of January 2nd, 2021, Google posted these two keys for testing in this article.

I'd like to run automated tests with reCAPTCHA. What should I do? For reCAPTCHA v3, create a separate key for testing environments. Scores may not be accurate as reCAPTCHA v3 relies on seeing real traffic.

For reCAPTCHA v2, use the following test keys. You will always get No CAPTCHA and all verification requests will pass.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

The reCAPTCHA widget will show a warning message to ensure it's not used for production traffic.

The generated emails went into spam the first time I used the keys.

RegEx match open tags except XHTML self-contained tags

If you're simply trying to find those tags (without ambitions of parsing) try this regular expression:

/<[^/]*?>/g

I wrote it in 30 seconds, and tested here: http://gskinner.com/RegExr/

It matches the types of tags you mentioned, while ignoring the types you said you wanted to ignore.

Can I start the iPhone simulator without "Build and Run"?

Since XCode 4.3 the location has changed, the simulator can now be found at:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/

Text overwrite in visual studio 2010

press your keyboard Insert Key

Using Apache httpclient for https

This is what worked for me:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "password".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

How to make a WPF window be on top of all other windows of my app (not system wide)?

Instead you can use a Popup that will be TopMost always, decorate it similar to a Window and to attach it completely with your Application handle the LocationChanged event of your main Window and set IsOpen property of Popup to false.

Edit:

I hope you want something like this:

    Window1 window;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        window = new Window1();
        window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        window.Topmost = true;
        this.LocationChanged+=OnLocationchanged;
        window.Show();
    }
     
    private void OnLocationchanged(object sender, EventArgs e)
    {
          if(window!=null)
              window.Close();
    }

Hope it helps!!!

How to access JSON Object name/value?

You might want to try this approach:

var  str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

Vertically align text to top within a UILabel

Refering to the extension solution:

for(int i=1; i< newLinesToPad; i++) 
    self.text = [self.text stringByAppendingString:@"\n"];

should be replaced by

for(int i=0; i<newLinesToPad; i++)
    self.text = [self.text stringByAppendingString:@"\n "];

Additional space is needed in every added newline, because iPhone UILabels' trailing carriage returns seems to be ignored :(

Similarly, alignBottom should be updated too with a @" \n@%" in place of "\n@%" (for cycle initialization must be replaced by "for(int i=0..." too).

The following extension works for me:

// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end

// -- file: UILabel+VerticalAlign.m
@implementation UILabel (VerticalAlign)
- (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
        self.text = [self.text stringByAppendingString:@"\n "];
}

- (void)alignBottom {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
@end

Then call [yourLabel alignTop]; or [yourLabel alignBottom]; after each yourLabel text assignment.

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:

private fun isConnected(): Boolean {
    val activeNetwork = cManager.activeNetworkInfo
    return activeNetwork != null && activeNetwork.isConnected
}

There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.

try{
//for example, retrofit call
}
catch (e: Exception) {
        is UnknownHostException -> "Unknown host!"
        is ConnectException -> "No internet!"
        else -> "Unknown exception!"
    }

It's just a tricky moment that can by related with this problem.

Hope, I will help somebody)

how to run a command at terminal from java program?

I vote for Karthik T's answer. you don't need to open a terminal to run commands.

For example,

// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunShellCommandFromJava {

    public static void main(String[] args) {

        String command = "ping -c 3 www.google.com";

        Process proc = Runtime.getRuntime().exec(command);

        // Read the output

        BufferedReader reader =  
              new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
        while((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }

        proc.waitFor();   

    }
} 

The output:

$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms

--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms

jQuery dialog popup

This HTML is fine:

<a href="#" id="contactUs">Contact Us</a>                   
<div id="dialog" title="Contact form">
  <p>appear now</p>
</div>

You need to initialize the Dialog (not sure if you are doing this):

$(function() {
  // this initializes the dialog (and uses some common options that I do)
  $("#dialog").dialog({
    autoOpen : false, modal : true, show : "blind", hide : "blind"
  });

  // next add the onclick handler
  $("#contactUs").click(function() {
    $("#dialog").dialog("open");
    return false;
  });
});

Django, creating a custom 500/404 error page

If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.

Read String line by line

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

Dockerfile if else condition with external arguments

It might not look that clean but you can have your Dockerfile (conditional) as follow:

FROM centos:7
ARG arg
RUN if [[ -z "$arg" ]] ; then echo Argument not provided ; else echo Argument is $arg ; fi

and then build the image as:

docker build -t my_docker . --build-arg arg=45

or

docker build -t my_docker .

How to read xml file contents in jQuery and display in html elements?

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

How to compare two JSON have the same properties without order?

Easy way to compare two json string in javascript

var obj1 = {"name":"Sam","class":"MCA"};
var obj2 = {"class":"MCA","name":"Sam"};

var flag=true;

if(Object.keys(obj1).length==Object.keys(obj2).length){
    for(key in obj1) { 
        if(obj1[key] == obj2[key]) {
            continue;
        }
        else {
            flag=false;
            break;
        }
    }
}
else {
    flag=false;
}
console.log("is object equal"+flag);

No submodule mapping found in .gitmodule for a path that's not a submodule

No submodule mapping found in .gitmodules for path 'OtherLibrary/MKStore' when

$ git submodule update --init

I didn't know why the error occur. After spending a minute and found the answer in stackoverflow.

$ git rm --cached OtherLibrary/MKStore

and then update the submodule again. It's working fine.

http://en.saturngod.net/no-submodule-mapping-found-in-gitmodules

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

if you are using IIS, maybe you should try
"application pools" --> "DefaultAppPool" --> "application pools default value" --> "32-Bit-application-activ" --> set false

How can I restore the MySQL root user’s full privileges?

If you've deleted your root user by mistake you can do one thing:

  1. Stop MySQL service
  2. Run mysqld_safe --skip-grant-tables &
  3. Type mysql -u root -p and press enter.
  4. Enter your password
  5. At the mysql command line enter: use mysql;

Then execute this query:

insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`) 
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');

then restart the mysqld

EDIT: October 6, 2018

In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):

insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections) 
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');

How to replace specific values in a oracle database column?

If you need to update the value in a particular table:

UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');

where

  TABLE-NAME         - The name of the table being updated
  COLUMN-NAME        - The name of the column being updated
  STRING-TO-REPLACE  - The value to replace
  REPLACEMENT-STRING - The replacement

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

The way i solved this was by making a system tray icon that had a cancel option.

When restoring a backup, how do I disconnect all active connections?

Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.

But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works

Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.

How to add favicon.ico in ASP.NET site

/favicon.ico

might do the trick
I have tried this on my sample website

<link rel="shortcut icon" type="image/x-icon" href="~/ows.ico" />

Try this one in your site put the link in MasterPage,It works :)

<link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />


I have tested in ,
FireFox.
enter image description here
Chrome.
enter image description here
Opera.
enter image description here

Some troubleshoots:
1. Check if your favicon is accessible (correct url) ,goto view source and click on the favicon link
2. Full refresh your browser by Ctrl+F5 every time you make changes.
3. Try searching from SO you may find your related problem here.


Some Links to help you out:
Serving favicon.ico in ASP.NET MVC
Favicon Not Showing
Why is favicon not visible

How to use struct timeval to get the execution time?

You have two typing errors in your code:

 struct timeval,

should be

 struct timeval

and after the printf() parenthesis you need a semicolon.

Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.

Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec and subtract "before" tv_usec. You gain nothing by casting an integer number of seconds to a float.

I'd suggest checking out the man page for struct timeval.

This is the code:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks table.

Documentation here

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

For version 19.1 and above goto specified directory and delete these mentioned files:

  1. C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1<smart-git-version>

    • preferences.yml
    • license file
  2. C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1\.backup

    • preferences.yml

For the previous version goto specified directory and delete mentioned file:

  1. C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\17<smart-git-version>

    • setting.xml

how to fire event on file select

vanilla js using es6

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});

Cookies vs. sessions

As others said, Sessions are clever and has more advantage of hiding the information from the client.

But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

How to disable text selection using jQuery?

One solution to this, for appropriate cases, is to use a <button> for the text that you don't want to be selectable. If you are binding to the click event on some text block, and don't want that text to be selectable, changing it to be a button will improve the semantics and also prevent the text being selected.

<button>Text Here</button>

Python, Pandas : write content of DataFrame into text File

You can use pandas.DataFrame.to_csv(), and setting both index and header to False:

In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

pandas.DataFrame.to_csv can write to a file directly, for more info you can refer to the docs linked above.

How to use a variable inside a regular expression?

I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

Output can be printed using the following:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

How to get a .csv file into R?

Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.

The easiest is

df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5. 

Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).

MySQL: How to allow remote connection to mysql

Just F.Y.I I pulled my hair out with this problem for hours.. finally I call my hosting provider and found that in my case using a cloud server that in the control panel for 1and1 they have a secondary firewall that you have to clone and add port 3306. Once added I got straight in..

Python: tf-idf-cosine: to find document similarity

First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()

>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 1787553 stored elements in Compressed Sparse Row format>

Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.

As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.

The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:

>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 89 stored elements in Compressed Sparse Row format>

scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:

>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1.        ,  0.04405952,  0.11016969, ...,  0.04433602,
    0.04457106,  0.03293218])

Hence to find the top 5 related documents, we can use argsort and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):

>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([    0,   958, 10576,  3277])
>>> cosine_similarities[related_docs_indices]
array([ 1.        ,  0.54967926,  0.32902194,  0.2825788 ])

The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:

>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
   ---- brought to you by your neighborhood Lerxst ----

The second most similar document is a reply that quotes the original message hence has many common words:

>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26

In article <[email protected]> [email protected] (where's my
thing) writes:
>
>  I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.

Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.

>    ---- brought to you by your neighborhood Lerxst ----

Rush fan?

--
Robert Seymour              [email protected]
Physics and Philosophy, Reed College    (NeXTmail accepted)
Artificial Life Project         Reed College
Reed Solar Energy Project (SolTrain)    Portland, OR

Difference between spring @Controller and @RestController annotation

The @Controller annotation indicates that the class is a "Controller" like a web controller while @RestController annotation indicates that the class is a controller where @RequestMapping methods assume @ResponseBody semantics by default i.e. servicing REST API

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Getting unique items from a list

You can use Distinct extension method from LINQ

LINQ .Any VS .Exists - What's the difference?

Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.

How to use onClick with divs in React.js

For future googlers (thousands have now googled this question):

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)

Check to see if python script is running

A simple example if you only are looking for a process name exist or not:

import os

def pname_exists(inp):
    os.system('ps -ef > /tmp/psef')
    lines=open('/tmp/psef', 'r').read().split('\n')
    res=[i for i in lines if inp in i]
    return True if res else False

Result:
In [21]: pname_exists('syslog')
Out[21]: True

In [22]: pname_exists('syslog_')
Out[22]: False

Most efficient method to groupby on an array of objects

I have expanded on the accepted answer to include grouping by multiple properties, add thenby and make it purely functional with no mutation. See a demo at https://stackblitz.com/edit/typescript-ezydzv

export interface Group {
  key: any;
  items: any[];
}

export interface GroupBy {
  keys: string[];
  thenby?: GroupBy;
}

export const groupBy = (array: any[], grouping: GroupBy): Group[] => {
  const keys = grouping.keys;
  const groups = array.reduce((groups, item) => {
    const group = groups.find(g => keys.every(key => item[key] === g.key[key]));
    const data = Object.getOwnPropertyNames(item)
      .filter(prop => !keys.find(key => key === prop))
      .reduce((o, key) => ({ ...o, [key]: item[key] }), {});
    return group
      ? groups.map(g => (g === group ? { ...g, items: [...g.items, data] } : g))
      : [
          ...groups,
          {
            key: keys.reduce((o, key) => ({ ...o, [key]: item[key] }), {}),
            items: [data]
          }
        ];
  }, []);
  return grouping.thenby ? groups.map(g => ({ ...g, items: groupBy(g.items, grouping.thenby) })) : groups;
};

convert iso date to milliseconds in javascript

Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);

var date = new Date(); 
var myDate= date - new Date(0);

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I tried everything above nothing worked for me it was a space in a folder name

/swift files/project a/code.xcworkspace -> /swift_files/project_a/code.xcworkspace
did the trick If I looked deeper it was stopping at /swift

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

It can also happen due to a typo in referencing a table such as [dbo.Product] instead of [dbo].[Product].

How to find the largest file in a directory and its subdirectories?

Try following command :

find /your/path -printf "%k %p\n" | sort -g -k 1,1 | awk '{if($1 > 500000) print $1/1024 "MB" " " $2 }' |tail -n 1 

This will print the largest file name and size and more than 500M. You can move the if($1 > 500000),and it will print the largest file in the directory.

How does String substring work in Swift

Here's a function that returns substring of a given substring when start and end indices are provided. For complete reference you can visit the links given below.

func substring(string: String, fromIndex: Int, toIndex: Int) -> String? {
    if fromIndex < toIndex && toIndex < string.count /*use string.characters.count for swift3*/{
        let startIndex = string.index(string.startIndex, offsetBy: fromIndex)
        let endIndex = string.index(string.startIndex, offsetBy: toIndex)
        return String(string[startIndex..<endIndex])
    }else{
        return nil
    }
}

Here's a link to the blog post that I have created to deal with string manipulation in swift. String manipulation in swift (Covers swift 4 as well)

Or you can see this gist on github

What are intent-filters in Android?

Keep the first intent filter with keys MAIN and LAUNCHER and add another as ANY_NAME and DEFAULT.

Your LAUNCHER will be activity A and DEFAULT will be your activity B.

Is there any way to do HTTP PUT in python

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

How do I get total physical memory size using PowerShell without WMI?

If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.

(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()

Split code over multiple lines in an R script

I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][time_[s]<=12000]

I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []. Splitting at ][ doesn´t work.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, 
    Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, 
    Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, 
    Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

iPhone/iPad browser simulator?

There's no good substitute to testing on an actual device.

Real devices have higher display densities, meaning that pixels are smaller. If you don't test on a real device, you may not realise that your design includes text that is too small to read or buttons that are too small to tap.

You use real devices with your fingers, not a mouse. This means that the accuracy of your taps is much lower and what you are tapping is obscured by your finger. If you don't test on a real device, you may not realise you've introduced usability problems into your design.

how to generate public key from windows command prompt

If you've got git-bash installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen.

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How to restore the menu bar in Visual Studio Code

To restore menu bar visibility so that you don't press key Alt to make the menu bar visible and the menu bar remains visible all the time, see the setting below.

You inadvertently changed the value from "default" to "toggle", so restore the setting to "default" as shown below.

"window.menuBarVisibility": "default"

How do I find the length of an array?

ANSWER:

int number_of_elements = sizeof(array)/sizeof(array[0])

EXPLANATION:

Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:

int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to

number_of_elements = 720/24

Note that you don't need to know what data type the array is, even if it's a custom data type.

MATLAB - multiple return values from a function?

Use the following in the function you will call and it will work just fine.

     [a b c] = yourfunction(optional)
     %your code
     a = 5;
     b = 7;
     c = 10;
     return
     end

This is a way to call the function both from another function and from the command terminal

     [aa bb cc] = yourfunction(optional);

The variables aa, bb and cc now hold the return variables.

How would I access variables from one class to another?

var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1


class ClassB(ClassA):
    def __init__(self):
        super().__init__()
        print("var1",self.var1)
        print("var2",self.var2)


object1 = ClassB()
sum = object1.methodA()
print(sum)

How to stretch in width a WPF user control to its window?

What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).

$(document).ready(function() is not working

You only get this error if jQuery is not correctly loaded, you can check with firebug what url its trying to load so you can see if your relative path is wrong.

Also, on a separate note, you can use $(function(){ as a shorthand to $(document).ready(function(){

Removing specific rows from a dataframe

DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ]   # note the ! (negation)

Or if sub is a factor as suggested by your use of quotes:

DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]

Could also use subset:

subset(DF,  ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )

(And I endorse the use of which in Dirk's answer when using "[" even though some claim it is not needed.)

JavaScript Regular Expression Email Validation

It would be best to use:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;

This allows domains such as: whatever.info (4 letters at the end)

Also to test, using

pattern.test("[email protected]")

returns true if it works

http://www.w3schools.com/js/js_obj_regexp.asp

Does C have a string type?

To note it in the languages you mentioned:

Java:

String str = new String("Hello");

Python:

str = "Hello"

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.

C:

char * str = "Hello";  // the string "Hello\0" is pointed to by the character pointer
                       // str. This "string" can not be modified (read only)

or

char str[] = "Hello";  // the characters: 'H''e''l''l''o''\0' have been copied to the 
                       // array str. You can change them via: str[x] = 't'

A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0'). Note that the sentinel character is auto-magically appended for you in the cases above.

Check if a temporary table exists and delete if it exists before creating a temporary table

I think the problem is you need to add GO statement in between to separate the execution into batches. As the second drop script i.e. IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results did not drop the temp table being part of single batch. Can you please try the below script.

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
)

GO

select company, stepid, fieldid from #Results

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
    NewColumn            NVARCHAR(50)
)

GO

select company, stepid, fieldid, NewColumn from #Results

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

You can set the line-height in pixels instead of percentage. Is that what you mean?

Use python requests to download CSV

this worked nicely for me:

from csv import DictReader

f = requests.get('https://somedomain.com/file').content.decode('utf-8')
reader = DictReader(f.split('\n'))
csv_dict_list = list(reader)

What is the relative performance difference of if/else versus switch statement in Java?

Use switch!

I hate to maintain if-else-blocks! Have a test:

public class SpeedTestSwitch
{
    private static void do1(int loop)
    {
        int temp = 0;
        for (; loop > 0; --loop)
        {
            int r = (int) (Math.random() * 10);
            switch (r)
            {
                case 0:
                    temp = 9;
                    break;
                case 1:
                    temp = 8;
                    break;
                case 2:
                    temp = 7;
                    break;
                case 3:
                    temp = 6;
                    break;
                case 4:
                    temp = 5;
                    break;
                case 5:
                    temp = 4;
                    break;
                case 6:
                    temp = 3;
                    break;
                case 7:
                    temp = 2;
                    break;
                case 8:
                    temp = 1;
                    break;
                case 9:
                    temp = 0;
                    break;
            }
        }
        System.out.println("ignore: " + temp);
    }

    private static void do2(int loop)
    {
        int temp = 0;
        for (; loop > 0; --loop)
        {
            int r = (int) (Math.random() * 10);
            if (r == 0)
                temp = 9;
            else
                if (r == 1)
                    temp = 8;
                else
                    if (r == 2)
                        temp = 7;
                    else
                        if (r == 3)
                            temp = 6;
                        else
                            if (r == 4)
                                temp = 5;
                            else
                                if (r == 5)
                                    temp = 4;
                                else
                                    if (r == 6)
                                        temp = 3;
                                    else
                                        if (r == 7)
                                            temp = 2;
                                        else
                                            if (r == 8)
                                                temp = 1;
                                            else
                                                if (r == 9)
                                                    temp = 0;
        }
        System.out.println("ignore: " + temp);
    }

    public static void main(String[] args)
    {
        long time;
        int loop = 1 * 100 * 1000 * 1000;
        System.out.println("warming up...");
        do1(loop / 100);
        do2(loop / 100);

        System.out.println("start");

        // run 1
        System.out.println("switch:");
        time = System.currentTimeMillis();
        do1(loop);
        System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));

        // run 2
        System.out.println("if/else:");
        time = System.currentTimeMillis();
        do2(loop);
        System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
    }
}

My C# standard code for benchmarking

Get Number of Rows returned by ResultSet in Java

A simple getRowCount method can look like this :

private int getRowCount(ResultSet resultSet) {
    if (resultSet == null) {
        return 0;
    }

    try {
        resultSet.last();
        return resultSet.getRow();
    } catch (SQLException exp) {
        exp.printStackTrace();
    } finally {
        try {
            resultSet.beforeFirst();
        } catch (SQLException exp) {
            exp.printStackTrace();
        }
    }

    return 0;
}

Just to be aware that this method will need a scroll sensitive resultSet, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.

INNER JOIN vs LEFT JOIN performance in SQL Server

I found something interesting in SQL server when checking if inner joins are faster than left joins.

If you dont include the items of the left joined table, in the select statement, the left join will be faster than the same query with inner join.

If you do include the left joined table in the select statement, the inner join with the same query was equal or faster than the left join.

How do I create a file at a specific path?

where is the file created?

In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.

Opening file in the root directory probably fails due to lack of privileges.

How to scroll to specific item using jQuery?

I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.

 var scrollDownTo =$("#show_question_" + nQueId).position().top;
        console.log(scrollDownTo);
        $('#slider_light_box_container').animate({
            scrollTop: scrollDownTo
            }, 1000, function(){
        });

        }

What's the difference between emulation and simulation?

Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.

Bootstrap Navbar toggle button not working

If you will change the ID then Toggle will not working same problem was with me i just change

<div class="collapse navbar-collapse" id="defaultNavbar1">
    <ul class="nav navbar-nav">

id="defaultNavbar1" then toggle is working

jQuery if Element has an ID?

Simple way:

Fox example this is your html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}

Turn off iPhone/Safari input element rounding

input -webkit-appearance: none; alone does not work.

Try adding -webkit-border-radius:0px; in addition.

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you use Grunt to build your project, there is a plugin that will automatically assemble your partials into an Angular module that primes $templateCache. You can concatenate this module with the rest of your code and load everything from one file on startup.

https://npmjs.org/package/grunt-html2js

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

The link below will demonstrate how I accomplished this. Not very hard - just have to use some clever front-end dev!!

<div style="position: fixed; bottom: 0%; top: 0%;">

    <div style="overflow-y: scroll; height: 100%;">

       Menu HTML goes in here

    </div>

</div>

http://jsfiddle.net/RyanBrackett/b44Zn/

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

Can we locate a user via user's phone number in Android?

I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.

How do I use 3DES encryption/decryption in Java?

Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:

import java.security.MessageDigest;
import java.util.Arrays;

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

public class TripleDESTest {

    public static void main(String[] args) throws Exception {

        String text = "kyle boon";

        byte[] codedtext = new TripleDESTest().encrypt(text);
        String decodedtext = new TripleDESTest().decrypt(codedtext);

        System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
        System.out.println(decodedtext); // This correctly shows "kyle boon"
    }

    public byte[] encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);

        return cipherText;
    }

    public String decrypt(byte[] message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
}

How to wait in a batch script?

You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use

ping -n 11 127.0.0.1 > nul

This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)

How to generate components in a specific folder with Angular CLI?

Try to use

ng g component plainsight/some-name.component.ts

Or try it manually, if you feel more comfortable.

Serializing and submitting a form with jQuery and PHP

Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:

 <textarea name="comentarii" cols="36" rows="5" placeholder="Message>  

How to know Hive and Hadoop versions from command prompt?

$ hive --version
Hive version 0.8.1.3

EDIT: added another '-' before the version. Doesn't work for newer versions. Hope it works for all now.

Known to work in the following distributions:

  • HortonWorks distribution: $ hive --version Hive 0.14.0.2.2.0.0-2041
  • CDH 5.3

It does not work:

  • CDH 4.3
  • HDinsight (Azure)

jQuery OR Selector?

I have written an incredibly simple (5 lines of code) plugin for exactly this functionality:

http://byrichardpowell.github.com/jquery-or/

It allows you to effectively say "get this element, or if that element doesnt exist, use this element". For example:

$( '#doesntExist' ).or( '#exists' );

Whilst the accepted answer provides similar functionality to this, if both selectors (before & after the comma) exist, both selectors will be returned.

I hope it proves helpful to anyone who might land on this page via google.

How to get all of the immediate subdirectories in Python

Check "Getting a list of all subdirectories in the current directory".

Here's a Python 3 version:

import os

dir_list = next(os.walk('.'))[1]

print(dir_list)

Rails 4 LIKE query - ActiveRecord adds quotes

Your placeholder is replaced by a string and you're not handling it right.

Replace

"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search

with

"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"

How to hide output of subprocess in Python 2.7

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

How to listen for a WebView finishing loading a URL?

I found one elegant solution as well, have not tested it rigorously though:

public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (m_webView.getProgress() == 100) {
                progressBar.setVisibility(View.GONE);
                m_webView.setVisibility(View.VISIBLE);
            }
        } 

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

If you want the old directive back, you can add this to your app:

Directive:

directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
    return {
        scope: {
            ngBindHtmlUnsafe: '=',
        },
        template: "<div ng-bind-html='trustedHtml'></div>",
        link: function($scope, iElm, iAttrs, controller) {
            $scope.updateView = function() {
                $scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
            }

            $scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
                $scope.updateView(newVal);
            });
        }
    };
}]);

Usage

<div ng-bind-html-unsafe="group.description"></div>

Source - https://github.com/angular-ui/bootstrap/issues/813

Unable to set variables in bash script

Assignment in bash scripts cannot have spaces around the = and you probably want your date commands enclosed in backticks $():

#!/bin/bash
folder="ABC"
useracct='test'
day=$(date "+%d")
month=$(date "+%B")
year=$(date "+%Y")
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir $newfoldername
cp -R $folderToBeMoved $newfoldername
if [-f $newfoldername/Primetime.eyetv]; then rm $folderToBeMoved; fi

With the last three lines commented out, for me this outputs:

Network is 
day is 16
Month is March
YEAR is 2010
source is /users/test/Documents/Archive/Primetime.eyetv
dest is /Volumes/Media/Network/ABC/March162010

Difference between Destroy and Delete

Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called

If you care about your models callbacks then use destroy_all

From the official docs

http://apidock.com/rails/ActiveRecord/Base/destroy_all/class

destroy_all(conditions = nil) public

Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).

Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Understanding Python super() with __init__() methods

There isn't, really. super() looks at the next class in the MRO (method resolution order, accessed with cls.__mro__) to call the methods. Just calling the base __init__ calls the base __init__. As it happens, the MRO has exactly one item-- the base. So you're really doing the exact same thing, but in a nicer way with super() (particularly if you get into multiple inheritance later).

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

jQuery Dialog Box

Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:

$(document).ready({
    $('a.TOClink').click(function(){
        showTOC();
    });
});

function showTOC() {
    $('#example').dialog({modal:true});
}

A more concise example which accomplishes the desired effect using the jQuery UI dialog is:

   <div id="terms" style="display:none;">
       Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
   <a id="showTerms" href="#">Show Terms &amp; Conditions</a>      
   <script type="text/javascript">
       $(document).ready(function(){
           $('#showTerms').click(function(){
               $('#terms').dialog({modal:true});   
           });
       });
   </script>

Show/Hide the console window of a C# console application

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

Difference between a SOAP message and a WSDL?

We can consider a telephone call In that Number is wsdl and exchange of information is soap.

WSDL is description how to connect with communication server.SOAP is have communication messages.

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

What does request.getParameter return?

String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Open Facebook Page in Facebook App (if installed) on Android

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions.

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) { //newer versions of fb app
                return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
            } else { //older versions of fb app
                return "fb://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

That's all you need.

Storing Objects in HTML5 localStorage

You can use ejson to store the objects as strings.

EJSON is an extension of JSON to support more types. It supports all JSON-safe types, as well as:

All EJSON serializations are also valid JSON. For example an object with a date and a binary buffer would be serialized in EJSON as:

{
  "d": {"$date": 1358205756553},
  "b": {"$binary": "c3VyZS4="}
}

Here is my localStorage wrapper using ejson

https://github.com/UziTech/storage.js

I added some types to my wrapper including regular expressions and functions

How to get a product's image in Magento?

$model = Mage::getModel('catalog/product'); //getting product model
$_products = $model->getCollection(); //getting product object for particular product id
foreach($_products as $_product) { ?>
    <a href = '<?php echo $model->load($_product->getData("entity_id"))->getUrl_path(); ?>'> <img src= '<?php echo $model->load($_product->getData("entity_id"))->getImageUrl();  ?>' width="75px" height="75px"/></a>
     <?php echo "<br/>".$model->load($_product->getData("entity_id"))->getPrice()."<br/>". $model->load($_product->getData("entity_id"))->getSpecial_price()."<br/>".$model->load($_product->getData("entity_id"))->getName()?>
<?php 

Countdown timer in React

You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

Using Java to find substring of a bigger string using Regular Expression

This regexp works for me:

form\[([^']*?)\]

example:

form[company_details][0][name]
form[company_details][0][common_names][1][title]

output:

Match 1
1.  company_details
Match 2
1.  company_details

Tested on http://rubular.com/

Entity Framework select distinct name

use Select().Distinct()

for example

DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

How to list all Git tags?

You can list all existing tags git tag or you could filter the list with git tag -l 'v1.1.*', where * acts as a wildcard. It will return a list of tags marked with v1.1.

You will notice that when you call git tag you do not get to see the contents of your annotations. To preview them you must add -n to your command: git tag -n2.

$ git tag -l -n2

v1.0 Release version 1.0

v1.1 Release version 1.1

The command lists all existing tags with maximum 3 lines of their tag message. By default -n only shows the first line. For more info be sure to check this tag related article as well.

How to find index of an object by key and value in an javascript array

If you want to check on the object itself without interfering with the prototype, use hasOwnProperty():

var getIndexIfObjWithOwnAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i].hasOwnProperty(attr) && array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

to also include prototype attributes, use:

var getIndexIfObjWithAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

ComboBox SelectedItem vs SelectedValue

If we want to bind to a dictionary ie

  <ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                              ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
                              Margin="{StaticResource SmallMarginLeftBottom}"/>

then SelectedItem will not work whilist SelectedValue will

Get google map link with latitude/longitude

Keep it in iframe, dynamically bind data from object.

"https://www.google.com/maps/embed/v1/place?key=[APIKEY]%20&q=" + content..Latitude + ',' + content.Longitude;

References for longitude and Latitude.
https://developers.google.com/maps/documentation/embed/guide

Note:[APIKEY] will expire in 60days and regenerate key.

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

How to get Current Directory?

I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.

To get the executable path use GetModuleFileName:

TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );

Here's a C++ function that gets the directory without the file name:

#include <windows.h>
#include <string>
#include <iostream>

wstring ExePath() {
    TCHAR buffer[MAX_PATH] = { 0 };
    GetModuleFileName( NULL, buffer, MAX_PATH );
    std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
    return std::wstring(buffer).substr(0, pos);
}

int main() {
    std::cout << "my directory is " << ExePath() << "\n";
}

error while loading shared libraries: libncurses.so.5:

Your system likely does not provide the ncurses library at the version android studio uses. My arch linux install only had ncurses 6 but android studio needs version 5. You could check if your distribution has a compatability package, or use the solution that Rahmat Aligos suggested.

How do I see if Wi-Fi is connected on Android?

This works for me:

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // Mobile
    State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

    // Wi-Fi
    State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

    // And then use it like this:

    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
    }
    else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled  :) ....",Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
    }

And add this permission:

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

Removing object from array in Swift 3

The Swift equivalent to NSMutableArray's removeObject is:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
    array.remove(at: index)
}

if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(of is preferable because it's faster than filter.

Update:

In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

array.removeAll{$0 == "beta"}