Programs & Examples On #Modelmetadata

MVC4 input field placeholder

I did so

Field in model:

[Required]
[Display(Name = "User name")]
public string UserName { get; set; }

Razor:

<li>
  @Html.TextBoxFor(m => m.UserName, new { placeholder = Html.DisplayNameFor(n => n.UserName)})
</li>

How to find a string inside a entire database?

SQL Locator (free) has worked great for me. It comes with a lot of options and it's fairly easy to use.

Delete everything in a MongoDB database

For Meteor developers.

  1. Open a second terminal window while running your app in localhost:3000.

  2. In your project's folder run, meteor mongo.

    coolName = new Mongo.Collection('yourCollectionName');

  3. Then simply enter db.yourCollectionName.drop();

  4. You'll automatically see the changes in your local server.

For everybody else.

db.yourCollectionName.drop();

how to check redis instance version?

To support the answers given above, The details of the redis instance can be obtained by

$ redis-cli
$ INFO

This gives all the info you may need

# Server
redis_version:5.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:da75abdfe06a50f8
redis_mode:standalone
os:Linux 5.3.0-51-generic x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:7.5.0
process_id:14126
run_id:adfaeec5683d7381a2a175a2111f6159b6342830
tcp_port:6379
uptime_in_seconds:16860
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:15766886
executable:/tmp/redis-5.0.5/src/redis-server
config_file:

# Clients
connected_clients:22
....More Verbose

The version lies in the second line :)

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

I was facing the same problem and how i resolved see below steps or Image:

  1. Clicked on Windows menu item of eclipse
  2. Clicked on preferences
  3. select Installed JREs
  4. Add your installed jdk's path(JRE home: C:\Program Files\Java\jdk1.8.0_201\jre`)
  5. Add JRE name: jdk1.8.0_201
  6. Clicked on Finish
  7. Apply changes and close

enter image description here

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

Safe navigation operator (?.) or (!.) and null property paths

A new library called ts-optchain provides this functionality, and unlike lodash' solution, it also keeps your types safe, here is a sample of how it is used (taken from the readme):

import { oc } from 'ts-optchain';

interface I {
  a?: string;
  b?: {
    d?: string;
  };
  c?: Array<{
    u?: {
      v?: number;
    };
  }>;
  e?: {
    f?: string;
    g?: () => string;
  };
}

const x: I = {
  a: 'hello',
  b: {
    d: 'world',
  },
  c: [{ u: { v: -100 } }, { u: { v: 200 } }, {}, { u: { v: -300 } }],
};

// Here are a few examples of deep object traversal using (a) optional chaining vs
// (b) logic expressions. Each of the following pairs are equivalent in
// result. Note how the benefits of optional chaining accrue with
// the depth and complexity of the traversal.

oc(x).a(); // 'hello'
x.a;

oc(x).b.d(); // 'world'
x.b && x.b.d;

oc(x).c[0].u.v(); // -100
x.c && x.c[0] && x.c[0].u && x.c[0].u.v;

oc(x).c[100].u.v(); // undefined
x.c && x.c[100] && x.c[100].u && x.c[100].u.v;

oc(x).c[100].u.v(1234); // 1234
(x.c && x.c[100] && x.c[100].u && x.c[100].u.v) || 1234;

oc(x).e.f(); // undefined
x.e && x.e.f;

oc(x).e.f('optional default value'); // 'optional default value'
(x.e && x.e.f) || 'optional default value';

// NOTE: working with function value types can be risky. Additional run-time
// checks to verify that object types are functions before invocation are advised!
oc(x).e.g(() => 'Yo Yo')(); // 'Yo Yo'
((x.e && x.e.g) || (() => 'Yo Yo'))();

How to clear gradle cache?

Take care with gradle daemon, you have to stop it before clear and re-run gradle.

Stop first daemon:

./gradlew --stop

Clean cache using:

rm -rf ~/.gradle/caches/

Run again you compilation

How can I get file extensions with JavaScript?

function extension(fname) {
  var pos = fname.lastIndexOf(".");
  var strlen = fname.length;
  if (pos != -1 && strlen != pos + 1) {
    var ext = fname.split(".");
    var len = ext.length;
    var extension = ext[len - 1].toLowerCase();
  } else {
    extension = "No extension found";
  }
  return extension;
}

//usage

extension('file.jpeg')

always returns the extension lower cas so you can check it on field change works for:

file.JpEg

file (no extension)

file. (noextension)

How to store a datetime in MySQL with timezone info

I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format. Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM which when store in unix timestamp would be 1568400241

Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be

echo date('m/d/Y', 1568400241);

This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a

commands not found on zsh

Best solution work for me for permanent change path

Open Finder-> go to folder /Users/ /usr/local/bin

open .zshrc with TextEdit

.zshrc is hidden file so unhide it by command+shift+. press

delete file content and type

export PATH=~/usr/bin:/bin:/usr/sbin:/sbin:$PATH

and save

now

zsh: command not found Gone

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

.gitignore exclude folder but include specific subfolder

There are a bunch of similar questions about this, so I'll post what I wrote before:

The only way I got this to work on my machine was to do it this way:

# Ignore all directories, and all sub-directories, and it's contents:
*/*

#Now ignore all files in the current directory 
#(This fails to ignore files without a ".", for example 
#'file.txt' works, but 
#'file' doesn't):
*.*

#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*

Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.

This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153

These were useful topics:

I also tried

*
*/*
**/**

and **/wp-content/themes/**

or /wp-content/themes/**/*

None of that worked for me, either. Lots of trial and error!

operator << must take exactly one argument

A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

 friend ostream& operator<<(ostream&, A&);

then try to define it as a member function of the class logic

 ostream& logic::operator<<(ostream& os, A& a)
          ^^^^^^^

Are you confused about whether logic is a class or a namespace?

The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << a.number;
}

Convert integer to binary in C#

I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.

public static string ByteConvert (int num)
{
    int[] p = new int[8];
    string pa = "";
    for (int ii = 0; ii<= 7;ii = ii +1)
    {
        p[7-ii] = num%2;
        num = num/2;
    }
    for (int ii = 0;ii <= 7; ii = ii + 1)
    {
        pa += p[ii].ToString();
    }
    return pa;
}

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

The argument to remove() is a filter document, so passing in an empty document means 'remove all':

db.user.remove({})

However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

More details in the docs.

Homebrew: Could not symlink, /usr/local/bin is not writable

Following Alex's answer I was able to resolve this issue; seems this to be an issue non specific to the packages being installed but of the permissions of homebrew folders.

sudo chown -R `whoami`:admin /usr/local/bin

For some packages, you may also need to do this to /usr/local/share or /usr/local/opt:

sudo chown -R `whoami`:admin /usr/local/share
sudo chown -R `whoami`:admin /usr/local/opt

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

MS Access: how to compact current database in VBA

Application.SetOption "Auto compact", False '(mentioned above) Use this with a button caption: "DB Not Compact On Close"

Write code to toggle the caption with "DB Compact On Close" along with Application.SetOption "Auto compact", True

AutoCompact can be set by means of the button or by code, ex: after importing large temp tables.

The start up form can have code that turns off Auto Compact, so that it doesn't run every time.

This way, you are not trying to fight Access.

How to delete selected text in the vi editor

When using a terminal like PuTTY, usually mouse clicks and selections are not transmitted to the remote system. So, vi has no idea that you just selected some text. (There are exceptions to this, but in general mouse actions aren't transmitted.)

To delete multiple lines in vi, use something like 5dd to delete 5 lines.

If you're not using Vim, I would strongly recommend doing so. You can use visual selection, where you press V to start a visual block, move the cursor to the other end, and press d to delete (or any other editing command, such as y to copy).

Python Pandas - Find difference between two data frames

import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
    'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
    'Age':[23,12,34,44,28,40]})

# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)

# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)

# df1
#     Age   Name
# 0   23   John
# 1   45   Mike
# 2   12  Smith
# 3   34   Wale
# 4   27  Marry
# 5   44    Tom
# 6   28  Menda
# 7   39   Bolt
# 8   40  Yuswa
# df2
#     Age   Name
# 0   23   John
# 1   12  Smith
# 2   34   Wale
# 3   44    Tom
# 4   28  Menda
# 5   40  Yuswa
# df_1notin2
#     Age   Name
# 0   45   Mike
# 1   27  Marry
# 2   39   Bolt

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

Replace string within file contents

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

My suggestions :

  • Keep the program modular. Keep the Calculate class in a separate Calculate.java file and create a new class that calls the main method. This would make the code readable.
  • For setting the values in the number, use constructors. Do not use like the methods you have used above like :

    public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }

    Constructors exists to initialize the objects.This is their job and they are pretty good at it.

  • Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well

  • In the main class, create a Calculate object using the new operator and the constructor in place.

  • Call the getAnswer() method with the created Calculate object.

Rest of the code looks fine to me. Be modular. You could read your program in a much better way.

Here is my modular piece of code. Two files : Main.java & Calculate.java

Calculate.java

public class Calculate {


private double fn;
private double sn;
private char op;

    public double getFn() {
        return fn;
    }

    public void setFn(double fn) {
        this.fn = fn;
    }

    public double getSn() {
        return sn;
    }

    public void setSn(double sn) {
        this.sn = sn;
    }

    public char getOp() {
        return op;
    }

    public void setOp(char op) {
        this.op = op;
    }



    public Calculate(double fn, double sn, char op) {
        this.fn = fn;
        this.sn = sn;
        this.op = op;
    }


public void getAnswer(){
    double ans;
    switch (getOp()){
        case '+': 
            ans = add(getFn(), getSn());
            ansOutput(ans);
            break;
        case '-': 
            ans = sub (getFn(), getSn());
            ansOutput(ans);
            break;
        case '*': 
            ans = mul (getFn(), getSn());
            ansOutput(ans);
            break;
        case '/': 
            ans = div (getFn(), getSn());
            ansOutput(ans);
            break;
        default:
            System.out.println("--------------------------");
            System.out.println("Invalid choice of operator");
            System.out.println("--------------------------");
        }
    }
    public static double add(double x,double y){
        return x + y;
    }
    public static double sub(double x, double y){
        return x - y;
    }
    public static double mul(double x, double y){
        return x * y;
    }
    public static double div(double x, double y){
        return x / y;
    }

    public static void ansOutput(double x){
        System.out.println("----------- -------");
        System.out.printf("the answer is %.2f\n", x);
        System.out.println("-------------------");
    }
}

Main.java

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

How do I check for a network connection?

Call this method to check the network Connection.

public static bool IsConnectedToInternet()
        {
            bool returnValue = false;
            try
            {

                int Desc;
                returnValue = Utility.InternetGetConnectedState(out Desc, 0);
            }
            catch
            {
                returnValue = false;
            }
            return returnValue;
        }

Put this below line of code.

[DllImport("wininet.dll")]
        public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

TERM environment variable not set

SOLVED: On Debian 10 by adding "EXPORT TERM=xterm" on the Script executed by CRONTAB (root) but executed as www-data.

$ crontab -e

*/15 * * * * /bin/su - www-data -s /bin/bash -c '/usr/local/bin/todos.sh'

FILE=/usr/local/bin/todos.sh

#!/bin/bash -p
export TERM=xterm && cd /var/www/dokuwiki/data/pages && clear && grep -r -h '|(TO-DO)' > /var/www/todos.txt && chmod 664 /var/www/todos.txt && chown www-data:www-data /var/www/todos.txt

How can I replace a newline (\n) using sed?

@OP, if you want to replace newlines in a file, you can just use dos2unix (or unix2dox)

dos2unix yourfile yourfile

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

Im my case the problem was that I cretead sertificates without entering any data in cli interface. When I regenerated cretificates and enetered all fields: City, State, etc all became fine.

 sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

Does Java support default parameter values?

NO, But we have alternative in the form of function overloading.

called when no parameter passed

void operation(){

int a = 0;
int b = 0;

} 

called when "a" parameter was passed

void operation(int a){

int b = 0;
//code

} 

called when parameter b passed

void operation(int a , int b){
//code
} 

Remove an item from an IEnumerable<T> collection

There is now an extension method to convert the IEnumerable<> to a Dictionary<,> which then has a Remove method.

public readonly IEnumerable<User> Users = new User[]; // or however this would be initialized

// To take an item out of the collection
Users.ToDictionary(u => u.Id).Remove(1123);

// To take add an item to the collection
Users.ToList().Add(newuser);

How to run Unix shell script from Java code?

I think with

System.getProperty("os.name"); 

Checking the operating system on can manage the shell/bash scrips if such are supported. if there is need to make the code portable.

Unable to call the built in mb_internal_encoding method?

mbstring is a "non-default" extension, that is not enabled by default ; see this page of the manual :

Installation

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details

So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)


I don't use CentOS, but you may have to install the extension first, using something like this (see this page, for instance, which seems to give a solution) :

yum install php-mbstring

(The package name might be a bit different ; so, use yum search to get it :-) )

How to upgrade all Python packages with pip

You can just print the packages that are outdated:

pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:'

Can you overload controller methods in ASP.NET MVC?

You can use [ActionName("NewActionName")] to use the same method with a different name:

public class HomeController : Controller
{
    public ActionResult GetEmpName()
    {
        return Content("This is the test Message");
    }

    [ActionName("GetEmpWithCode")]
    public ActionResult GetEmpName(string EmpCode)
    {
        return Content("This is the test Messagewith Overloaded");
    }
}

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

Please follow the below steps

1). First, navigate to the /etc/postgresql/{your pg version}/main directory.

My version is 10 Then:

cd /etc/postgresql/10/main

2). Here resides the pg_hba.conf file needs to do some changes here you may need sudo access for this.

sudo nano pg_hba.conf

3). Scroll down the file till you find this –

# Database administrative login by Unix domain socket
local   all             postgres                                peer

4). Here change the peer to md5 as follows.

# Database administrative login by Unix domain socket
local   all             all                                md5
  • peer means it will trust the authenticity of UNIX user hence does not

  • prompt for the password. md5 means it will always ask for a password, and validate it after hashing with MD5.

5).Now save the file and restart the Postgres server.

sudo service postgresql restart

Now it should be ok.

How to silence output in a Bash script?

If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative: echo "hi" | grep "use this hack to hide the oputut :) "

I want to load another HTML page after a specific amount of time

use this JavaScript code:

<script>
    setTimeout(function(){
       window.location.href = 'form2.html';
    }, 5000);
</script>

Add Whatsapp function to website, like sms, tel

Here is the solution to your problem! You just need to use this format:

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

In the place of "urlencodedtext" you need to keep the content in Url-encode format.

UPDATE-- Use this from now(Nov-2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing

After clicking on the link, you will be shown a list of contacts you can send your message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

Remove row lines in twitter bootstrap

This is what worked for me..

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td,
.table-no-border>tbody,
.table-no-border>thead,
.table-no-border>tfoot{
  border-top: none !important; 
  border-bottom: none !important; 
}

Had to whip out the !important to make it stick.

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Animate the transition between fragments

Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.

What is size_t in C?

size_t is an unsigned type. So, it cannot represent any negative values(<0). You use it when you are counting something, and are sure that it cannot be negative. For example, strlen() returns a size_t because the length of a string has to be at least 0.

In your example, if your loop index is going to be always greater than 0, it might make sense to use size_t, or any other unsigned data type.

When you use a size_t object, you have to make sure that in all the contexts it is used, including arithmetic, you want non-negative values. For example, let's say you have:

size_t s1 = strlen(str1);
size_t s2 = strlen(str2);

and you want to find the difference of the lengths of str2 and str1. You cannot do:

int diff = s2 - s1; /* bad */

This is because the value assigned to diff is always going to be a positive number, even when s2 < s1, because the calculation is done with unsigned types. In this case, depending upon what your use case is, you might be better off using int (or long long) for s1 and s2.

There are some functions in C/POSIX that could/should use size_t, but don't because of historical reasons. For example, the second parameter to fgets should ideally be size_t, but is int.

Cordova - Error code 1 for command | Command failed for

I removed android platforms and installed again then worked. I wrote these lines in command window:

cordova platform remove android
then
cordova platform add android

How do I put a border around an Android textview?

This may help you.

<RelativeLayout
    android:id="@+id/textbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@android:color/darker_gray" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="3dp"
        android:background="@android:color/white"
        android:gravity="center"
        android:text="@string/app_name"
        android:textSize="20dp" />

</RelativeLayout

How to read a config file using python

You need a section in your file:

[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third

Then, read the properties:

import ConfigParser

config = ConfigParser.ConfigParser()
config.readfp(open(r'abc.txt'))
path1 = config.get('My Section', 'path1')
path2 = config.get('My Section', 'path2')
path3 = config.get('My Section', 'path3')

Is there a .NET/C# wrapper for SQLite?

From https://system.data.sqlite.org:

System.Data.SQLite is an ADO.NET adapter for SQLite.

System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.

"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."

It even supports Mono.

How can I kill all sessions connecting to my oracle database?

I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html

select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;

Then ran:

Alter System Kill Session '<value from ss above>'
;

To kill individual sessions.

Use chrome as browser in C#?

OpenWebKitSharp gives you full control over WebKit Nightly, which is very close to webkit in terms of performance and compatibility. Chrome uses WebKit Chromium engine, while WebKit.NET uses Cairo and OpenWebKitSharp Nightly. Chromium should be the best of these builds, while at 2nd place should come Nightly and that's why I suggest OpenWebKitSharp.

http://gt-web-software.webs.com/libraries.htm at the OpenWebKitSharp section

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

How do you read a file into a list in Python?

Two ways to read file into list in python (note these are not either or) -

  1. use of with - supported from python 2.5 and above
  2. use of list comprehensions

1. use of with

This is the pythonic way of opening and reading files.

#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
    for line in file: 
        line = line.strip() #or some other preprocessing
        lines.append(line) #storing everything in memory!

#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
    lines = [line.strip() for line in file]

#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators. 
with open("C:\name\MyDocuments\numbers") as file:
    for line in file:
        line = line.strip() #preprocess line
        doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.

the .strip() is used for each line of the file to remove \n newline character that each line might have. When the with ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.

2. use of list comprehension

This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.

data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]

Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.

Android Studio don't generate R.java for my import project

Go to Menu-Tab -> Project -> Build -> Automatically(check this option). and than reopen a new project.

How Do I Take a Screen Shot of a UIView?

- (void)drawRect:(CGRect)rect {
  UIGraphicsBeginImageContext(self.bounds.size);    
  [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);  
}

This method may put in your Controller class.

Which passwordchar shows a black dot (•) in a winforms textbox?

I was also wondering how to store it cleanly in a variable. As using

char c = '•';

is not very good practice (I guess). I found out the following way of storing it in a variable

char c = (char)0x2022;// or 0x25cf depending on the one you choose

or even cleaner

char c = '\u2022';// or "\u25cf"

https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx

same for strings

string s = "\u2022";

https://msdn.microsoft.com/en-us/library/362314fe.aspx

How to embed a PDF?

This works perfectly and this is official html5.

<object data="https://link-to-pdf"></object>

How to implement infinity in Java?

A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.

If T is a type for which lteq is defined, you can define InfiniteOr<T> with lteq something like this:

class InfiniteOr with type parameter T:
    field the_T of type null-or-an-actual-T
    isInfinite()
        return this.the_T == null
    getFinite():
        assert(!isInfinite());
        return this.the_T
    lteq(that)
        if that.isInfinite()
            return true
        if this.isInfinite()
            return false
        return this.getFinite().lteq(that.getFinite())

I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.

The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null to represent infinity here, since that seems the most straightforward in Java.

If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.

There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq) I think it's simpler to look at right-hand-side infinity first. I note that lteq is not commutative, but add and mul are; maybe that is relevant.

Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.

Fastest check if row exists in PostgreSQL

I would like to propose another thought to specifically address your sentence: "So I want to check if a single row from the batch exists in the table because then I know they all were inserted."

You are making things efficient by inserting in "batches" but then doing existence checks one record at a time? This seems counter intuitive to me. So when you say "inserts are always done in batches" I take it you mean you are inserting multiple records with one insert statement. You need to realize that Postgres is ACID compliant. If you are inserting multiple records (a batch of data) with one insert statement, there is no need to check if some were inserted or not. The statement either passes or it will fail. All records will be inserted or none.

On the other hand, if your C# code is simply doing a "set" separate insert statements, for example, in a loop, and in your mind, this is a "batch" .. then you should not in fact describe it as "inserts are always done in batches". The fact that you expect that part of what you call a "batch", may actually not be inserted, and hence feel the need for a check, strongly suggests this is the case, in which case you have a more fundamental problem. You need change your paradigm to actually insert multiple records with one insert, and forego checking if the individual records made it.

Consider this example:

CREATE TABLE temp_test (
    id SERIAL PRIMARY KEY,
    sometext TEXT,
    userid INT,
    somethingtomakeitfail INT unique
)
-- insert a batch of 3 rows
;;
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 1, 1),
('bar', 2, 2),
('baz', 3, 3)
;;
-- inspect the data of what we inserted
SELECT * FROM temp_test
;;
-- this entire statement will fail .. no need to check which one made it
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 2, 4),
('bar', 2, 5),
('baz', 3, 3)  -- <<--(deliberately simulate a failure)
;;
-- check it ... everything is the same from the last successful insert ..
-- no need to check which records from the 2nd insert may have made it in
SELECT * FROM temp_test

This is in fact the paradigm for any ACID compliant DB .. not just Postgresql. In other words you are better off if you fix your "batch" concept and avoid having to do any row by row checks in the first place.

Git for beginners: The definitive practical guide

Git Reset

Say you make a pull, merge it into your code, and decide you don't like it. Use git-log, or tig, and find the hash of wherever you want to go back to (probably your last commit before the pull/merge) copy the hash, and do:

# Revert to a previous commit by hash:
git-reset --hard <hash>

Instead of the hash, you can use HEAD^ as a shortcut for the previous commit.

# Revert to previous commit:
git-reset --hard HEAD^

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

How can I print out all possible letter combinations a given phone number can represent?

Here is the working code for the same.. its a recursion on each step checking possibility of each combinations on occurrence of same digit in a series....I am not sure if there is any better solution then this from complexity point of view.....

Please let me know for any issues....

import java.util.ArrayList;


public class phonenumbers {

    /**
     * @param args
     */
    public static String mappings[][] = {
        {"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
        {"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"}, 
        {"T", "U", "V"}, {"W", "X", "Y", "Z"}
    };

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String phone = "3333456789";
        ArrayList<String> list= generateAllnums(phone,"",0);
    }

    private static ArrayList<String> generateAllnums(String phone,String sofar,int j) {
        // TODO Auto-generated method stub

        //System.out.println(phone);
        if(phone.isEmpty()){
            System.out.println(sofar);
            for(int k1=0;k1<sofar.length();k1++){
                int m=sofar.toLowerCase().charAt(k1)-48;
                if(m==-16)
                    continue;
                int i=k1;
                while(true && i<sofar.length()-2){
                    if(sofar.charAt(i+1)==' ')
                        break;
                    else if(sofar.charAt(i+1)==sofar.charAt(k1)){
                        i++;
                    }else{
                        break;
                    }

                }
                i=i-k1;
                //System.out.print(" " + m +", " + i + " ");
                System.out.print(mappings[m][i%3]);
                k1=k1+i;
            }
            System.out.println();

            return null;
        }
        int num= phone.charAt(j);
        int k=0;
        for(int i=j+1;i<phone.length();i++){
            if(phone.charAt(i)==num){
                k++;
            }
        }

        if(k!=0){

            int p=0;
            ArrayList<String> list2= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p)+ " ", 0);
            ArrayList<String> list3= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p), 0);

        }
        else{
            ArrayList<String> list1= generateAllnums(phone.substring(1), sofar+phone.charAt(0), 0);
        }
        return null;

    }

}

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

How to open .dll files to see what is written inside?

Open .dll file with visual studio. Or resource editor.

Failed to install *.apk on device 'emulator-5554': EOF

Neither above helped me, instead, I connected my phone through the back USB hubs (I used forward USB hubs previously), and this helped me!

How to change the new TabLayout indicator color and height

With the design support library you can now change them in the xml:

To change the color of the TabLayout indicator:

app:tabIndicatorColor="@color/color"

To change the height of the TabLayout indicator:

app:tabIndicatorHeight="4dp"

How to stop the task scheduled in java.util.Timer class

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

How to convert a double to long without casting?

... And here is the rounding way which doesn't truncate. Hurried to look it up in the Java API Manual:

double d = 1234.56;
long x = Math.round(d); //1235

How do I cancel an HTTP fetch() request?

TL/DR:

fetch now supports a signal parameter as of 20 September 2017, but not all browsers seem support this at the moment.

2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)

This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortControllers AbortSignal.

Long Version

How to:

The way it works is this:

Step 1: You create an AbortController (For now I just used this)

const controller = new AbortController()

Step 2: You get the AbortControllers signal like this:

const signal = controller.signal

Step 3: You pass the signal to fetch like so:

fetch(urlToFetch, {
    method: 'get',
    signal: signal, // <------ This is our AbortSignal
})

Step 4: Just abort whenever you need to:

controller.abort();

Here's an example of how it would work (works on Firefox 57+):

_x000D_
_x000D_
<script>_x000D_
    // Create an instance._x000D_
    const controller = new AbortController()_x000D_
    const signal = controller.signal_x000D_
_x000D_
    /*_x000D_
    // Register a listenr._x000D_
    signal.addEventListener("abort", () => {_x000D_
        console.log("aborted!")_x000D_
    })_x000D_
    */_x000D_
_x000D_
_x000D_
    function beginFetching() {_x000D_
        console.log('Now fetching');_x000D_
        var urlToFetch = "https://httpbin.org/delay/3";_x000D_
_x000D_
        fetch(urlToFetch, {_x000D_
                method: 'get',_x000D_
                signal: signal,_x000D_
            })_x000D_
            .then(function(response) {_x000D_
                console.log(`Fetch complete. (Not aborted)`);_x000D_
            }).catch(function(err) {_x000D_
                console.error(` Err: ${err}`);_x000D_
            });_x000D_
    }_x000D_
_x000D_
_x000D_
    function abortFetching() {_x000D_
        console.log('Now aborting');_x000D_
        // Abort._x000D_
        controller.abort()_x000D_
    }_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<h1>Example of fetch abort</h1>_x000D_
<hr>_x000D_
<button onclick="beginFetching();">_x000D_
    Begin_x000D_
</button>_x000D_
<button onclick="abortFetching();">_x000D_
    Abort_x000D_
</button>
_x000D_
_x000D_
_x000D_

Sources:

Two Decimal places using c#

The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use

yournumber.ToString("0.00");

Adding new line of data to TextBox

I find this method saves a lot of typing, and prevents a lot of typos.

string nl = "\r\n";

txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

What is __main__.py?

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
+-- demo
    +-- __init__.py
    +-- __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

how to remove empty strings from list, then remove duplicate values from a list

To simplify Amiram Korach's solution:

dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))

No need to use Distinct() or ToList()

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

An example with variable (ES6):

const item = document.querySelector([data-itemid="${id}"]);

Count number of records returned by group by

How about:

SELECT count(column_1)
FROM
    (SELECT * FROM temptable
    GROUP BY column_1, column_2, column_3, column_4) AS Records

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:


Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <hr>
   <div ng-if="showFrom(message)">
       <div>From: {{message.from.name}}</div>
   </div>    
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{message.createdBy.name}}</div>
   </div>    
   <div ng-if="showTo(message)">
      <div>To: {{message.to.name}}</div>
   </div>    
</div>

Fiddle.

replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

How to refer to relative paths of resources when working with a code repository

Try to use a filename relative to the current files path. Example for './my_file':

fn = os.path.join(os.path.dirname(__file__), 'my_file')

In Python 3.4+ you can also use pathlib:

fn = pathlib.Path(__file__).parent / 'my_file'

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

c# open file with default application and parameters

this should be close!

public static void OpenWithDefaultProgram(string path)
{
    Process fileopener = new Process();
    fileopener.StartInfo.FileName = "explorer";
    fileopener.StartInfo.Arguments = "\"" + path + "\"";
    fileopener.Start();
}

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

I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.

To make it short, for this task os.listdir() is the fastest and is 1.7x as fast as the next best: os.walk() (with a break!), 2.7x as fast as pathlib, 3.2x faster than os.scandir() and 3.3x faster than glob.
Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break



print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

Results:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

To avoid adding extra divs when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.

$('a.ajax').live('click', function() {
    var url = this.href;
    var dialog = $("#dialog");
    if ($("#dialog").length == 0) {
        dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
    } 

    // load remote content
    dialog.load(
            url,
            {},
            function(responseText, textStatus, XMLHttpRequest) {
                dialog.dialog();
            }
        );
    //prevent the browser to follow the link
    return false;
});`

Creating Unicode character from its number

This is how you do it:

int cc = 0x2202;
char ccc = (char) Integer.parseInt(String.valueOf(cc), 16);
final String text = String.valueOf(ccc);

This solution is by Arne Vajhøj.

Get Unix timestamp with C++

As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:

#include <chrono>

//...

using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

CSS hide scroll bar, but have element scrollable

if you really want to get rid of the scrollbar, split the information up into two separate pages.

Usability guidelines on scrollbars by Jakob Nielsen:

There are five essential usability guidelines for scrolling and scrollbars:

  • Offer a scrollbar if an area has scrolling content. Don't rely on auto-scrolling or on dragging, which people might not notice.
  • Hide scrollbars if all content is visible. If people see a scrollbar, they assume there's additional content and will be frustrated if they can't scroll.
  • Comply with GUI standards and use scrollbars that look like scrollbars.
  • Avoid horizontal scrolling on Web pages and minimize it elsewhere.
  • Display all important information above the fold. Users often decide whether to stay or leave based on what they can see without scrolling. Plus they only allocate 20% of their attention below the fold.

To make your scrollbar only visible when it is needed (i.e. when there is content to scroll down to), use overflow: auto.

Netbeans how to set command line arguments in Java

I am guessing that you are running the file using Run | Run File (or shift-F6) rather than Run | Run Main Project. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:

Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.

I verified this with a little snippet of code:

public class Junk
{
    public static void main(String[] args)
    {
        for (String s : args)
            System.out.println("arg -> " + s);
    }
}

I set Run -> Arguments to x y z. When I ran the file by itself I got no output. When I ran the project the output was:

arg -> x
arg -> y
arg -> z

How do you delete all text above a certain line

Providing you know these vim commands:

1G -> go to first line in file
G -> go to last line in file

then, the following make more sense, are more unitary and easier to remember IMHO:

d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file

Cheers.

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

jquery clone div and append it after specific div

You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.

$("#car2").clone().insertAfter("div.car_well:last");

How to calculate the median of an array?

Use Arrays.sort and then take the middle element (in case the number n of elements in the array is odd) or take the average of the two middle elements (in case n is even).

  public static long median(long[] l)
  {
    Arrays.sort(l);
    int middle = l.length / 2;
    if (l.length % 2 == 0)
    {
      long left = l[middle - 1];
      long right = l[middle];
      return (left + right) / 2;
    }
    else
    {
      return l[middle];
    }
  }

Here are some examples:

  @Test
  public void evenTest()
  {
    long[] l = {
        5, 6, 1, 3, 2
    };
    Assert.assertEquals((3 + 4) / 2, median(l));
  }

  @Test
  public oddTest()
  {
    long[] l = {
        5, 1, 3, 2, 4
    };
    Assert.assertEquals(3, median(l));
  }

And in case your input is a Collection, you might use Google Guava to do something like this:

public static long median(Collection<Long> numbers)
{
  return median(Longs.toArray(numbers)); // requires import com.google.common.primitives.Longs;
}

Javascript equivalent of php's strtotime()?

Maybe you can exploit a sample function like :

_x000D_
_x000D_
function strtotime(date, addTime){_x000D_
  let generatedTime=date.getTime();_x000D_
  if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds _x000D_
  if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes _x000D_
  if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours _x000D_
  return new Date(generatedTime);_x000D_
}_x000D_
_x000D_
let futureDate = strtotime(new Date(), {_x000D_
    hours: 1, //Adding one hour_x000D_
    minutes: 45 //Adding fourty five minutes_x000D_
  });_x000D_
document.body.innerHTML = futureDate;
_x000D_
_x000D_
_x000D_

`

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

Count all duplicates of each value

You'd want the COUNT operator.

SELECT NUMBER, COUNT(*) 
FROM T_NAME
GROUP BY NUMBER
ORDER BY NUMBER ASC

jQuery autohide element after 5 seconds

jQuery(".success_mgs").show(); setTimeout(function(){ jQuery(".success_mgs").hide();},5000);

Creating NSData from NSString in Swift

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

How to sort by dates excel?

It's actually really easy. Highlight the DATE column and make sure that its set as date in Excel. Highlight everything you want to change, Then go to [DATA]>[SORT]>[COLUMN] and set sorting by date. Hope it helps.

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

How to pass text in a textbox to JavaScript function?

You could either access the element’s value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById:

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

Return date as ddmmyyyy in SQL Server

Just for the record, since SQL 2012 you can use FORMAT, as simple as:

SELECT FORMAT(GETDATE(), 'ddMMyyyy')

(op question is specific about SQL 2008)

Can you have multiple $(document).ready(function(){ ... }); sections?

You can even nest document ready functions inside included html files. Here's an example using jquery:

File: test_main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>
    <div id="main-container">
        <h1>test_main.html</h1>
    </div>

<script>
    $(document).ready( function()
    {
        console.log( 'test_main.html READY' );
        $("#main-container").load("test_embed.html");
    } );
</script>

</body>
</html>

File: test_embed.html

<h1>test_embed.html</h1>
<script>
    $(document).ready( function()
    {
        console.log( 'test_embed.html READY' );
    } );
</script>

Console output:

test_main.html READY                       test_main.html:15
test_embed.html READY                      (program):4

Browser shows:

test_embed.html

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Right click on your folder on your server or local machine and give full permissions to

IIS_IUSRS

that's it.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

python : list index out of range error while iteratively popping elements

You're changing the size of the list while iterating over it, which is probably not what you want and is the cause of your error.

Edit: As others have answered and commented, list comprehensions are better as a first choice and especially so in response to this question. I offered this as an alternative for that reason, and while not the best answer, it still solves the problem.

So on that note, you could also use filter, which allows you to call a function to evaluate the items in the list you don't want.

Example:

>>> l = [1,2,3,0,0,1]
>>> filter(lambda x: x > 0, l)
[1, 2, 3]

Live and learn. Simple is better, except when you need things to be complex.

Copying sets Java

Starting from Java 10:

Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);

Set.copyOf() returns an unmodifiable Set containing the elements of the given Collection.

The given Collection must not be null, and it must not contain any null elements.

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

Run cmd commands through Java

one of the way to execute cmd from java !

public void executeCmd() {
    String anyCommand="your command";
    try {
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Find all elements with a certain attribute value in jquery

$('div[imageId="imageN"]').each(function() {
    // `this` is the div
});

To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I have worked with Xamarin. Here are the positives and negatives I have found:

Positives

  1. Easy to code, C# makes the job easier
  2. Performance won't be a concern
  3. Native UI
  4. Good IDE, much like Xcode and Visual Studio.
  5. Xamarin Debugger
  6. Xamarin SDK is free and open-source. Wiki

Negatives

  1. You need to know the API for each platform you want to target (iOS, Android, WP8). However, you do not need to know Objective-C or Java.
  2. Xamarin shares only a few things across platforms (things like databases and web services).
  3. You have to design the UI of each platform separately (this can be a blessing or a curse).

How to change Elasticsearch max memory size

For anyone looking to do this on Centos 7 or with another system running SystemD, you change it in

/etc/sysconfig/elasticsearch 

Uncomment the ES_HEAP_SIZE line, and set a value, eg:

# Heap Size (defaults to 256m min, 1g max)
ES_HEAP_SIZE=16g

(Ignore the comment about 1g max - that's the default)

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

How to show PIL images on the screen?

From near the beginning of the PIL Tutorial:

Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let's display the image we just loaded:

     >>> im.show()

Update:

Nowadays theImage.show() method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.

How best to read a File into List<string>

List<string> lines = new List<string>();
 using (var sr = new StreamReader("file.txt"))
 {
      while (sr.Peek() >= 0)
          lines.Add(sr.ReadLine());
 }

i would suggest this... of Groo's answer.

Better way to right align text in HTML Table

Use jquery to apply class to all tr unobtrusively.

$(”table td”).addClass(”right-align-class");

Use enhanced filters on td in case you want to select a particular td.

See jquery

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Login with windows authentication mode and fist of all make sure that the sa authentication is enabled in the server, I am using SQL Server Management Studio, so I will show you how to do this there.

Right click on the server and click on Properties.

enter image description here

Now go to the Security section and select the option SQL Server and Windows Authentication mode

enter image description here

Once that is done, click OK. And then enable the sa login.

Go to your server, click on Security and then Logins, right click on sa and then click on Properties.

enter image description here

Now go tot Status and then select Enabled under Login. Then, click OK.

Now we can restart the SQLExpress, or the SQL you are using. Go to Services and Select the SQL Server and then click on Restart. Now open the SQL Server Management Studio and you should be able to login as sa user.

Measuring execution time of a function in C++

I recommend using steady_clock which is guarunteed to be monotonic, unlike high_resolution_clock.

#include <iostream>
#include <chrono>

using namespace std;

unsigned int stopwatch()
{
    static auto start_time = chrono::steady_clock::now();

    auto end_time = chrono::steady_clock::now();
    auto delta    = chrono::duration_cast<chrono::microseconds>(end_time - start_time);

    start_time = end_time;

    return delta.count();
}

int main() {
  stopwatch(); //Start stopwatch
  std::cout << "Hello World!\n";
  cout << stopwatch() << endl; //Time to execute last line
  for (int i=0; i<1000000; i++)
      string s = "ASDFAD";
  cout << stopwatch() << endl; //Time to execute for loop
}

Output:

Hello World!
62
163514

How to determine if a string is a number with C++?

Here is a solution for checking positive integers:

bool isPositiveInteger(const std::string& s)
{
    return !s.empty() && 
           (std::count_if(s.begin(), s.end(), std::isdigit) == s.size());
}

Check if string contains only digits

Here's a Solution without using regex

const  isdigit=(value)=>{
    const val=Number(value)?true:false
    console.log(val);
    return val
}

isdigit("10")//true
isdigit("any String")//false

Unable to execute dex: Multiple dex files define

I'm leaving this answer for someone who gets in this scenario as I did.

I stumbled here and there before noticing that I mistakenly dragged and dropped the Support Library JAR file into my src folder and it was lying there. Since I had no idea how it happened or when I dropped it there, I could never imagine something was wrong there.

I was getting the same error, I found the problem after sometime and removed it. Project is now working fine.

LINQ - Left Join, Group By, and Count

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

How do I call ::CreateProcess in c++ to launch a Windows executable?

There is an example at http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx

Just replace the argv[1] with your constant or variable containing the program.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

accepting HTTPS connections with self-signed certificates

The top answer didn´t work for me. After some investigation I found the required information on "Android Developer": https://developer.android.com/training/articles/security-ssl.html#SelfSigned

Creating an empty implementation of X509TrustManager did the trick:

private static class MyTrustManager implements X509TrustManager
{

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
         throws CertificateException
    {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException
    {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers()
    {
        return null;
    }

}

...

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
try
{
    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManager[] tmlist = {new MyTrustManager()};
    context.init(null, tmlist, null);
    conn.setSSLSocketFactory(context.getSocketFactory());
}
catch (NoSuchAlgorithmException e)
{
    throw new IOException(e);
} catch (KeyManagementException e)
{
    throw new IOException(e);
}
conn.setRequestMethod("GET");
int rcode = conn.getResponseCode();

Please be aware that this empty implementation of TustManager is just an example and using it in a productive environment would cause a severe security threat!

Should I use the datetime or timestamp data type in MySQL?

Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field.

If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native format. You can do calculations within MySQL that way ("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)") and it is simple to change the format of the value to a UNIX timestamp ("SELECT UNIX_TIMESTAMP(my_datetime)") when you query the record if you want to operate on it with PHP.

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

milliseconds to time in javascript

function millisecondsToTime(milli)
{
      var milliseconds = milli % 1000;
      var seconds = Math.floor((milli / 1000) % 60);
      var minutes = Math.floor((milli / (60 * 1000)) % 60);

      return minutes + ":" + seconds + "." + milliseconds;
}

How to round up value C# to the nearest integer?

Use Math.Ceiling to round up

Math.Ceiling(0.5); // 1

Use Math.Round to just round

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1

And Math.Floor to round down

Math.Floor(0.5); // 0

How to assign a NULL value to a pointer in python?

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples

Run javascript function when user finishes typing instead of on key up?

The chosen answer above does not work.

Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

And the same code in vanilla JavaScript solution:

//setup before functions
let typingTimer;                //timer identifier
let doneTypingInterval = 5000;  //time in ms (5 seconds)
let myInput = document.getElementById('myInput');

//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

This solution does use ES6 but it's not necessary here. Just replace let with var and the arrow function with a regular function.

Open another application from your own (intent)

Open application if it is exist, or open Play Store application for install it:

private void open() {
    openApplication(getActivity(), "com.app.package.here");
}

public void openApplication(Context context, String packageN) {
    Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
    if (i != null) {
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
        }
    }
}

Selecting default item from Combobox C#

this is the correct form:

comboBox1.Text = comboBox1.Items[0].ToString();

U r welcome

How to set a hidden value in Razor

While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.

@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)

Html attributes for EditorFor() in ASP.NET MVC

Html.TextBoxFor(model => model.Control.PeriodType, 
    new { @class="text-box single-line"})

you can use like this ; same output with Html.EditorFor ,and you can add your html attributes

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Radio Buttons "Checked" Attribute Not Working

_x000D_
_x000D_
**Radio button aria-checked: true or false one at a time**_x000D_
_x000D_
$('input:radio[name=anynameofinput]').change(function() {_x000D_
            if (this.value === 'value1') {_x000D_
                $("#id1").attr("aria-checked","true");_x000D_
                $("#id2").attr("aria-checked","false");_x000D_
            }_x000D_
            else if (this.value === 'value2') {;_x000D_
                $("#id2").attr("aria-checked","true");_x000D_
                $("#id1").attr("aria-checked","false");_x000D_
            }_x000D_
   });
_x000D_
_x000D_
_x000D_

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Using IF ELSE statement based on Count to execute different Insert statements

If this is in SQL Server, your syntax is correct; however, you need to reference the COUNT(*) as the Total Count from your nested query. This should give you what you need:

SELECT CASE WHEN TotalCount >0 THEN 'TRUE' ELSE 'FALSE' END FROM
(
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) DerivedTable

Using this, you could assign TotalCount to a variable and then use an IF ELSE statement to execute your INSERT statements:

DECLARE @TotalCount int
SELECT @TotalCount = TotalCount FROM
(
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) DerivedTable
IF @TotalCount > 0
    -- INSERT STATEMENT 1 GOES HERE
ELSE
    -- INSERT STATEMENT 2 GOES HERE

Convert List to Pandas Dataframe Column

You can directly call the

pd.DataFrame()

method and pass your list as parameter.

l = ['Thanks You','Its fine no problem','Are you sure']
pd.DataFrame(l)

Output:

                      0
0            Thanks You
1   Its fine no problem
2          Are you sure

And if you have multiple lists and you want to make a dataframe out of it.You can do it as following:

import pandas as pd
names =["A","B","C","D"]
salary =[50000,90000,41000,62000]
age = [24,24,23,25]
data = pd.DataFrame([names,salary,age]) #Each list would be added as a row
data = data.transpose() #To Transpose and make each rows as columns
data.columns=['Names','Salary','Age'] #Rename the columns
data.head()

Output:

    Names   Salary  Age
0       A    50000   24
1       B    90000   24
2       C    41000   23
3       D    62000   25

Invoke native date picker from web-app on iOS/Android

In HTML:

  <form id="my_form"><input id="my_field" type="date" /></form>

In JavaScript

_x000D_
_x000D_
   // test and transform if needed_x000D_
    if($('#my_field').attr('type') === 'text'){_x000D_
        $('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd');  _x000D_
    };_x000D_
_x000D_
    // check_x000D_
    if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
        $('#my_field').removeClass('bad');_x000D_
    } else {_x000D_
        $('#my_field').addClass('bad');_x000D_
    };
_x000D_
_x000D_
_x000D_

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

How to order citations by appearance using BibTeX?

I'm a bit new to Bibtex (and to Latex in general) and I'd like to revive this old post since I found it came up in many of my Google search inquiries about the ordering of a bibliography in Latex.

I'm providing a more verbose answer to this question in the hope that it might help some novices out there facing the same difficulties as me.

Here is an example of the main .tex file in which the bibliography is called:

\documentclass{article}
\begin{document}

So basically this is where the body of your document goes.

``FreeBSD is easy to install,'' said no one ever \cite{drugtrafficker88}.

``Yeah well at least I've got chicken,'' said Leeroy Jenkins \cite{goodenough04}.

\newpage
\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited
\bibliography{references} % Or whatever your .bib file is called
\end{document}

...and an example of the .bib file itself:

@ARTICLE{ goodenough04,
AUTHOR    = "G. D. Goodenough and others", 
TITLE     = "What it's like to have a sick-nasty last name",
JOURNAL   = "IEEE Trans. Geosci. Rem. Sens.",
YEAR      = "xxxx",
volume    = "xx",
number    = "xx",
pages     = "xx--xx"
}
@BOOK{ drugtrafficker88,
AUTHOR    = "G. Drugtrafficker", 
TITLE     = "What it's Like to Have a Misleading Last Name",
YEAR      = "xxxx",
PUBLISHER = "Harcourt Brace Jovanovich, Inc."
ADDRESS   = "The Florida Alps, FL, USA"
}

Note the references in the .bib file are listed in reverse order but the references are listed in the order they are cited in the paper.

More information on the formatting of your .bib file can be found here: http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Printing everything except the first field with awk

awk '{ tmp = $1; sub(/^[^ ]+ +/, ""); print $0, tmp }'

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{item.name}}
  </option>
</select>

byId(item1: ItemModel, item2: ItemModel) {
  return item1.id === item2.id;
}

Some tutorial here

Import SQL file by command line in Windows 7

To import database from dump file (in this case called filename.sql)

    use: mysql -u username -p password database_name < filename.sql 

you are on Windows you will need to open CMD and go to directory where mysql.exe is installed. you are using WAMP server then this is usually located in: C:\wamp\bin\mysql\mysql5.5.8\bin (*note the version of mysql might be different)

So you will: cd C:\wamp\bin\mysql\mysql5.5.8\bin

and then execute one of the above commands. Final command like this

    C:\wamp\bin\mysql\mysql5.5.8\bin>mysql -u rootss -p pwdroot testdatabasename < D:\test\Projects\test_demo_db.sql

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

Drop view if exists

To cater for the schema as well, use this format in SQL 2014

if exists(select 1 from sys.views V inner join sys.[schemas] S on  v.schema_id = s.schema_id where s.name='dbo' and v.name = 'someviewname' and v.type = 'v')
  drop view [dbo].[someviewname];
go

And just throwing it out there, to do stored procedures, because I needed that too:

if exists(select 1
          from sys.procedures p
          inner join sys.[schemas] S on p.schema_id = s.schema_id
          where
              s.name='dbo' and p.name = 'someprocname'
          and p.type in ('p', 'pc')
  drop procedure [dbo].[someprocname];
go

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set

header('Content-type: text/plain');

How do I test if a variable does not equal either of two values?

You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.

You want:

var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
    do stuff;
}
else {
    do other stuff;
}

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Attempted to read or write protected memory

In my case fonts used in one of the shared library was not installed in the system.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Bootstrap: how do I change the width of the container?

Here is the solution :

@media (min-width: 1200px) {
    .container{
        max-width: 970px;
    }
}

The advantage of doing this, versus customizing Bootstrap as in @Bastardo's answer, is that it doesn't change the Bootstrap file. For example, if using a CDN, you can still download most of Bootstrap from the CDN.

How to pass parameter to function using in addEventListener?

In the first line of your JS code:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelection by placing (this) behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.


In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.

If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

select.addEventListener('change', getSelection, false);

If that is not what you want, you'd best bind your value for this to the function you're passing to addEventListener:

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bind part is also a call, but this call just returns the same function we're calling bind on, with the value for this inside that function scope fixed to thisArg, effectively overriding the dynamic nature of this-binding.


To get to your actual question: "How to pass parameters to function in addEventListener?"

You would have to use an additional function definition:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of this inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection function.


We also might again have an object of our choice to be this inside the outer callback:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);

How can I use a custom font in Java?

If you want to use the font to draw with graphics2d or similar, this works:

InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)

Get record counts for all tables in MySQL database

SELECT SUM(TABLE_ROWS) 
     FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_SCHEMA = '{your_db}';

Note from the docs though: For InnoDB tables, the row count is only a rough estimate used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).

Test if number is odd or even

PHP is converting null and an empty string automatically to a zero. That happens with modulo as well. Therefor will the code

$number % 2 == 0 or !($number & 1)

with value $number = '' or $number = null result in true. I test it therefor somewhat more extended:

function testEven($pArg){
    if(is_int($pArg) === true){
        $p = ($pArg % 2);
        if($p === 0){
            print "The input '".$pArg."' is even.<br>";
        }else{
            print "The input '".$pArg."' is odd.<br>";
        }
    }else{
        print "The input '".$pArg."' is not a number.<br>";
    }
}

The print is there for testing purposes, hence in practice it becomes:
function testEven($pArg){
    if(is_int($pArg)=== true){
        return $pArg%2;
    }
    return false;
}

This function returns 1 for any odd number, 0 for any even number and false when it is not a number. I always write === true or === false to let myself (and other programmers) know that the test is as intended.

Difference between \b and \B in regex

\b is used as word boundary

word = "categorical cat"

Find all "cat" in the above word

without \b

re.findall(r'cat',word)
['cat', 'cat']

with \b

re.findall(r'\bcat\b',word)
['cat']

The simplest way to comma-delimit a list?

In my opinion, this is the simplest to read and understand:

StringBuilder sb = new StringBuilder();
for(String string : strings) {
    sb.append(string).append(',');
}
sb.setLength(sb.length() - 1);
String result = sb.toString();

Convert boolean result into number/integer

I just came across this shortcut today.

~~(true)

~~(false)

People much smarter than I can explain:

http://james.padolsey.com/javascript/double-bitwise-not/

What is the cleanest way to disable CSS transition effects temporarily?

I would advocate disabling animation as suggested by DaneSoul, but making the switch global:

/*kill the transitions on any descendant elements of .notransition*/
.notransition * { 
  -webkit-transition: none !important; 
  -moz-transition: none !important; 
  -o-transition: none !important; 
  -ms-transition: none !important; 
  transition: none !important; 
} 

.notransition can be then applied to the body element, effectively overriding any transition animation on the page:

$('body').toggleClass('notransition');

Extract source code from .jar file

You can extract a jar file with the command :

jar xf filename.jar

References : Oracle's JAR documentation

Pointer arithmetic for void pointer in C

Final conclusion: arithmetic on a void* is illegal in both C and C++.

GCC allows it as an extension, see Arithmetic on void- and Function-Pointers (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allow void* arithmetic for the purposes of compatibility with GCC. Other compilers (such as MSVC) disallow arithmetic on void*, and GCC disallows it if the -pedantic-errors flag is specified, or if the -Werror-pointer-arith flag is specified (this flag is useful if your code base must also compile with MSVC).

The C Standard Speaks

Quotes are taken from the n1256 draft.

The standard's description of the addition operation states:

6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.

So, the question here is whether void* is a pointer to an "object type", or equivalently, whether void is an "object type". The definition for "object type" is:

6.2.5.1: Types are partitioned into object types (types that fully describe objects) , function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).

And the standard defines void as:

6.2.5-19: The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation.

Therefore you cannot perform pointer arithmetic on a void pointer.

Notes

Originally, it was thought that void* arithmetic was permitted, because of these sections of the C standard:

6.2.5-27: A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.

However,

The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

So this means that printf("%s", x) has the same meaning whether x has type char* or void*, but it does not mean that you can do arithmetic on a void*.

Editor's note: This answer has been edited to reflect the final conclusion.

How to use border with Bootstrap

If you need a basic border around you just need to use bootstrap wells.

For example the code below:

<div class="well">Basic Well</div>

How to make type="number" to positive numbers only

I cannot find the perfect solution as some work for inputting but not for copy&paste, some are the other way around. This solution works for me. It prevents from negative number, typing "e", copy&paste "e" text.

create a function.

<script language="JavaScript">

  // this prevents from typing non-number text, including "e".
  function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    let charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
      evt.preventDefault();
    } else {
      return true;
    }
  }
</script>

add these properties to input. this two prevent from copy&paste non-number text, including "e". you need to have both together to take effect.

<input type="number" oninput="validity.valid||(value='');" onpress="isNumber(event)" />

If you are using Vue you can refer this answer here. I have extracted it to a mixin which can be reused.

Initializing array of structures

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point { int x, y; };

the following initialization

struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

struct point p = { xvalue, yvalue };

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:', as shown here:

struct point p = { y: yvalue, x: xvalue };

You can also write:

my_data data[] = {
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

as:

my_data data[] = {
    [0] = { .name = "Peter" },
    [1] = { .name = "James" },
    [2] = { .name = "John" },
    [3] = { .name = "Mike" }
}; 

or:

my_data data[] = {
    [0].name = "Peter",
    [1].name = "James",
    [2].name = "John",
    [3].name = "Mike"
}; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = {
    [3].name = "Mike",
    [1].name = "James",
    [0].name = "Peter",
    [2].name = "John"
}; 

If you have multiple fields in your struct (for example, an int age), you can initialize all of them at once using the following:

my_data data[] = {
    [3].name = "Mike",
    [2].age = 40,
    [1].name = "James",
    [3].age = 23,
    [0].name = "Peter",
    [2].name = "John"
}; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Make the id parameter be a nullable int:

public ActionResult Edit(int? id, User collection)

And then add the validation:

if (Id == null) ...

What is a Y-combinator?

A fixed point combinator (or fixed-point operator) is a higher-order function that computes a fixed point of other functions. This operation is relevant in programming language theory because it allows the implementation of recursion in the form of a rewrite rule, without explicit support from the language's runtime engine. (src Wikipedia)

JavaScript check if variable exists (is defined/initialized)

You could use a try...catch block like the following:

_x000D_
_x000D_
var status = 'Variable exists'

try {
  myVar
} catch (ReferenceError) {
  status = 'Variable does not exist'
}

console.log(status)
_x000D_
_x000D_
_x000D_

A disadvantage is you cannot put it in a function as it would throw a ReferenceError

_x000D_
_x000D_
function variableExists(x) {
  var status = true
  try {
    x
  } catch (ReferenceError) {
    status = false
  }
  
  return status
}

console.log(variableExists(x))
_x000D_
_x000D_
_x000D_

Edit:

If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:

_x000D_
_x000D_
function globalVariableExists(variable) {
  if (window[variable] != undefined) {
    return true
  }
  
  return false
}

var x = undefined

console.log(globalVariableExists("x"))

console.log(globalVariableExists("y"))

var z = 123

console.log(globalVariableExists("z"))
_x000D_
_x000D_
_x000D_

Edit 2:

If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:

_x000D_
_x000D_
function variableExists(variable, thisObj) {
  if (thisObj[variable] !== undefined) {
    return true
  }
  
  return false
}

class someClass {
  constructor(name) { 
    this.x = 99
    this.y = 99
    this.z = 99
    this.v = 99
    
    console.log(variableExists(name, this))
  }
}

new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
_x000D_
_x000D_
_x000D_

Angular - Set headers for every request

Here is an improved version of the accepted answer, updated for Angular2 final :

import {Injectable} from "@angular/core";
import {Http, Headers, Response, Request, BaseRequestOptions, RequestMethod} from "@angular/http";
import {I18nService} from "../lang-picker/i18n.service";
import {Observable} from "rxjs";
@Injectable()
export class HttpClient {

    constructor(private http: Http, private i18n: I18nService ) {}

    get(url:string):Observable<Response> {
        return this.request(url, RequestMethod.Get);
    }

    post(url:string, body:any) {   
        return this.request(url, RequestMethod.Post, body);
    }

    private request(url:string, method:RequestMethod, body?:any):Observable<Response>{

        let headers = new Headers();
        this.createAcceptLanguageHeader(headers);

        let options = new BaseRequestOptions();
        options.headers = headers;
        options.url = url;
        options.method = method;
        options.body = body;
        options.withCredentials = true;

        let request = new Request(options);

        return this.http.request(request);
    }

    // set the accept-language header using the value from i18n service that holds the language currently selected by the user
    private createAcceptLanguageHeader(headers:Headers) {

        headers.append('Accept-Language', this.i18n.getCurrentLang());
    }
}

Of course it should be extended for methods like delete and put if needed (I don't need them yet at this point in my project).

The advantage is that there is less duplicated code in the get/post/... methods.

Note that in my case I use cookies for authentication. I needed the header for i18n (the Accept-Language header) because many values returned by our API are translated in the user's language. In my app the i18n service holds the language currently selected by the user.

tr:hover not working

Also try thistr:hover td {color: aqua;} `

How to open an external file from HTML

Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='http://server/directory/file.xlsx'

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

You can do this easily with the KoGrid plugin for KnockoutJS.

<script type="text/javascript">
    $(function () {
        window.viewModel = {
            myObsArray: ko.observableArray([
                { id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
                { id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
                { id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
                { id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
            ])
        };

        ko.applyBindings(viewModel);
    });
</script>

<div data-bind="koGrid: { data: myObsArray }">

Sample

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Adding a default value in dropdownlist after binding with database

The solution provided by Justin should work. To be sure making use of SelectedIndex property will also help.

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };

ddlColor.DataTextField = "Color";
ddlColor.DataBind();

ddlColor.Items.Insert(0, new ListItem("Select Color", ""); 
ddlColor.SelectedIndex = 0;

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

addID in jQuery?

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

database_password: password would between quotes: " or '.

like so:

database_password: "password"

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

How to prevent custom views from losing state across screen orientation changes

Here is another variant that uses a mix of the two above methods. Combining the speed and correctness of Parcelable with the simplicity of a Bundle:

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    // The vars you want to save - in this instance a string and a boolean
    String someString = "something";
    boolean someBoolean = true;
    State state = new State(super.onSaveInstanceState(), someString, someBoolean);
    bundle.putParcelable(State.STATE, state);
    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        State customViewState = (State) bundle.getParcelable(State.STATE);
        // The vars you saved - do whatever you want with them
        String someString = customViewState.getText();
        boolean someBoolean = customViewState.isSomethingShowing());
        super.onRestoreInstanceState(customViewState.getSuperState());
        return;
    }
    // Stops a bug with the wrong state being passed to the super
    super.onRestoreInstanceState(BaseSavedState.EMPTY_STATE); 
}

protected static class State extends BaseSavedState {
    protected static final String STATE = "YourCustomView.STATE";

    private final String someText;
    private final boolean somethingShowing;

    public State(Parcelable superState, String someText, boolean somethingShowing) {
        super(superState);
        this.someText = someText;
        this.somethingShowing = somethingShowing;
    }

    public String getText(){
        return this.someText;
    }

    public boolean isSomethingShowing(){
        return this.somethingShowing;
    }
}

How should the ViewModel close the form?

I've read all the answers but I must say, most of them are just not good enough or even worse.

You could handle this beatifully with DialogService class which responsibility is to show dialog window and return dialog result. I have create sample project demonstrating it's implementation and usage.

here are most important parts:

//we will call this interface in our viewmodels
public interface IDialogService
{
    bool? ShowDialog(object dialogViewModel, string caption);
}

//we need to display logindialog from mainwindow
public class MainWindowViewModel : ViewModelBase
{
    public string Message {get; set;}
    public void ShowLoginCommandExecute()
    {
        var loginViewModel = new LoginViewModel();
        var dialogResult = this.DialogService.ShowDialog(loginViewModel, "Please, log in");

        //after dialog is closed, do someting
        if (dialogResult == true && loginViewModel.IsLoginSuccessful)
        {
            this.Message = string.Format("Hello, {0}!", loginViewModel.Username);
        }
    }
}


public class DialogService : IDialogService
{
    public bool? ShowDialog(object dialogViewModel, string caption)
    {
        var contentView = ViewLocator.GetView(dialogViewModel);
        var dlg = new DialogWindow
        {
            Title = caption
        };
        dlg.PART_ContentControl.Content = contentView;

        return dlg.ShowDialog();
    }
}

Isn't this just simpler? more straitforward, more readable and last but not least easier to debug than EventAggregator or other similar solutions?

as you can see, In my view models I'm have used ViewModel first approach described in my post here: Best practice for calling View from ViewModel in WPF

Of course, in real world, the DialogService.ShowDialog must have more option to configure the dialog, e.g. buttons and commands they should execute. There are different way of doing so, but its out of scope :)

How can I stop the browser back button using JavaScript?

None of the most-upvoted answers worked for me in Chrome 79. It looks like Chrome changed its behavior with respect to the Back button after version 75. See here:

https://support.google.com/chrome/thread/8721521?hl=en

However, in that Google thread, the answer provided by Azrulmukmin Azmi at the very end did work. This is his solution.

<script>
    history.pushState(null, document.title, location.href);
    history.back();
    history.forward();
    window.onpopstate = function () {
        history.go(1);
    };
</script>

The problem with Chrome is that it doesn't trigger onpopstate event unless you make browser action ( i.e. call history.back). That's why I've added those to script.

I don't entirely understand what he wrote, but apparently an additional history.back() / history.forward() is now required for blocking Back in Chrome 75+.

Merge unequal dataframes and replace missing rows with 0

Assuming df1 has all the values of x of interest, you could use a dplyr::left_join() to merge and then either a base::replace() or tidyr::replace_na() to replace the NAs as 0s:

library(tidyverse)

# dplyr only:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace(y, is.na(y), 0))

# dplyr and tidyr:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace_na(y, 0))

# In the sample data column `x` is a factor, which will give a warning with the join. This can be prevented by converting to a character before the join:
df_new <- 
  left_join(df1 %>% mutate(x = as.character(x)), 
            df2 %>% mutate(x = as.character(x)), 
            by = 'x') %>% 
    mutate(y = replace(y, is.na(y), 0))

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

Button background as transparent

We can use attribute android:background in Button xml like below.

android:background="?android:attr/selectableItemBackground"

Or we can use style

style="?android:attr/borderlessButtonStyle" for transparent and shadow less background.

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

How to access the contents of a vector from a pointer to the vector in C++?

vector<int> v;
v.push_back(906);
vector<int> * p = &v;
cout << (*p)[0] << endl;

Kill all processes for a given user

Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

pkill -9 -u `id -u username`

Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

Fastest way to determine if an integer's square root is an integer

Newton's Method with integer arithmetic

If you wish to avoid non-integer operations you could use the method below. It basically uses Newton's Method modified for integer arithmetic.

/**
 * Test if the given number is a perfect square.
 * @param n Must be greater than 0 and less
 *    than Long.MAX_VALUE.
 * @return <code>true</code> if n is a perfect
 *    square, or <code>false</code> otherwise.
 */
public static boolean isSquare(long n)
{
    long x1 = n;
    long x2 = 1L;

    while (x1 > x2)
    {
        x1 = (x1 + x2) / 2L;
        x2 = n / x1;
    }

    return x1 == x2 && n % x1 == 0L;
}

This implementation can not compete with solutions that use Math.sqrt. However, its performance can be improved by using the filtering mechanisms described in some of the other posts.

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

no module named zlib

For the case I met, I found there are missing modules after make. So I did the following:

  1. install zlib-devel
  2. make and install python again.