Programs & Examples On #Rightfax

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Vim: insert the same characters across multiple lines

  1. Move the cursor to the n in name.
  2. Enter visual block mode (Ctrlv).
  3. Press j three times (or 3j).
  4. Press I (capital i).
  5. Type in vendor_. Note: It will only update the screen in the first line - until Esc is pressed (6.), at which point all lines will be updated.
  6. Press Esc.

mini-screencast demonstrating the method

An uppercase I must be used rather than a lowercase i, because the lowercase i is interpreted as the start of a text object, which is rather useful on its own, e.g. for selecting inside a tag block (it):

mini-screencast showing the usefulness of the 'it' text object

Sum across multiple columns with dplyr

I would use regular expression matching to sum over variables with certain pattern names. For example:

df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
                    sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))

This way you can create more than one variable as a sum of certain group of variables of your data frame.

How to disable all <input > inside a form with jQuery?

Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true)

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

Error when trying vagrant up

Check the following entry in your Vagrantfile

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "base"

This is the default file setting which is created with vagrant init command. But what you need to do is do initialise vagrant environment with an OS box. For instance $vagrant init centos/7. And the Vagrantfile will look something like this:

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "centos/7"

This will resolve the error of not found base when doing a vagrant up.

Angular 2 Sibling Component Communication

A directive can make sense in certain situations to 'connect' components. In fact the things being connected don't even need to be full components, and sometimes it's more lightweight and actually simpler if they aren't.

For example I've got a Youtube Player component (wrapping Youtube API) and I wanted some controller buttons for it. The only reason the buttons aren't part of my main component is that they're located elsewhere in the DOM.

In this case it's really just an 'extension' component that will only ever be of use with the 'parent' component. I say 'parent', but in the DOM it is a sibling - so call it what you will.

Like I said it doesn't even need to be a full component, in my case it's just a <button> (but it could be a component).

@Directive({
    selector: '[ytPlayerPlayButton]'
})
export class YoutubePlayerPlayButtonDirective {

    _player: YoutubePlayerComponent; 

    @Input('ytPlayerVideo')
    private set player(value: YoutubePlayerComponent) {
       this._player = value;    
    }

    @HostListener('click') click() {
        this._player.play();
    }

   constructor(private elementRef: ElementRef) {
       // the button itself
   }
}

In the HTML for ProductPage.component, where youtube-player is obviously my component that wraps the Youtube API.

<youtube-player #technologyVideo videoId='NuU74nesR5A'></youtube-player>

... lots more DOM ...

<button class="play-button"        
        ytPlayerPlayButton
        [ytPlayerVideo]="technologyVideo">Play</button>

The directive hooks everything up for me, and I don't have to declare the (click) event in the HTML.

So the directive can nicely connect to the video player without having to involve ProductPage as a mediator.

This is the first time I've actually done this, so not yet sure how scalable it might be for much more complex situations. For this though I'm happy and it leaves my HTML simple and responsibilities of everything distinct.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Faced similar issue. I tried installing mysql-python using pip, but it failed due to gcc dependency errors.

The solution that worked for me

conda install mysql-python

Please note that I already had anaconda installed, which didn't had gcc dependency.

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

if you have more than one classes in your classifier, you might want to use pandas-ml at that part. Confusion Matrix of pandas-ml give more detailed information. check that

RESULT

Default background color of SVG root element

Let me report a very simple solution I found, that is not written in previous answers. I also wanted to set background in an SVG, but I also want that this works in a standalone SVG file.

Well, this solution is really simple, in fact SVG supports style tags, so you can do something like

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
  <style>svg { background-color: red; }</style>
  <text>hello</text>
</svg>

How to change default timezone for Active Record in Rails?

In Ruby on Rails 6.0.1 go to config > locales > application.rb y agrega lo siguiente:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module CrudRubyOnRails6
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    config.active_record.default_timezone = :local
    config.time_zone = 'Lima'

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

You can see that I am configuring the time zone with 2 lines:

config.active_record.default_timezone =: local
config.time_zone = 'Lima'

I hope it helps those who are working with Ruby on Rails 6.0.1

Extract time from date String

A very simple way is to use Formatter (see date time conversions) or more directly String.format as in

String.format("%tR", new Date())

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

Convert NSDate to NSString

#ios #swift #convertDateinString

Simply just do like this to "convert date into string" as per format you passed:

let formatter = DateFormatter()

formatter.dateFormat = "dd-MM-YYYY" // pass formate here
        
let myString = formatter.string(from: date) // this will convert Date in String

Note: You can specify different formats such like "yyyy-MM-dd", "yyyy", "MM" etc...

Check if a specific tab page is selected (active)

I think that using the event tabPage1.Enter is more convenient.

tabPage1.Enter += new System.EventHandler(tabPage1_Enter);

private void tabPage1_Enter(object sender, EventArgs e)
{
    MessageBox.Show("you entered tabPage1");
}

This is better than having nested if-else statement when you have different logic for different tabs. And more suitable in case new tabs may be added in the future.

Note that this event fires if the form loads and tabPage1 is opened by default.

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

Difference between RUN and CMD in a Dockerfile

There has been enough answers on RUN and CMD. I just want to add a few words on ENTRYPOINT. CMD arguments can be overwritten by command line arguments, while ENTRYPOINT arguments are always used.

This article is a good source of information.

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

Ansible: get current target host's IP address

The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)

This will print ip's in quotes also to avoid confusion in using config files.

_x000D_
_x000D_
>> main.yml_x000D_
_x000D_
---_x000D_
- hosts: localhost_x000D_
  tasks:_x000D_
    - name: ipify_x000D_
      ipify_facts:_x000D_
    - debug: var=hostvars[inventory_hostname]['ipify_public_ip']_x000D_
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']_x000D_
    - name: template_x000D_
      template:_x000D_
        src: debug.j2_x000D_
        dest: /tmp/debug.ansible_x000D_
_x000D_
>> templates/debug.j2_x000D_
_x000D_
public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}_x000D_
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"_x000D_
_x000D_
default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}_x000D_
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
_x000D_
_x000D_
_x000D_

Vue.js: Conditional class style binding

<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}

How to get the current URL within a Django template?

You can get the url without parameters by using {{request.path}} You can get the url with parameters by using {{request.get_full_path}}

Questions every good .NET developer should be able to answer?

Good questions I have been asked are

  • What do you think is good about .NET?
  • What do you think is bad about .NET?

It would be interesting to see what a candidate would come up with and you'll certainly learn quite a bit about how he/she uses the framework.

SQL Server : fetching records between two dates?

You need to be more explicit and add the start and end times as well, down to the milliseconds:

select * 
from xxx 
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'

The database can very well interpret '2012-10-27' as '2012-10-27 00:00:00.000'.

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

YES the warning is backwards.

And in fact it shouldn't even be a warning in the first place. Because all this warning is saying (but backwards unfortunately) is that the CRLF characters in your file with Windows line endings will be replaced with LF's on commit. Which means it's normalized to the same line endings used by *nix and MacOS.

Nothing strange is going on, this is exactly the behavior you would normally want.

This warning in it's current form is one of two things:

  1. An unfortunate bug combined with an over-cautious warning message, or
  2. A very clever plot to make you really think this through...

;)

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

Finding the id of a parent div using Jquery

$(this).parents('div').attr('id');

scrollable div inside container

_x000D_
_x000D_
function start() {_x000D_
 document.getElementById("textBox1").scrollTop +=5;_x000D_
    scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
 var loc = document.getElementById("textBox1").scrollTop;_x000D_
 document.getElementById("textBox1").scrollTop -= loc;_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start 
_x000D_
_x000D_
_x000D_

Multiple aggregate functions in HAVING clause

Something like this?

HAVING COUNT(caseID) > 2
AND COUNT(caseID) < 4

Enter key in textarea

You could do something like this:

_x000D_
_x000D_
$("#txtArea").on("keypress",function(e) {_x000D_
    var key = e.keyCode;_x000D_
_x000D_
    // If the user has pressed enter_x000D_
    if (key == 13) {_x000D_
        document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
        return false;_x000D_
    }_x000D_
    else {_x000D_
        return true;_x000D_
    }_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
_x000D_
_x000D_

Clear contents of cells in VBA using column reference

The issue is not with the with statement, it is on the Range function, it doesn't accept the absolute cell value.. it should be like Range("A4:B100").. you can refer the following thread for reference..

following code should work.. Convert cells(1,1) into "A1" and vice versa

LastColData = Sheets(WSNAME).Range("A4").End(xlToRight).Column
            LastRowData = Sheets(WSNAME).Range("A4").End(xlDown).Row
            Rng = "A4:" & Sheets(WSNAME).Cells(LastRowData, LastColData).Address(RowAbsolute:=False, ColumnAbsolute:=False)

 Worksheets(WSNAME).Range(Rng).ClearContents

Why can't I do <img src="C:/localfile.jpg">?

Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How do I get the time difference between two DateTime objects using C#?

You need to use a TimeSpan. Here is some sample code:

TimeSpan sincelast = TimeSpan.FromTicks(DateTime.Now.Ticks - LastUpdate.Ticks);

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Convert Text to Date?

Besides other options, I confirm that using

c.Value = CDate(c.Value)

works (just tested with the description of your case, with Excel 2010). As for the reasons for you getting a type mismatch error, you may check (e.g.) this.

It might be a locale issue.

Android: how to make an activity return results to the activity which calls it?

In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.

startActivityForResult(new Intent(“YourFullyQualifiedClassName”),requestCode);

In the activity you can make use of setData() to return result.

Intent data = new Intent();
String text = "Result to be returned...."
//---set the data to pass back---
data.setData(Uri.parse(text));
setResult(RESULT_OK, data);
//---close the activity---
finish();

So then again in the first activity you write the below code in onActivityResult()

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String returnedResult = data.getData().toString();
            // OR
            // String returnedResult = data.getDataString();
        }
    }
}

EDIT based on your comment: If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.

Intent data = new Intent();
data.putExtra("streetkey","streetname");
data.putExtra("citykey","cityname");
data.putExtra("homekey","homename");
setResult(RESULT_OK,data);
finish();

Get them in onActivityResult like below:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String street = data.getStringExtra("streetkey");
            String city = data.getStringExtra("citykey");
            String home = data.getStringExtra("homekey");
        }
    }
}

How to get a index value from foreach loop in jstl

You can use the varStatus attribute like this:-

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.

Hence, you can send that to your javascript method like this:-

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

How do you open a file in C++?

**#include<fstream> //to use file
#include<string>  //to use getline
using namespace std;
int main(){
ifstream file;
string str;
file.open("path the file" , ios::binary | ios::in);
while(true){
   getline(file , str);
   if(file.fail())
       break;
   cout<<str;
}
}**

Try reinstalling `node-sass` on node 0.12?

This answer is a bit orthogonal to the the OP, but --

libsass bindings don't install properly with the node-sass wrapper on Node v4.0.0. I got the same error message as in the question (Error: 'libsass' bindings not found. Try reinstalling 'node-sass') but I ended up uninstalling Node v4.0.0 and installing v0.12.7 using nvm, via this script:

https://gist.github.com/brock/5b1b70590e1171c4ab54

and now libsass and node-sass are behaving properly.

Find index of last occurrence of a substring in a string

Python String rindex() Method

Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].

Syntax
Following is the syntax for rindex() method -

str.rindex(str, beg=0 end=len(string))

Parameters
str - This specifies the string to be searched.

beg - This is the starting index, by default its 0

len - This is ending index, by default its equal to the length of the string.

Return Value
This method returns last index if found otherwise raises an exception if str is not found.

Example
The following example shows the usage of rindex() method.

Live Demo

!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "is";

print str1.rindex(str2)
print str1.index(str2)

When we run above program, it produces following result -

5
2

Ref: Python String rindex() Method - Tutorialspoint

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

I accidentally had two devices connected.

After removing one device, INSTALL_FAILED_UPDATE_INCOMPATIBLE error has gone.

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

How do I show/hide a UIBarButtonItem?

Setting the text color to a clear color when the bar button item is disabled is probably a cleaner option. There's no weirdness that you have to explain in a comment. Also you don't destroy the button so you still keep any associated storyboard segues.

[self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]}
                                                      forState:UIControlStateDisabled];

Then when ever you want the bar button item hidden, you can just do:

self.navigationItem.rightBarButton.enabled = NO;

It's lame there's no hidden property but this offers the same result.

How to change the icon of .bat file programmatically?

If you want an icon for a batch file, first create a link for the batch file as follows

Right click in window folder where you want the link select New -> Shortcut, then specify where the .bat file is.

This creates the .lnk file you wanted. Then you can specify an icon for the link, on its properties page.

Some nice icons are available here:

%SystemRoot%\System32\SHELL32.dll

Note For me on Windows 10: %SystemRoot% == C:\Windows\

More Icons are here: C:\Windows\System32\imageres.dll

Also you might want to have the first line in the batch file to be "cd .." if you stash your batch files in a bat subdirectory one level below where your shortcuts, are supposed to execute.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

POST data in JSON format

Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:

let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];

and then just xhr.send(JSON.stringify(data)); like in Jan's original answer.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

I recommend to use the Using jquery validation plugin and jquery ui date picker

jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
   var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
   if (! re.test(value) ) return false
   // parseDate throws exception if the value is invalid
   try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
   catch(e){return false;} 
   },
   "Please enter a valid date format dd-mm-yyyy"
);

this.ui.form.validate({
    debug: true,
    rules : {
    title : { required : true, minlength: 4 }, 
    date : { required: true, customDateValidator: true }
    }
}) ;

Using Jquery and date picker just create a function with

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
 if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}

You might use only the regular expression for validation

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
return re.test(value) 

Of course the date format should be of your region

When is JavaScript synchronous?

JavaScript is single threaded and has a synchronous execution model. Single threaded means that one command is being executed at a time. Synchronous means one at a time i.e. one line of code is being executed at time in order the code appears. So in JavaScript one thing is happening at a time.

Execution Context

The JavaScript engine interacts with other engines in the browser. In the JavaScript execution stack there is global context at the bottom and then when we invoke functions the JavaScript engine creates new execution contexts for respective functions. When the called function exits its execution context is popped from the stack, and then next execution context is popped and so on...

For example

function abc()
{
   console.log('abc');
}


function xyz()
{
   abc()
   console.log('xyz');
}
var one = 1;
xyz();

In the above code a global execution context will be created and in this context var one will be stored and its value will be 1... when the xyz() invocation is called then a new execution context will be created and if we had defined any variable in xyz function those variables would be stored in the execution context of xyz(). In the xyz function we invoke abc() and then the abc() execution context is created and put on the execution stack... Now when abc() finishes its context is popped from stack, then the xyz() context is popped from stack and then global context will be popped...

Now about asynchronous callbacks; asynchronous means more than one at a time.

Just like the execution stack there is the Event Queue. When we want to be notified about some event in the JavaScript engine we can listen to that event, and that event is placed on the queue. For example an Ajax request event, or HTTP request event.

Whenever the execution stack is empty, like shown in above code example, the JavaScript engine periodically looks at the event queue and sees if there is any event to be notified about. For example in the queue there were two events, an ajax request and a HTTP request. It also looks to see if there is a function which needs to be run on that event trigger... So the JavaScript engine is notified about the event and knows the respective function to execute on that event... So the JavaScript engine invokes the handler function, in the example case, e.g. AjaxHandler() will be invoked and like always when a function is invoked its execution context is placed on the execution context and now the function execution finishes and the event ajax request is also removed from the event queue... When AjaxHandler() finishes the execution stack is empty so the engine again looks at the event queue and runs the event handler function of HTTP request which was next in queue. It is important to remember that the event queue is processed only when execution stack is empty.

For example see the code below explaining the execution stack and event queue handling by Javascript engine.

function waitfunction() {
    var a = 5000 + new Date().getTime();
    while (new Date() < a){}
    console.log('waitfunction() context will be popped after this line');
}

function clickHandler() {
    console.log('click event handler...');   
}

document.addEventListener('click', clickHandler);


waitfunction(); //a new context for this function is created and placed on the execution stack
console.log('global context will be popped after this line');

And

<html>
    <head>

    </head>
    <body>

        <script src="program.js"></script>
    </body>
</html>

Now run the webpage and click on the page, and see the output on console. The output will be

waitfunction() context will be popped after this line
global context will be emptied after this line
click event handler...

The JavaScript engine is running the code synchronously as explained in the execution context portion, the browser is asynchronously putting things in event queue. So the functions which take a very long time to complete can interrupt event handling. Things happening in a browser like events are handled this way by JavaScript, if there is a listener supposed to run, the engine will run it when the execution stack is empty. And events are processed in the order they happen, so the asynchronous part is about what is happening outside the engine i.e. what should the engine do when those outside events happen.

So JavaScript is always synchronous.

Making authenticated POST requests with Spring RestTemplate for Android

Ok found the answer. exchange() is the best way. Oddly the HttpEntity class doesn't have a setBody() method (it has getBody()), but it is still possible to set the request body, via the constructor.

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("field", "value");

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);

How to replace spaces in file names using a bash script

My solution to the problem is a bash script:

#!/bin/bash
directory=$1
cd "$directory"
while [ "$(find ./ -regex '.* .*' | wc -l)" -gt 0 ];
do filename="$(find ./ -regex '.* .*' | head -n 1)"
mv "$filename" "$(echo "$filename" | sed 's|'" "'|_|g')"
done

just put the directory name, on which you want to apply the script, as an argument after executing the script.

ByRef argument type mismatch in Excel VBA

I don't know why, but it is very important to declare the variables separately if you want to pass variables (as variables) into other procedure or function.

For example there is a procedure which make some manipulation with data: based on ID returns Part Number and Quantity information. ID as constant value, other two arguments are variables.

Public Sub GetPNQty(ByVal ID As String, PartNumber As String, Quantity As Long)

the next main code gives me a "ByRef argument mismatch":

Sub KittingScan()  
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty) 

End sub

and the next one is working as well:

Sub KittingScan()
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)

End sub

"for" vs "each" in Ruby

This is the only difference:

each:

irb> [1,2,3].each { |x| }
  => [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
    from (irb):2
    from :0

for:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.

Other than that, for is just syntax sugar for the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

How to get nth jQuery element

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Shell Script: Execute a python program from within a shell script

Save the following program as print.py:

#!/usr/bin/python3
print('Hello World')

Then in the terminal type:

chmod +x print.py
./print.py

How can I check if a key exists in a dictionary?

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

How to use `subprocess` command with pipes

Or you can always use the communicate method on the subprocess objects.

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

The communicate method returns a tuple of the standard output and the standard error.

HTML text input field with currency symbol

Another solution which I prefer is to use an additional input element for an image of the currency symbol. Here's an example using an image of a magnifying glass within a search text field:

html:

<input type="image" alt="Subscribe" src="/graphics/icons/search-button.png">
<input type="text" placeholder="Search" name="query">

css:

#search input[type="image"] {
background-color: transparent;
border: 0 none;
margin-top: 10px;
vertical-align: middle;
margin: 5px 0 0 5px;
position: absolute;
}

This results in the input on the left sidebar here:

https://fsfe.org

WAMP shows error 'MSVCR100.dll' is missing when install

Some times you have to install all versions or a bunch of them.

Anyone who has not found above answers useful , take a look at here

Homebrew install specific version of formula?

Most of the other answers are obsolete by now. Unfortunately Homebrew still doesn’t have a builtin way of installing an outdated version, unless that version exists as a separate formula (e.g. python@2, [email protected] …).

Luckily, for other formulas there’s a much easier way than the convoluted mess that used to be necessary. Here are the full instructions:

  1. Search for the correct version in the logs:

    brew log formula
    # Scroll down/up with j/k or the arrow keys
    # or use eg. /4\.4\.23 to search a specific version
    
    # This syntax only works on pre-2.0 Homebrew versions
    brew log --format=format:%H\ %s -F --grep=‹version› ‹formula›
    

    This will show a list of commit hashes. Take one that is appropriate (mostly it should be pretty obvious, and usually is the most recent (i.e. top) one.

  2. Find the URL at which the formula resides in the upstream repository:

    brew info ‹formula› | grep ^From:
    
  3. Fix the URL:

    1. Replace github.com with raw.githubusercontent.com
    2. Replace blob/master with the commit hash we found in the first step.
  4. Install the desired version by replacing master in the previously found URL by the commit hash, e.g.:

    brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/‹hash›/Formula/‹formula›.rb
    

(The last step may necessitate running brew unlink ‹formula› before.)


If you have copied a commit hash you want to use, you can use something like this example to install that version, replacing the value and bash with your commit hash and your desired formula.

BREW_VERSION_SHA=32353d2286f850fd965e0a48bcf692b83a6e9a41
BREW_FORMULA_NAME=bash
brew info $BREW_FORMULA_NAME \
| sed -n \
    -e '/^From: /s///' \
    -e 's/github.com/raw.githubusercontent.com/' \
    -e 's%blob/%%' \
    -e "s/master/$BREW_VERSION_SHA/p" \
| xargs brew install

This example is installing bash 4.4.23 instead of bash 5, though if you performed a brew upgrade afterward then bash 5 would get installed over top, unless you first executed brew pin bash. Instead to make this smoother WITHOUT pinning, you should first install the latest with brew install bash, then brew unlink bash, then install the older version you want per the script above, and then use brew switch bash 4.4.23 to set up the symlinks to the older version. Now a brew upgrade shouldn't affect your version of Bash. You can brew switch bash to get a list of the versions available to switch to.


Alternative using a custom local-only tap

Another way of achieving the same goal appears to be:

brew tap-new username/repo-name
# extract with a version seems to run a grep under the hood
brew extract --version='4.4.23' bash username/repo-name
brew install [email protected]
# Note this "fails" when trying to grab a bottle for the package and seems to have
# some odd doubling of the version in that output, but this isn't fatal.

This creates a formula@version in your custom tap that you can install per the above example. The downside is that you probably still need to brew unlink bash and then brew link [email protected] in order to use your specific version of Bash or any other formula.

HTML5 Number Input - Always show 2 decimal places

If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:

Javascript:

function limitDecimalPlaces(e, count) {
  if (e.target.value.indexOf('.') == -1) { return; }
  if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
    e.target.value = parseFloat(e.target.value).toFixed(count);
  }
}

HTML:

<input type="number" oninput="limitDecimalPlaces(event, 2)" />

Note that this cannot AFAIK, defend against this chrome bug with the number input.

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

not-null property references a null or transient value

This could be as simple as:

@Column(name = "Some_Column", nullable = false)

but while persisting, the value of "Some_Column"is null, even if "Some_Column" may not be any primary or foreign key.

Best way to test if a row exists in a MySQL table

At times it is quite handy to get the auto increment primary key (id) of the row if it exists and 0 if it doesn't.

Here's how this can be done in a single query:

SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...

Push items into mongo array via mongoose

I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.

---- Person model

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

***Important: SingleFriend.schema -> make sure to use lowercase for schema

--- Child schema

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

Jquery Hide table rows

This should do the trick.

$(textInput).closest("tr").hide();

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

How to set URL query params in Vue with Vue-Router

Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.

const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });

How to modify values of JsonObject / JsonArray directly?

This works for modifying childkey value using JSONObject. import used is

import org.json.JSONObject;

ex json:(convert json file to string while giving as input)

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "test"
    },
}

Code

JSONObject jObject  = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);

output:

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "data1"
    },
}

HTML+CSS: How to force div contents to stay in one line?

Everybody jumped on this one!!! I too made a fiddle:

http://jsfiddle.net/audetwebdesign/kh4aR/

RobAgar gets a point for pointing out white-space:nowrap first.

Couple of things here, you need overflow: hidden if you don't want to see the extra characters poking out into your layout.

Also, as mentioned, you could use white-space: pre (see EnderMB) keeping in mind that pre will not collapse white space whereas white-space: nowrap will.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

Cannot edit in read-only editor VS Code

If you can't find where to find code runner as said in Ali NoumSali Traore's answer, here's what you got to do:

  1. Go to extensions (Ctrl + Shift + X)
  2. Find code runner and click on the settings icon on bottom right of the code runner
  3. Click configure extensions settings
  4. Find code_runner: Run in terminal
  5. Check "Whether to run code in terminal"

Could not resolve this reference. Could not locate the assembly

If anyone face this issue with some nuget packages, you can fix that by reinstalling the packages using the Package Manager Console:

Update-Package -reinstall 

jQuery checkbox checked state changed event

Is very simple, this is the way I use:

JQuery:

$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
    var checkbox = $(this), // Selected or current checkbox
        value = checkbox.val(); // Value of checkbox

    if (checkbox.is(':checked'))
    {
        console.log('checked');
    }else
    {
        console.log('not checked');
    }
});

Regards!

Sort hash by key, return hash in Ruby

ActiveSupport::OrderedHash is another option if you don't want to use ruby 1.9.2 or roll your own workarounds.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Can a normal Class implement multiple interfaces?

Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.

Ceremonial example:

enter image description here

public interface Mammal {
    void move();
    boolean possessIntelligence();
}
public interface Animal extends Mammal {
    void liveInJungle();
}

public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
    void liveInCivilization();
}
public interface Carnivore {
    void eatMeat();
}
public interface Herbivore {
    void eatPlant();
}
public interface Omnivore extends Carnivore, Herbivore {
    void eatBothMeatAndPlant();
}
public interface FourLeggedMammal {
    void moveWithFourLegs();
}
public interface TwoLeggedMammal {
    void moveWithTwoLegs();
}
public interface Hunter {
    void huntForFood();
}
public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
    @Override
    public void liveInJungle() {
        System.out.println("I live in Outback country");
    }

    @Override
    public void move() {
        moveWithTwoLegs();
    }

    @Override
    public void moveWithTwoLegs() {
        System.out.println("I like to jump");
    }

    @Override
    public void eat() {
        eatPlant();
    }

    @Override
    public void eatPlant() {
        System.out.println("I like this grass");
    }

    @Override
    public boolean possessIntelligence() {
        return false;
    }
}

public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
    @Override
    public void liveInJungle() {
        System.out.println("I am king of the jungle!");

    }

    @Override
    public void move() {
        moveWithFourLegs();
    }

    @Override
    public void moveWithFourLegs() {
        System.out.println("I like to run sometimes.");
    }

    @Override
    public void eat() {
        eatMeat();
    }

    @Override
    public void eatMeat() {
        System.out.println("I like deer meat");
    }

    @Override
    public boolean possessIntelligence() {
        return false;
    }

    @Override
    public void huntForFood() {
        System.out.println("My females hunt often");
    }
}
public class Teacher implements Human {
    @Override
    public void liveInCivilization() {
        System.out.println("I live in an apartment");
    }

    @Override
    public void moveWithTwoLegs() {
        System.out.println("I wear shoes and walk with two legs one in front of the other");
    }

    @Override
    public void move() {
        moveWithTwoLegs();
    }

    @Override
    public boolean possessIntelligence() {
        return true;
    }

    @Override
    public void huntForFood() {
        System.out.println("My ancestors used to but now I mostly rely on cattle");
    }

    @Override
    public void eat() {
        eatBothMeatAndPlant();
    }

    @Override
    public void eatBothMeatAndPlant() {
        eatPlant();
        eatMeat();
    }

    @Override
    public void eatMeat() {
        System.out.println("I like this bacon");
    }

    @Override
    public void eatPlant() {
        System.out.println("I like this broccoli");
    }
}

How do I change the default location for Git Bash on Windows?

Git bash is used to play with bash commands. So I use bash method itself in windows Git bash

Edit your .bash_profile (create it if you doesnot have one - see below how to create). Enter the following lines.

Add these lines to the file

alias ws="cd /d/workspace/"
ws

My .bash_profile looks like this

Smilyface@SmilingMachine /d/workspace
$ cat ~/.bash_profile
alias ws="cd /d/workspace/"
ws

How to create a new .bash_profile ?

touch ~/.bash_profile

OR write into the file directly

vi ~/.bash_profile 

Simple, aha !

ld.exe: cannot open output file ... : Permission denied

If you think the executable is locked by a process, try Process Explorer from SysInternals. In the File/handle, enter Fibonacci.exe and you should see who holds the file.

If it is not enough, you can use Process Monitor (from SysInternals, again) to follow the activity of all processes on your system on Fibonacci.exe. With a little bit of analysis (call stacks), you'll may find out why the access to the file is denied and what make it disappear.

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

How to list the tables in a SQLite database file that was opened with ATTACH?

There are a few steps to see the tables in an SQLite database:

  1. List the tables in your database:

    .tables
    
  2. List how the table looks:

    .schema tablename
    
  3. Print the entire table:

    SELECT * FROM tablename;
    
  4. List all of the available SQLite prompt commands:

    .help
    

Show DataFrame as table in iPython Notebook

To display dataframes contained in a list:

display(*dfs)

Android change SDK version in Eclipse? Unable to resolve target android-x

go to project properties and change the target from 7 to 8 also change the target in android manifest and also go to properties of project by right clicking on the project and choose the target

selected value get from db into dropdown select box option using php mysql error

The easiest way I can think of is the following:

<?php

$selection = array('PHP', 'ASP');
echo '<select>
      <option value="0">Please Select Option</option>';

foreach ($selection as $selection) {
    $selected = ($options == $selection) ? "selected" : "";
    echo '<option '.$selected.' value="'.$selection.'">'.$selection.'</option>';
}

echo '</select>';

The code basically places all of your options in an array which are called upon in the foreach loop. The loop checks to see if your $options variable matches the current selection it's on, if it's a match then $selected will = selected, if not then it is set as blank. Finally the option tag is returned containing the selection from the array and if that particular selection is equal to your $options variable, it's set as the selected option.

Check a collection size with JSTL

use ${fn:length(companies) > 0} to check the size. This returns a boolean

Getting "cannot find Symbol" in Java project in Intellij

In my case, I had a problem with finding a class from another module. In pom.xml, I just had this dependency with <scope>compile</scope> specified. Removing this line helped.

How to open existing project in Eclipse

Assume that the application folder is in your pen drive.

open eclipse, go to import,select Android,In Android select "existing android code into workspace"

next and finish.

Ramanand Bhat

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

C#: Limit the length of a string?

foo = foo.Substring(0,5);

Transpose a data frame

You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!

Here's a solution that keeps numbers as numbers:

# first remember the names
n <- df.aree$name

# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))

str(df.aree) # Check the column types

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

How to uninstall mini conda? python

If you are using windows, just search for miniconda and you'll find the folder. Go into the folder and you'll find a miniconda uninstall exe file. Run it.

How to set null to a GUID property

Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.

No. Because it's non-nullable. If you want it to be nullable, you have to use Nullable<Guid> - if you didn't, there'd be no point in having Nullable<T> to start with. You've got a fundamental issue here - which you actually know, given your first paragraph. You've said, "I know if I want to achieve A, I must do B - but I want to achieve A without doing B." That's impossible by definition.

The closest you can get is to use one specific GUID to stand in for a null value - Guid.Empty (also available as default(Guid) where appropriate, e.g. for the default value of an optional parameter) being the obvious candidate, but one you've rejected for unspecified reasons.

Use of "global" keyword in Python

This is the difference between accessing the name and binding it within a scope.

If you're just looking up a variable to read its value, you've got access to global as well as local scope.

However if you assign to a variable who's name isn't in local scope, you are binding that name into this scope (and if that name also exists as a global, you'll hide that).

If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.

Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).

>>> a = 1
>>> def p():
    print(a) # accessing global scope, no binding going on
>>> def q():
    a = 3 # binding a name in local scope - hiding global
    print(a)
>>> def r():
    print(a) # fail - a is bound to local scope, but not assigned yet
    a = 4
>>> p()
1
>>> q()
3
>>> r()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r()
  File "<pyshell#32>", line 2, in r
    print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>> 

Why calling react setState method doesn't mutate the state immediately?

Watch out the react lifecycle methods!

I worked for several hours to find out that getDerivedStateFromProps will be called after every setState().

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

How to write to a file in Scala?

Edit 2019 (8 years later), Scala-IO being not very active, if any, Li Haoyi suggests his own library lihaoyi/os-lib, that he presents below.

June 2019, Xavier Guihot mentions in his answer the library Using, a utility for performing automatic resource management.


Edit (September 2011): since Eduardo Costa asks about Scala2.9, and since Rick-777 comments that scalax.IO commit history is pretty much non-existent since mid-2009...

Scala-IO has changed place: see its GitHub repo, from Jesse Eichar (also on SO):

The Scala IO umbrella project consists of a few sub projects for different aspects and extensions of IO.
There are two main components of Scala IO:

  • Core - Core primarily deals with Reading and writing data to and from arbitrary sources and sinks. The corner stone traits are Input, Output and Seekable which provide the core API.
    Other classes of importance are Resource, ReadChars and WriteChars.
  • File - File is a File (called Path) API that is based on a combination of Java 7 NIO filesystem and SBT PathFinder APIs.
    Path and FileSystem are the main entry points into the Scala IO File API.
import scalax.io._

val output:Output = Resource.fromFile("someFile")

// Note: each write will open a new connection to file and 
//       each write is executed at the begining of the file,
//       so in this case the last write will be the contents of the file.
// See Seekable for append and patching files
// Also See openOutput for performing several writes with a single connection

output.writeIntsAsBytes(1,2,3)
output.write("hello")(Codec.UTF8)
output.writeStrings(List("hello","world")," ")(Codec.UTF8)

Original answer (January 2011), with the old place for scala-io:

If you don't want to wait for Scala2.9, you can use the scala-incubator / scala-io library.
(as mentioned in "Why doesn't Scala Source close the underlying InputStream?")

See the samples

{ // several examples of writing data
    import scalax.io.{
      FileOps, Path, Codec, OpenOption}
    // the codec must be defined either as a parameter of ops methods or as an implicit
    implicit val codec = scalax.io.Codec.UTF8


    val file: FileOps = Path ("file")

    // write bytes
    // By default the file write will replace
    // an existing file with the new data
    file.write (Array (1,2,3) map ( _.toByte))

    // another option for write is openOptions which allows the caller
    // to specify in detail how the write should take place
    // the openOptions parameter takes a collections of OpenOptions objects
    // which are filesystem specific in general but the standard options
    // are defined in the OpenOption object
    // in addition to the definition common collections are also defined
    // WriteAppend for example is a List(Create, Append, Write)
    file.write (List (1,2,3) map (_.toByte))

    // write a string to the file
    file.write("Hello my dear file")

    // with all options (these are the default options explicitely declared)
    file.write("Hello my dear file")(codec = Codec.UTF8)

    // Convert several strings to the file
    // same options apply as for write
    file.writeStrings( "It costs" :: "one" :: "dollar" :: Nil)

    // Now all options
    file.writeStrings("It costs" :: "one" :: "dollar" :: Nil,
                    separator="||\n||")(codec = Codec.UTF8)
  }

C# send a simple SSH command

For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170

Java Reflection: How to get the name of a variable?

As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.


Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

How to get a responsive button in bootstrap 3

<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>

We can use btn-block for automatic responsive.

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

Difference between .on('click') vs .click()

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

JSON to TypeScript class instance?

You can now use Object.assign(target, ...sources). Following your example, you could use it like this:

class Foo {
  name: string;
  getName(): string { return this.name };
}

let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));

console.log(foo.getName()); //returns John Doe

Object.assign is part of ECMAScript 2015 and is currently available in most modern browsers.

Error in plot.new() : figure margins too large in R

I found the same error today. I have tried the "Clear all Plots" button, but it was giving me the same error. Then this trick worked for me, Try to increase the plot area by dragging. It will help you for sure.

Java Regex Capturing Groups

From the doc :

Capturing groups</a> are indexed from left
 * to right, starting at one.  Group zero denotes the entire pattern, so
 * the expression m.group(0) is equivalent to m.group().

So capture group 0 send the whole line.

How to set a default value for an existing column

The correct way to do this is as follows:

  1. Run the command:

    sp_help [table name] 
    
  2. Copy the name of the CONSTRAINT.

  3. Drop the DEFAULT CONSTRAINT:

    ALTER TABLE [table name] DROP [NAME OF CONSTRAINT] 
    
  4. Run the command below:

    ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
    

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

Just to add to the other answers, the documentation gives this explanation:

  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

  • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

  • A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

Getting full-size profile picture

With Javascript you can get full size profile images like this

pass your accessToken to the getface() function from your FB.init call

function getface(accessToken){
  FB.api('/me/friends', function (response) {
    for (id in response.data) { 
        var homie=response.data[id].id         
        FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
          for (album in aresponse.data) {
            if (aresponse.data[album].name == "Profile Pictures") {                      
              FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
                console.log(aresponse.data[0].images[0].source); 
              });                  
            }
          }   
        });
    }
  });
}

How can I set the initial value of Select2 when using AJAX?

after spending a few hours searching for a solution, I decided to create my own. He it is:

 function CustomInitSelect2(element, options) {
            if (options.url) {
                $.ajax({
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                    element.select2({
                        data: data
                    });
                    if (options.initialValue) {
                        element.val(options.initialValue).trigger('change');
                    }
                });
            }
        }

And you can initialize the selects using this function:

$('.select2').each(function (index, element) {
            var item = $(element);
            if (item.data('url')) {
                CustomInitSelect2(item, {
                    url: item.data('url'),
                    initialValue: item.data('value')
                });
            }
            else {
                item.select2();
            }
        });

And of course, here is the html:

<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>

Node.js - Find home directory in platform agnostic way

os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());

Can I add a custom attribute to an HTML tag?

You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED means it is an optional attribute, or you could use #REQUIRED, etc.

More information is in DTD - Attributes.

Why shouldn't I use mysql_* functions in PHP?

It's possible to define almost all mysql_* functions using mysqli or PDO. Just include them on top of your old PHP application, and it will work on PHP7. My solution here.

<?php

define('MYSQL_LINK', 'dbl');
$GLOBALS[MYSQL_LINK] = null;

function mysql_link($link=null) {
    return ($link === null) ? $GLOBALS[MYSQL_LINK] : $link;
}

function mysql_connect($host, $user, $pass) {
    $GLOBALS[MYSQL_LINK] = mysqli_connect($host, $user, $pass);
    return $GLOBALS[MYSQL_LINK];
}

function mysql_pconnect($host, $user, $pass) {
    return mysql_connect($host, $user, $pass);
}

function mysql_select_db($db, $link=null) {
    $link = mysql_link($link);
    return mysqli_select_db($link, $db);
}

function mysql_close($link=null) {
    $link = mysql_link($link);
    return mysqli_close($link);
}

function mysql_error($link=null) {
    $link = mysql_link($link);
    return mysqli_error($link);
}

function mysql_errno($link=null) {
    $link = mysql_link($link);
    return mysqli_errno($link);
}

function mysql_ping($link=null) {
    $link = mysql_link($link);
    return mysqli_ping($link);
}

function mysql_stat($link=null) {
    $link = mysql_link($link);
    return mysqli_stat($link);
}

function mysql_affected_rows($link=null) {
    $link = mysql_link($link);
    return mysqli_affected_rows($link);
}

function mysql_client_encoding($link=null) {
    $link = mysql_link($link);
    return mysqli_character_set_name($link);
}

function mysql_thread_id($link=null) {
    $link = mysql_link($link);
    return mysqli_thread_id($link);
}

function mysql_escape_string($string) {
    return mysql_real_escape_string($string);
}

function mysql_real_escape_string($string, $link=null) {
    $link = mysql_link($link);
    return mysqli_real_escape_string($link, $string);
}

function mysql_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql);
}

function mysql_unbuffered_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql, MYSQLI_USE_RESULT);
}

function mysql_set_charset($charset, $link=null){
    $link = mysql_link($link);
    return mysqli_set_charset($link, $charset);
}

function mysql_get_host_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_host_info($link);
}

function mysql_get_proto_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_proto_info($link);
}
function mysql_get_server_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_server_info($link);
}

function mysql_info($link=null) {
    $link = mysql_link($link);
    return mysqli_info($link);
}

function mysql_get_client_info() {
    $link = mysql_link();
    return mysqli_get_client_info($link);
}

function mysql_create_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "CREATE DATABASE `$db`");
}

function mysql_drop_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "DROP DATABASE `$db`");
}

function mysql_list_dbs($link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, "SHOW DATABASES");
}

function mysql_list_fields($db, $table, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    $table = str_replace('`', '', mysqli_real_escape_string($link, $table));
    return mysqli_query($link, "SHOW COLUMNS FROM `$db`.`$table`");
}

function mysql_list_tables($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "SHOW TABLES FROM `$db`");
}

function mysql_db_query($db, $sql, $link=null) {
    $link = mysql_link($link);
    mysqli_select_db($link, $db);
    return mysqli_query($link, $sql);
}

function mysql_fetch_row($qlink) {
    return mysqli_fetch_row($qlink);
}

function mysql_fetch_assoc($qlink) {
    return mysqli_fetch_assoc($qlink);
}

function mysql_fetch_array($qlink, $result=MYSQLI_BOTH) {
    return mysqli_fetch_array($qlink, $result);
}

function mysql_fetch_lengths($qlink) {
    return mysqli_fetch_lengths($qlink);
}

function mysql_insert_id($qlink) {
    return mysqli_insert_id($qlink);
}

function mysql_num_rows($qlink) {
    return mysqli_num_rows($qlink);
}

function mysql_num_fields($qlink) {
    return mysqli_num_fields($qlink);
}

function mysql_data_seek($qlink, $row) {
    return mysqli_data_seek($qlink, $row);
}

function mysql_field_seek($qlink, $offset) {
    return mysqli_field_seek($qlink, $offset);
}

function mysql_fetch_object($qlink, $class="stdClass", array $params=null) {
    return ($params === null)
        ? mysqli_fetch_object($qlink, $class)
        : mysqli_fetch_object($qlink, $class, $params);
}

function mysql_db_name($qlink, $row, $field='Database') {
    mysqli_data_seek($qlink, $row);
    $db = mysqli_fetch_assoc($qlink);
    return $db[$field];
}

function mysql_fetch_field($qlink, $offset=null) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    return mysqli_fetch_field($qlink);
}

function mysql_result($qlink, $offset, $field=0) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    $row = mysqli_fetch_array($qlink);
    return (!is_array($row) || !isset($row[$field]))
        ? false
        : $row[$field];
}

function mysql_field_len($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->length : false;
}

function mysql_field_name($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgname) ? $field->name : $field->orgname;
}

function mysql_field_table($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgtable) ? $field->table : $field->orgtable;
}

function mysql_field_type($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->type : false;
}

function mysql_free_result($qlink) {
    try {
        mysqli_free_result($qlink);
    } catch (Exception $e) {
        return false;
    }
    return true;
}

If else in stored procedure sql server

If there are no matching row/s then @ParLngId will be NULL not zero, so you need IF @ParLngId IS NULL.

You should also use SCOPE_IDENTITY() rather than @@IDENTITY.

MySQL table is marked as crashed and last (automatic?) repair failed

I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".

  • Server type: MySQL
  • Server version: 5.7.23 - MySQL Community Server (GPL)
  • phpMyAdmin: Version information: 4.7.7

Setting the default active profile in Spring-boot

If you are using AWS Lambda with SprintBoot, then you must declare the following under environment variables:

key: JAVA_TOOL_OPTIONS & value: -Dspring.profiles.active=dev

os.walk without digging into directories below

A slight change to Alex's answer, but using __next__():

print(next(os.walk('d:/'))[2]) or print(os.walk('d:/').__next__()[2])

with the [2] being the file in root, dirs, file mentioned in other answers

Evenly space multiple views within a container view

Very quick Interface Builder solution:

For any number of views to be evenly spaced within a superview, simply give each an "Align Center X to superview" constraint for horizontal layout, or "Align Center Y superview" for vertical layout, and set the Multiplier to be N:p (NOTE: some have had better luck with p:N - see below)

where

N = total number of views, and

p = position of the view including spaces

First position is 1, then a space, making the next position 3, so p becomes a series [1,3,5,7,9,...]. Works for any number of views.

So, if you have 3 views to space out, it looks like this:

Illustration of how to evenly spread views in IB

EDIT Note: The choice of N:p or p:N depends on the relation order of your alignment constraint. If "First Item" is Superview.Center, you may use p:N, while if Superview.Center is "Second Item", you may use N:p. If in doubt, just try both out... :-)

Getting the inputstream from a classpath resource (XML file)

someClassWithinYourSourceDir.getClass().getResourceAsStream();

How do I measure request and response times at once using cURL?

The following is inspired by Simon's answer. It's self-contained (doesn't require a separate format file), which makes it great for inclusion into .bashrc.

curl_time() {
    curl -so /dev/null -w "\
   namelookup:  %{time_namelookup}s\n\
      connect:  %{time_connect}s\n\
   appconnect:  %{time_appconnect}s\n\
  pretransfer:  %{time_pretransfer}s\n\
     redirect:  %{time_redirect}s\n\
starttransfer:  %{time_starttransfer}s\n\
-------------------------\n\
        total:  %{time_total}s\n" "$@"
}

Futhermore, it should work with all arguments that curl normally takes, since the "$@" just passes them through. For example, you can do:

curl_time -X POST -H "Content-Type: application/json" -d '{"key": "val"}' https://postman-echo.com/post

Output:

   namelookup:  0,125000s
      connect:  0,250000s
   appconnect:  0,609000s
  pretransfer:  0,609000s
     redirect:  0,000000s
starttransfer:  0,719000s
-------------------------
        total:  0,719000s

How to allow user to pick the image with Swift?

here is an easy way to do it:

but first you have to add ( Privacy - Photo Library Usage Description ) in the info.plist, and you should have a button and a UIImageView in your viewController.

then create an outlet of the UIImageView ( in this code the outlet is called myImage), and an action of the button ( I called the action importing in my code )

import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBOutlet weak var myImage: UIImageView!
    @IBAction func importing(_ sender: Any) {
        let Picker = UIImagePickerController()
        Picker.delegate = self
        Picker.sourceType = .photoLibrary
        self.present(Picker, animated: true, completion: nil)
        Picker.allowsEditing = true
        Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
    }

     func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
    {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
        myImage.contentMode = .scaleAspectFit //2
        myImage.image = chosenImage //3
        dismiss(animated:true, completion: nil) //4
    }

}

Android Gradle Apache HttpClient does not exist?

Add this library into build.gradle

 android {
      useLibrary 'org.apache.http.legacy'
 }

Detecting Enter keypress on VB.NET

I see this has been answered, but it seems like you could avoid all of this 'remapping' of the enter key by simply hooking your validation into the AcceptButton on a form. ie. you have 3 textboxes (txtA,txtB,txtC) and an 'OK' button set to be AcceptButton (and TabOrder set properly). So, if in txtA and you hit enter, if the data is invalid, your focus will stay in txtA, but if it is valid, assuming the other txts need input, validation will just put you into the next txt that needs valid input thus simulating TAB behaviour... once all txts have valid input, pressing enter will fire a succsessful validation and close form (or whatever...) Make sense?

unable to start mongodb local server

OS X. Activity Monitor, look for mongod, cross it . then run again mongod. problem Solved.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

After encountering the same issue in a Web API 2 project (and being unable to use the standard CORS packages for reasons not worth going into here), I was able to resolve this by implementing a custom DelagatingHandler:

public class AllowOptionsHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (request.Method == HttpMethod.Options &&
            response.StatusCode == HttpStatusCode.MethodNotAllowed)
        {
            response = new HttpResponseMessage(HttpStatusCode.OK);
        }

        return response;
    }
}

For the Web API configuration:

config.MessageHandlers.Add(new AllowOptionsHandler());

Note that I also have the CORS headers enabled in Web.config, similar to some of the other answers posted here:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule" />
  </modules>

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

Note that my project does not include MVC, only Web API 2.

How to create a timeline with LaTeX?

Also the package chronosys provides a nice solution. Here's an example from the user manual:

enter image description here

What does --net=host option in Docker command really do?

The --net=host option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.

Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.

While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.

For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host.

Generally speaking, --net=host is only needed when you are running programs with very specific, unusual network needs.

Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

AngularJS - difference between pristine/dirty and touched/untouched

In Pro Angular-6 book is detailed as below;

  • valid: This property returns true if the element’s contents are valid and false otherwise.
  • invalid: This property returns true if the element’s contents are invalid and false otherwise.

  • pristine: This property returns true if the element’s contents have not been changed.

  • dirty: This property returns true if the element’s contents have been changed.
  • untouched: This property returns true if the user has not visited the element.
  • touched: This property returns true if the user has visited the element.

Can you change a path without reloading the controller in AngularJS?

Answers above, including the GitHub one, had some issues for my scenario and also back button or direct url change from browser was reloading the controller, which I did not like. I finally went with the following approach:

1. Define a property in route definitions, called 'noReload' for those routes where you don't want the controller to reload on route change.

.when('/:param1/:param2?/:param3?', {
    templateUrl: 'home.html',
    controller: 'HomeController',
    controllerAs: 'vm',
    noReload: true
})

2. In the run function of your module, put the logic that checks for those routes. It will prevent reload only if noReload is true and previous route controller is the same.

fooRun.$inject = ['$rootScope', '$route', '$routeParams'];

function fooRun($rootScope, $route, $routeParams) {
    $rootScope.$on('$routeChangeStart', function (event, nextRoute, lastRoute) {
        if (lastRoute && nextRoute.noReload 
         && lastRoute.controller === nextRoute.controller) {
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                un();
                // Broadcast routeUpdate if params changed. Also update
                // $routeParams accordingly
                if (!angular.equals($route.current.params, lastRoute.params)) {
                    lastRoute.params = nextRoute.params;
                    angular.copy(lastRoute.params, $routeParams);
                    $rootScope.$broadcast('$routeUpdate', lastRoute);
                }
                // Prevent reload of controller by setting current
                // route to the previous one.
                $route.current = lastRoute;
            });
        }
    });
}

3. Finally, in the controller, listen to $routeUpdate event so you can do whatever you need to do when route parameters change.

HomeController.$inject = ['$scope', '$routeParams'];

function HomeController($scope, $routeParams) {
    //(...)

    $scope.$on("$routeUpdate", function handler(route) {
        // Do whatever you need to do with new $routeParams
        // You can also access the route from the parameter passed
        // to the event
    });

    //(...)
}

Keep in mind that with this approach, you don't change things in the controller and then update the path accordingly. It's the other way around. You first change the path, then listen to $routeUpdate event to change things in the controller when route parameters change.

This keeps things simple and consistent as you can use the same logic both when you simply change path (but without expensive $http requests if you like) and when you completely reload the browser.

JFrame Maximize window

The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ, which respectively set the frame to maximize vertically and horizontally

package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;

public class JFrameExample
{
    static JFrame frame;
    static GraphicsConfiguration gc;
    public static void main(String[] args)
    {
        frame = new JFrame(gc);
        frame.setTitle("Full Screen Example");
        frame.setExtendedState(MAXIMIZED_BOTH);

        JButton button = new JButton("exit");
        b.addActionListener(new ActionListener(){@Override
        public void actionPerformed(ActionEvent arg0){
            JFrameExample.frame.dispose();
            System.exit(0);
        }});

        frame.add(button);
        frame.setVisible(true);
    }
}

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

How can I get this ASP.NET MVC SelectList to work?

I use an extension method:

usage

var departmentItems = departments.ToSelectList(d => d.Code + 
                                               " - " + d.Description,
                                               d => d.Id.ToString(),
                                               " - ");

var functionItems = customerFunctions.ToSelectList(f => f.Description, 
                                                   f => f.Id.ToString(), 
                                                   " - ");

with

public static class MCVExtentions
{
    public static List<SelectListItem> ToSelectList<T>(
        this IEnumerable<T> enumerable, 
        Func<T, string> text, 
        Func<T, string> value, 
        string defaultOption)
    {
        var items = enumerable.Select(f => new SelectListItem()
                                     {
                                         Text = text(f), 
                                         Value = value(f) 
                                     }).ToList();
        items.Insert(0, new SelectListItem()
                    {
                        Text = defaultOption, 
                        Value = "-1" 
                    });
        return items;
    }
}

Open file dialog box in JavaScript

Simple answer .

(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"

(2) Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this- onclick="document.getElementById('myid').click()"

That is all.

C# Remove object from list of objects

You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.

for (int i = ChunkList.Count-1; i >=0; i--)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.RemoveAt(i);
    }
}

Simplest way to have a configuration file in a Windows Forms C# application

The best (IMHO) article about .NET Application configuration is on CodeProject, Unraveling the Mysteries of .NET 2.0 Configuration. And my next favorite (shorter) article about sections in the .NET configuration files is Understanding Section Handlers - App.config File.

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

Set height of <div> = to height of another <div> through .css

You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:

Please check the example: http://jsfiddle.net/xLA4q/

HTML:

<div class="nav-content-wrapper">
 <div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
 <div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>

CSS:

.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}

Delete forked repo from GitHub

I had also faced this issue. NO it will not affect your original repo by anyway. just simply delete it by entering the name of forked repo

Find size of object instance in bytes in c#

First of all, a warning: what follows is strictly in the realm of ugly, undocumented hacks. Do not rely on this working - even if it works for you now, it may stop working tomorrow, with any minor or major .NET update.

You can use the information in this article on CLR internals MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects - last I checked, it was still applicable. Here's how this is done (it retrieves the internal "Basic Instance Size" field via TypeHandle of the type).

object obj = new List<int>(); // whatever you want to get the size of
RuntimeTypeHandle th = obj.GetType().TypeHandle;
int size = *(*(int**)&th + 1);
Console.WriteLine(size);

This works on 3.5 SP1 32-bit. I'm not sure if field sizes are the same on 64-bit - you might have to adjust the types and/or offsets if they are not.

This will work for all "normal" types, for which all instances have the same, well-defined types. Those for which this isn't true are arrays and strings for sure, and I believe also StringBuilder. For them you'll have add the size of all contained elements to their base instance size.

How to display both icon and title of action inside ActionBar?

You can add button in toolbar

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="title">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="16dp"
            android:background="@color/transparent"
            android:drawableRight="@drawable/ic_your_icon"
            android:drawableTint="@drawable/btn_selector"
            android:text="@string/sort_by_credit"
            android:textColor="@drawable/btn_selector"
            />

    </android.support.v7.widget.Toolbar>

create file btn_selector.xml in drawable

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:state_selected="true"
    android:color="@color/white"
    />
<item
    android:color="@color/white_30_opacity"
    />

java:

private boolean isSelect = false;

OnClickListener for button:

private void myClick() {
    if (!isSelect) {
       //**your code**//
        isSelect = true;
    } else {//**your code**//
        isSelect = false;
    }
    sort.setSelected(isSelect);
}

What is causing "Unable to allocate memory for pool" in PHP?

I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.

The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:

usermod -a -G vhost-user-group apache-user

Then I had to restart apache for the change to take effect:

apachectl restart

Or

sudo /etc/init.d/httpd restart

Or whatever your system uses to restart apache.

If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?

How do I get the current date in Cocoa

Original poster - the way you're determining seconds until midnight won't work on a day when daylight savings starts or ends. Here's a chunk of code which shows how to do it... It'll be in number of seconds (an NSTimeInterval); you can do the division/modulus/etc to get down to whatever you need.

NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:[NSDate date]];
[dc setDay:dc.day + 1];
NSDate *midnightDate = [[NSCalendar currentCalendar] dateFromComponents:dc];
NSLog(@"Now: %@, Tonight Midnight: %@, Hours until midnight: %.1f", [NSDate date], midnightDate, [midnightDate timeIntervalSinceDate:[NSDate date]] / 60.0 / 60.0);

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

How can I check if given int exists in array?

You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.

also see this answer: C++ check if element exists in array

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

All you need to do is uncomment the two lines in /etc/apt/sources.list that refer to "partner"

sudo nano /etc/apt/sources.list
# uncomment the two lines referring to "partner"
sudo apt-get update 
sudo apt-get install sun-java6-jre sun-java6-bin sun-java6-jdk

(I can't find the command add-apt-repository on Ubuntu 10.10, 64 amd ... even searching with apt-cache yields nothing)

How to include a PHP variable inside a MySQL statement

That's the easy answer:

$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";

and you define $name whatever you want.
And another way, the complex way, is like that:

$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
         " FROM CountryInfo " .
         " INNER JOIN District " .
         " ON District.CountryInfoId = CountryInfo.CountryInfoId " .
         " INNER JOIN City " .
         " ON City.DistrictId = District.DistrictId " .
         " INNER JOIN '" . $GLOBALS['Name'] . "' " .
         " ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
         " WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
         "'";

Change navbar color in Twitter Bootstrap

It took me a while, but I discovered that including the following was what made it possible to change the navbar color:

.navbar{ 
    background-image: none;
}

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Pandas KeyError: value not in index

I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:

[['Gender']]

If it's easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())

Histogram with Logarithmic Scale and custom breaks

I've put together a function that behaves identically to hist in the default case, but accepts the log argument. It uses several tricks from other posters, but adds a few of its own. hist(x) and myhist(x) look identical.

The original problem would be solved with:

myhist(mydata$V3, breaks=c(0,1,2,3,4,5,25), log="xy")

The function:

myhist <- function(x, ..., breaks="Sturges",
                   main = paste("Histogram of", xname),
                   xlab = xname,
                   ylab = "Frequency") {
  xname = paste(deparse(substitute(x), 500), collapse="\n")
  h = hist(x, breaks=breaks, plot=FALSE)
  plot(h$breaks, c(NA,h$counts), type='S', main=main,
       xlab=xlab, ylab=ylab, axes=FALSE, ...)
  axis(1)
  axis(2)
  lines(h$breaks, c(h$counts,NA), type='s')
  lines(h$breaks, c(NA,h$counts), type='h')
  lines(h$breaks, c(h$counts,NA), type='h')
  lines(h$breaks, rep(0,length(h$breaks)), type='S')
  invisible(h)
}

Exercise for the reader: Unfortunately, not everything that works with hist works with myhist as it stands. That should be fixable with a bit more effort, though.

Git will not init/sync/update new submodules

  • Remove the submodule from your .git/config
  • Run git submodule init command
  • Go to your submodule directory and run git pull origin master

It should works now

eslint: error Parsing error: The keyword 'const' is reserved

I had this same problem with this part of my code:

const newComment = {
    dishId: dishId,
    rating: rating,
    author: author,
    comment: comment
};
newComment.date = new Date().toISOString();

Same error, const is a reserved word.

The thing is, I made the .eslintrc.js from the link you gave in the update and still got the same error. Also, I get an parsing error in the .eslintrc.js: Unexpected token ':'.

Right in this part:

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

...

curl error 18 - transfer closed with outstanding read data remaining

I've solved this error by this way.

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;

Error still occurs, but I can handle response data in variable.

What is (functional) reactive programming?

If you want to get a feel for FRP, you could start with the old Fran tutorial from 1998, which has animated illustrations. For papers, start with Functional Reactive Animation and then follow up on links on the publications link on my home page and the FRP link on the Haskell wiki.

Personally, I like to think about what FRP means before addressing how it might be implemented. (Code without a specification is an answer without a question and thus "not even wrong".) So I don't describe FRP in representation/implementation terms as Thomas K does in another answer (graphs, nodes, edges, firing, execution, etc). There are many possible implementation styles, but no implementation says what FRP is.

I do resonate with Laurence G's simple description that FRP is about "datatypes that represent a value 'over time' ". Conventional imperative programming captures these dynamic values only indirectly, through state and mutations. The complete history (past, present, future) has no first class representation. Moreover, only discretely evolving values can be (indirectly) captured, since the imperative paradigm is temporally discrete. In contrast, FRP captures these evolving values directly and has no difficulty with continuously evolving values.

FRP is also unusual in that it is concurrent without running afoul of the theoretical & pragmatic rats' nest that plagues imperative concurrency. Semantically, FRP's concurrency is fine-grained, determinate, and continuous. (I'm talking about meaning, not implementation. An implementation may or may not involve concurrency or parallelism.) Semantic determinacy is very important for reasoning, both rigorous and informal. While concurrency adds enormous complexity to imperative programming (due to nondeterministic interleaving), it is effortless in FRP.

So, what is FRP? You could have invented it yourself. Start with these ideas:

  • Dynamic/evolving values (i.e., values "over time") are first class values in themselves. You can define them and combine them, pass them into & out of functions. I called these things "behaviors".

  • Behaviors are built up out of a few primitives, like constant (static) behaviors and time (like a clock), and then with sequential and parallel combination. n behaviors are combined by applying an n-ary function (on static values), "point-wise", i.e., continuously over time.

  • To account for discrete phenomena, have another type (family) of "events", each of which has a stream (finite or infinite) of occurrences. Each occurrence has an associated time and value.

  • To come up with the compositional vocabulary out of which all behaviors and events can be built, play with some examples. Keep deconstructing into pieces that are more general/simple.

  • So that you know you're on solid ground, give the whole model a compositional foundation, using the technique of denotational semantics, which just means that (a) each type has a corresponding simple & precise mathematical type of "meanings", and (b) each primitive and operator has a simple & precise meaning as a function of the meanings of the constituents. Never, ever mix implementation considerations into your exploration process. If this description is gibberish to you, consult (a) Denotational design with type class morphisms, (b) Push-pull functional reactive programming (ignoring the implementation bits), and (c) the Denotational Semantics Haskell wikibooks page. Beware that denotational semantics has two parts, from its two founders Christopher Strachey and Dana Scott: the easier & more useful Strachey part and the harder and less useful (for software design) Scott part.

If you stick with these principles, I expect you'll get something more-or-less in the spirit of FRP.

Where did I get these principles? In software design, I always ask the same question: "what does it mean?". Denotational semantics gave me a precise framework for this question, and one that fits my aesthetics (unlike operational or axiomatic semantics, both of which leave me unsatisfied). So I asked myself what is behavior? I soon realized that the temporally discrete nature of imperative computation is an accommodation to a particular style of machine, rather than a natural description of behavior itself. The simplest precise description of behavior I can think of is simply "function of (continuous) time", so that's my model. Delightfully, this model handles continuous, deterministic concurrency with ease and grace.

It's been quite a challenge to implement this model correctly and efficiently, but that's another story.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is the code of TextScanner

public class TextScanner {

        private static void readFile(String fileName) {
            try {
              File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
              Scanner scanner = new Scanner(file);
              while (scanner.hasNext()) {
                System.out.println(scanner.next());
              }
              scanner.close();
            } catch (FileNotFoundException e) {
              e.printStackTrace();
            }
          }

          public static void main(String[] args) {
            if (args.length != 1) {
              System.err.println("usage: java TextScanner1"
                + "file location");
              System.exit(0);
            }
            readFile(args[0]);
      }
}

It will print text with delimeters

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

Error: Failed to lookup view in Express

I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.

  1. I changed the filename from index.js to index.pug
  2. Then used in the '/' route: res.render('index.pug') - instead of res.render('index')
  3. Set environment variable: DEBUG=express:view Now it works like a charm.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

I too received the same error as quoted below:

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path.

I followed these steps to resolve the issue:

  1. Right Click on Project
  2. Select Properties
  3. Select Project Facets
  4. Select Apache Tomcat as Runtime server
  5. Click OK

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Utility of HTTP header "Content-Type: application/force-download" for mobile?

Content-Type: application/force-download means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".

Use the correct mime type for whatever media you are using (e.g. audio/mpeg for mp3).

Use the Content-Disposition: attachment; etc etc header if you want to encourage the client to download it instead of following the default behaviour.

Declare a const array

For the sake of completeness, now we also have ImmutableArrays at our disposal. This should be truly immutable:

public readonly static ImmutableArray<string> Tiles = ImmutableArray.Create(new[] { "German", "Spanish", "Corrects", "Wrongs" });

Requires System.Collections.Immutable NuGet reference

https://msdn.microsoft.com/en-us/library/mt452182(v=vs.111).aspx

How do I use StringUtils in Java?

The mostly used StringUtils class is the Apache Commons Lang StringUtils (org.apache.commons.lang3.StringUtils). To use this class you first have to download the Apache Commons Lang3 package then you have to add it to your project libraries.

You can go to this link to get more details: http://examples.javacodegeeks.com/core-java/apache/commons/lang3/stringutils/org-apache-commons-lang3-stringutils-example/

How to pipe list of files returned by find command to cat to view all the files

Modern version

POSIX 2008 added the + marker to find which means it now automatically groups as many files as are reasonable into a single command execution, very much like xargs does, but with a number of advantages:

  1. You don't have to worry about odd characters in the file names.
  2. You don't have to worry about the command being invoked with zero file names.

The file name issue is a problem with xargs without the -0 option, and the 'run even with zero file names' issue is a problem with or without the -0 option — but GNU xargs has the -r or --no-run-if-empty option to prevent that happening. Also, this notation cuts down on the number of processes, not that you're likely to measure the difference in performance. Hence, you could sensibly write:

find . -exec grep something {} +

Classic version

find . -print | xargs grep something

If you're on Linux or have the GNU find and xargs commands, then use -print0 with find and -0 with xargs to handle file names containing spaces and other odd-ball characters.

find . -print0 | xargs -0 grep something

Tweaking the results from grep

If you don't want the file names (just the text) then add an appropriate option to grep (usually -h to suppressing 'headings'). To absolutely guarantee the file name is printed by grep (even if only one file is found, or the last invocation of grep is only given 1 file name), then add /dev/null to the xargs command line, so that there will always be at least two file names.

How do you access the matched groups in a JavaScript regular expression?

/*Regex function for extracting object from "window.location.search" string.
 */

var search = "?a=3&b=4&c=7"; // Example search string

var getSearchObj = function (searchString) {

    var match, key, value, obj = {};
    var pattern = /(\w+)=(\w+)/g;
    var search = searchString.substr(1); // Remove '?'

    while (match = pattern.exec(search)) {
        obj[match[0].split('=')[0]] = match[0].split('=')[1];
    }

    return obj;

};

console.log(getSearchObj(search));

type checking in javascript

Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2

How to drop a unique constraint from table column?

To find all system generated unique constraint names and other information related to it on any database.

You may use below query and enhance it as per your need:

SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME LIKE '%UQ%'

Final query to drop all unique constraint through database. You may add where clause to restrict it to one table:

    DECLARE @uqQuery NVARCHAR(MAX)
    SET @uqQuery = SUBSTRING( (SELECT '; ' + 'ALTER TABLE [' + Table_Schema+'].['+Table_Name
        +']  DROP CONSTRAINT ['+CONSTRAINT_NAME+']'

    FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME LIKE '%UQ%'
    FOR XML PATH('')), 2,  2000000)
    SELECT @uqQuery

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

Share Text on Facebook from Android App via ACTION_SEND

Check this out : By this we can check activity results also....
// Open all sharing option for user
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    sharingIntent.setType("text/plain");                    
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ShortDesc+" from "+BusinessName);
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ShortDesc+" "+ShareURL);
                    sharingIntent.putExtra(Intent.EXTRA_TITLE, ShortDesc+" "+ShareURL);
                    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"),1000);
/**
     * Get the result when we share any data to another activity 
     * */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
        case 1000:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Activity 1 returned NOT OK", Toast.LENGTH_LONG).show();
            break;
        case 1002:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
            break;
        }// end switch



    }// end onActivityResult

How to get the id of the element clicked using jQuery

I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...

For example in order to change it's background to yellow:

$("#"+String(this.id)).css("background-color","yellow");

Create a directory if it doesn't exist

Use the WINAPI CreateDirectory() function to create a folder.

You can use this function without checking if the directory already exists as it will fail but GetLastError() will return ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

The code for constructing the target file is incorrect:

string(OutputFolder+CopiedFile).c_str()

this would produce "D:\testEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

string(OutputFolder+"\\"+CopiedFile).c_str()

Display all post meta keys and meta values of the same post ID in wordpress

Default Usage

Get the meta for all keys:

<?php $meta = get_post_meta($post_id); ?>

Get the meta for a single key:

<?php $key_1_values = get_post_meta( 76, 'key_1' ); ?>

for example:

$myvals = get_post_meta($post_id);

foreach($myvals as $key=>$val)
{
    echo $key . ' : ' . $val[0] . '<br/>';
}

Note: some unwanted meta keys starting with "underscore(_)" will also come, so you will need to filter them out.

For reference: See Codex

Operator overloading in Java

Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.

We can take +(plus) for example:

int a = 2 + 4;
string = "hello" + "world";

Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.

Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

.box {
    background: url( 'img/box-bg.png' ) no-repeat top left;
    width: 200px;
    height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
       only screen and (    min--moz-device-pixel-ratio: 1.3 ),
       only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
       only screen and (         min-device-pixel-ratio: 1.3 ),
       only screen and ( min-resolution: 124.8dpi ),
       only screen and ( min-resolution: 1.3dppx ) {

       .box {
           background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
       }

}

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

Can a table row expand and close?

To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.

Fitting a histogram with python

Here is another solution using only matplotlib.pyplot and numpy packages. It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic. Here is the corresponding code :

# Python version : 2.7.9
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt

# For the explanation, I simulate the data :
N=1000
data = np.random.randn(N)
# But in reality, you would read data from file, for example with :
#data = np.loadtxt("data.txt")

# Empirical average and variance are computed
avg = np.mean(data)
var = np.var(data)
# From that, we know the shape of the fitted Gaussian.
pdf_x = np.linspace(np.min(data),np.max(data),100)
pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)

# Then we plot :
plt.figure()
plt.hist(data,30,normed=True)
plt.plot(pdf_x,pdf_y,'k--')
plt.legend(("Fit","Data"),"best")
plt.show()

and here is the output.

Razor Views not seeing System.Web.Mvc.HtmlHelper

Just to expand on Matt DeKrey's answer, just deleting the csproj.user file (without needing to recreate solutions) was able to fix the problem for me.

The only side effect I had was I needed to reset the Start Action back to using a specific page.

C++: Where to initialize variables in constructor

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

How to unescape a Java string literal in Java?

org.apache.commons.lang3.StringEscapeUtils from commons-lang3 is marked deprecated now. You can use org.apache.commons.text.StringEscapeUtils#unescapeJava(String) instead. It requires an additional Maven dependency:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.4</version>
        </dependency>

and seems to handle some more special cases, it e.g. unescapes:

  • escaped backslashes, single and double quotes
  • escaped octal and unicode values
  • \\b, \\n, \\t, \\f, \\r

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Un-tick the Prevent saving changes that require table re-creation box from Tools ? Options ? Designers tab.

SQL Server 2012 example:

enter image description here

Counting no of rows returned by a select query

The syntax error is just due to a missing alias for the subquery:

select COUNT(*) from
(
select m.Company_id
from Monitor as m
    inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
    group by m.Company_id
    having COUNT(m.Monitor_id)>=5)  mySubQuery  /* Alias */

How to clear memory to prevent "out of memory error" in excel vba?

If you operate on a large dataset, it is very possible that arrays will be used. For me creating a few arrays from 500 000 rows and 30 columns worksheet caused this error. I solved it simply by using the line below to get rid of array which is no longer necessary to me, before creating another one:

Erase vArray

Also if only 2 columns out of 30 are used, it is a good idea to create two 1-column arrays instead of one with 30 columns. It doesn't affect speed, but there will be a difference in memory usage.