Programs & Examples On #Region management

How can I resolve the error: "The command [...] exited with code 1"?

The first step is figuring out what the error actually is. In order to do this expand your MsBuild output to be diagnostic. This will reveal the actual command executed and hopefully the full error message as well

  • Tools -> Options
  • Projects and Solutions -> Build and Run
  • Change "MsBuild project build output verbosity" to "Diagnostic".

Jackson: how to prevent field serialization

You can mark it as @JsonIgnore.

With 1.9, you can add @JsonIgnore for getter, @JsonProperty for setter, to make it deserialize but not serialize.

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

MySQL: Error dropping database (errno 13; errno 17; errno 39)

As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:

rm -f /var/lib/mysql/<database_name>/

And then drop the database from your tool of choice or using the command:

DROP DATABASE <database_name>

jQuery: enabling/disabling datepicker

I am also having This Error!

Then i change this

$("#from").datepicker('disable');

to This

$("#from").datepicker("disable");

mistake : single and double quotes..

Now its Work fine for me..

Table is marked as crashed and should be repaired

I had the same issue when my server free disk space available was 0

You can use the command (there must be ample space for the mysql files)

REPAIR TABLE `<table name>`;

for repairing individual tables

Connect Bluestacks to Android Studio

world !

No need to do execute batch command. With the current version, just run BLUESTACKS before ANDROID STUDIO

&& (AND) and || (OR) in IF statements

This goes back to the basic difference between & and &&, | and ||

BTW you perform the same tasks many times. Not sure if efficiency is an issue. You could remove some of the duplication.

Z z2 = partialHits.get(req_nr).get(z); // assuming a value cannout be null.
Z z3 = tmpmap.get(z); // assuming z3 cannot be null.
if(z2 == null || z2 < z3){   
    partialHits.get(z).put(z, z3);   
} 

Setting Custom ActionBar Title from Fragment

Use the following:

getActivity().setTitle("YOUR_TITLE");

How to do joins in LINQ on multiple fields in single join

var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

Best practice for localization and globalization of strings and labels

jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.

to know more about this take a look at the How to internationalize your pages using JQuery?

Bash ignoring error for a particular command

Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs) : and just "do nothing". You'll save a few letters. :)

#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

What's the HTML to have a horizontal space between two objects?

You could use the old ways. And use a table. In the table you define 3 columns. You set the width of your whole table and define the width of every colum. that way you can horizantaly space 2 objects. You put object one inside cell1 (colum1, row1) and object2 in cell3 (colum 3, row 1) and you leave cell 2 empty. Given it has a width, you will see empty spaces. example

<table width="500">
    <tr>
        <td width="40%">
            Object 1
        </td>
        <td width="20%">

        </td>
        <td width="40%">
            Object 2
        </td>
    </tr>
</table>

Or you could go the better way with div's. Just put your objects inside divs. Add a middle div and put these 3 divs inside another div. At the css style to the upper div: overflow: auto and define a width. Add css style to the 3 divs to define their width and add float: left example

<div style="overflow: auto;width: 100%;">
    <div style="width:200px;float: left;">
        Object  1
    </div>
    <div style="width:200px;float: left;">

    </div>
    <div style="width:200px;float: left;">
        Object  2
    </div>
</div>

Plotting time in Python with Matplotlib

You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Produces an image similar to this:

Scatter Plot

How to Compare two strings using a if in a stored procedure in sql server 2008?

declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable

Clear image on picturebox

I assume you want to clear the Images drawn via PictureBox.

This you would be achieved via a Bitmap object and using Graphics object. you might be doing something like

Graphics graphic = Graphics.FromImage(pictbox.Image);
graphic.Clear(Color.Red) //Color to fill the background and reset the box

Is this what you were looking out?

EDIT

Since you are using the paint method this would cause it to be redrawn every time, I would suggest you to set a flag at the formlevel indicating whether it should or not paint the Picturebox

private bool _shouldDraw = true;
public bool ShouldDraw
{
    get { return _shouldDraw; }
    set { _shouldDraw = value; }
}

In your paint just use

if(ShouldDraw)
  //do your stuff

When you click the button set this property to false and you should be fine.

How to format strings in Java

Java 15

There is a new instance method called String::formatted(Object... args) as of Java 15.

The internal implementation is same to String::format(String format, Object... args).

Formats using this string as the format string, and the supplied arguments.

String step1 = "one";
String step2 = "two";

// results in "Step one of two"
String string = "Step %s of %s".formatted(step1, step2);     

Advantage: The difference is that the method is not static and the formatting pattern is a string itself from which a new one is created based on the args. This allows chaining to build the format itself first.

Disadvantage: There is no overloaded method with Locale, therefore uses the default one. If you need to use a custom Locale, you have to stick with String::format(Locale l,String format,Object... args).

java : non-static variable cannot be referenced from a static context Error

You probably want to add "static" to the declaration of con2.

In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.

"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Not able to launch IE browser using Selenium2 (Webdriver) with Java

The following snippet of WebDriver Java code should work to launch IE. The code will ignore the setup of Protected mode settings for all zone in the IE browser.

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
File file = new File("D:\\Ripon Al Wasim\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get("https://www.google.com/");

Download IEDriverServer and extract it into your desired location and set the absolute path (In my above example it was "D:\Ripon Al Wasim\IEDriverServer.exe")

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

change your code to this

$start_date = new DateTime( "@" . $dbResult->db_timestamp );

and it will work fine

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you load a page in your browser using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your API must not allow for HTTPS connections. Because of this, you must either force HTTP on the main page or request that they allow HTTPS connections.

Note on this: The request will still work if you go to the API URL instead of attempting to load it with AJAX. This is because the browser is not loading a resource from within a secured page, instead it's loading an insecure page and it's accepting that. In order for it to be available through AJAX, though, the protocols should match.

Server cannot set status after HTTP headers have been sent IIS7.5

I had the same issue with setting StatusCode and then Response.End in HandleUnauthorizedRequest method of AuthorizeAttribute

var ctx = filterContext.HttpContext;
ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
ctx.Response.End();

If you are using .NET 4.5+, add this line before Response.StatusCode

filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

If you are using .NET 4.0, try SuppressFormsAuthenticationRedirectModule.

Counting the number of True Booleans in a Python List

If you are only concerned with the constant True, a simple sum is fine. However, keep in mind that in Python other values evaluate as True as well. A more robust solution would be to use the bool builtin:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

>>> sum(1 for x in l if x)
3

P.S. Python trivia: True could be true without being 1. Warning: do not try this at work!

>>> True = 2
>>> if True: print('true')
... 
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3

Much more evil:

True = False

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

convert month from name to number

With PHP 5.4, you can turn Matthew's answer into a one-liner:

$date = sprintf('%d-%d-01', $year, date_parse('may')['month']);

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

The operation cannot be completed because the DbContext has been disposed error

Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList() statement inside using scope

How to sort a list of strings?

It is also worth noting the sorted() function:

for x in sorted(list):
    print x

This returns a new, sorted version of a list without changing the original list.

What is the fastest way to send 100,000 HTTP requests in Python?

Using a thread pool is a good option, and will make this fairly easy. Unfortunately, python doesn't have a standard library that makes thread pools ultra easy. But here is a decent library that should get you started: http://www.chrisarndt.de/projects/threadpool/

Code example from their site:

pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()

Hope this helps.

Iterating through a list in reverse order in java

Here is an (untested) implementation of a ReverseIterable. When iterator() is called it creates and returns a private ReverseIterator implementation, which simply maps calls to hasNext() to hasPrevious() and calls to next() are mapped to previous(). It means you could iterate over an ArrayList in reverse as follows:

ArrayList<String> l = ...
for (String s : new ReverseIterable(l)) {
  System.err.println(s);
}

Class Definition

public class ReverseIterable<T> implements Iterable<T> {
  private static class ReverseIterator<T> implements Iterator {
    private final ListIterator<T> it;

    public boolean hasNext() {
      return it.hasPrevious();
    }

    public T next() {
      return it.previous();
    }

    public void remove() {
      it.remove();
    }
  }

  private final ArrayList<T> l;

  public ReverseIterable(ArrayList<T> l) {
    this.l = l;
  }

  public Iterator<T> iterator() {
    return new ReverseIterator(l.listIterator(l.size()));
  }
}

Appending HTML string to the DOM

Use insertAdjacentHTML if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.

div.insertAdjacentHTML( 'beforeend', str );

Live demo: http://jsfiddle.net/euQ5n/

printing all contents of array in C#

Starting from C# 6.0, when $ - string interpolation has been introduced, there is one more way:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");

//output
A, B, C

Concatenation could be archived using the System.Linq, convert the string[] to char[] and print as a string

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC

Where does the .gitignore file belong?

Put .gitignore in the working directory. It doesn't work if you put it in the .git (repository) directory.

$ ls -1d .git*
.git
.gitignore

Failed to install Python Cryptography package with PIP and setup.py

This solved the problem for me (Ubuntu 16.04):

sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev

and then it was working like this:

pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1

How to get the query string by javascript?

You can easily build a dictionary style collection...

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1); 
  var keyValues = queryString.split('&'); 

  for(var i in keyValues) { 
    var key = keyValues[i].split('=');
    if (key.length > 1) {
      assoc[decode(key[0])] = decode(key[1]);
    }
  } 

  return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 

Multiple submit buttons on HTML form – designate one button as default

You should not be using buttons of the same name. It's bad semantics. Instead, you should modify your backend to look for different name values being set:

<input type="submit" name="COMMAND_PREV" value="&lsaquo; Prev">
<input type="submit" name="COMMAND_SAVE" value="Save">
<input type="reset"  name="NOTHING" value="Reset">
<input type="submit" name="COMMAND_NEXT" value="Next &rsaquo;">
<input type="button" name="NOTHING" value="Skip &rsaquo;" onclick="window.location = 'yada-yada.asp';">

Since I don't know what language you are using on the backend, I'll give you some pseudocode:

if (input name COMMAND_PREV is set) {

} else if (input name COMMAND_SAVE is set) {

} else if (input name COMMENT_NEXT is set) {

}

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

For Kotlin Users don't forget to add ? in data: Intent? like

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}

How to get file's last modified date on Windows command line?

Useful reference to get file properties using a batch file, included is the last modified time:

FOR %%? IN ("C:\somefile\path\file.txt") DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Drive and Path       : %%~dp?
    ECHO Drive                : %%~d?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)

Can I set enum start value in Java?

If you want emulate enum of C/C++ (base num and nexts incrementals):

enum ids {
    OPEN, CLOSE;
    //
    private static final int BASE_ORDINAL = 100;
    public int getCode() {
        return ordinal() + BASE_ORDINAL;
    }
};

public class TestEnum {
    public static void main (String... args){
        for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
            System.out.println(i.toString() + " " + 
                i.ordinal() + " " + 
                i.getCode());
        }
    }
}
OPEN 0 100
CLOSE 1 101

using mailto to send email with an attachment

what about this

<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
 <input type="submit" name="submit" id="submit" value="Email"/>
</FORM>

Android: How to set password property in an edit text?

I found when doing this that in order to set the gravity to center, and still have your password hint show when using inputType, the android:gravity="Center" must be at the end of your XML line.

<EditText android:textColor="#000000" android:id="@+id/editText2" 
    android:layout_width="fill_parent" android:hint="Password" 
    android:background="@drawable/rounded_corner" 
    android:layout_height="fill_parent" 
    android:nextFocusDown="@+id/imageButton1" 
    android:nextFocusRight="@+id/imageButton1" 
    android:nextFocusLeft="@+id/editText1"
    android:nextFocusUp="@+id/editText1" 
    android:inputType="textVisiblePassword" 
    android:textColorHint="#999999" 
    android:textSize="16dp" 
    android:gravity="center">
</EditText>

Does MySQL ignore null values on unique constraints?

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;

Result:

x
NULL
NULL
1

This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

git add, commit and push commands in one?

There are plenty of good solutions already, but here's a solution that I find more elegant for the way I want to work:

I put a script in my path called "git-put" that contains:

#!/bin/bash
git commit "$@" && git push -u

That allows me to run:

git put -am"my commit message"

..to add all files, commit them, and push them.

(I also added the "-u" because I like to do this anyway, even though it's not related to this issue. It ensures that the upstream branch is always set up for pulling.)

I like this approach because it also allows to to use "git put" without adding all the files (skip the "-a"), or with any other options I might want to pass to commit. Also, "put" is a short portmanteau of "push" and "commit"

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

How to convert color code into media.brush?

For simplicity you could create an extension:-

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

And then to use:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

How to set height property for SPAN

Another option of course is to use Javascript (Jquery here):

$('.box1,.box2').each(function(){
    $(this).height($(this).parent().height());
})

How to support placeholder attribute in IE8 and 9

You could use this jQuery plugin: https://github.com/mathiasbynens/jquery-placeholder

But your link seems to be also a good solution.

How to override the path of PHP to use the MAMP path?

Sometimes, it's easier to do this:

sudo ln -s /Applications/MAMP/bin/php/php5.6.10/bin/php /usr/bin/php;

Mamps version of PHP at the time of posting was php5.6.10, so make sure you change that to the version you're using.

You'll be up in a jiffy.

Fully backup a git repo?

Whats about just make a clone of it?

git clone --mirror other/repo.git

Every repository is a backup of its remote.

How do I create dynamic variable names inside a loop?

I agree it is generally preferable to use an Array for this.

However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this – which always refers to the current scope.

for (var i = 0; i < coords.length; ++i) {
    this["marker"+i] = "some stuff";
}

You can later retrieve the stored values (if you are within the same scope as when they were set):

var foo = this.marker0;
console.log(foo); // "some stuff"

This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.

Standard Android menu icons, for example refresh

Bear in mind, this is a practice that Google explicitly advises not to do:

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable).

Rather, you are adviced to make a local copy:

If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

What does "<>" mean in Oracle

It (<>) is a function that is used to compare values in database table.

!= (Not equal to) functions the same as the <> (Not equal to) comparison operator.

Get LatLng from Zip Code - Google Maps API

This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:

_x000D_
_x000D_
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
    var geocoder = new google.maps.Geocoder();_x000D_
    var address = zipcode;_x000D_
    geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
        if (status == google.maps.GeocoderStatus.OK) {_x000D_
            var latitude = results[0].geometry.location.lat();_x000D_
            var longitude = results[0].geometry.location.lng();_x000D_
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
        } else {_x000D_
            alert("Request failed.")_x000D_
        }_x000D_
    });_x000D_
    return [latitude, longitude];_x000D_
}
_x000D_
_x000D_
_x000D_

Selected value for JSP drop down using JSTL

You can try one even more simple:

<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>

How do I use $scope.$watch and $scope.$apply in AngularJS?

Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:

1) They are all event-driven things. (I hear the laugh, but read on)

If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.

2) $watch is "on-click".

What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...

3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.

4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)

Now, let's make it visual. Picture this to make it even more easy to grab the idea:

In a restaurant,

- WAITERS

are supposed to take orders from customers, this is

$watch(
  function(){return orders;},
  function(){Kitchen make it;}
);

- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()

- OWNER has the ultimate power to drive everyone upon request, this is $apply()

How to get rid of the "No bootable medium found!" error in Virtual Box?

FIX 1:

Step1: Go to settings > then select the following configuration(Disable Floppy)

Config

Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.

Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.

FIX 2:

Go to Settings > And Perform the following:

Config1

FIX 3:

Try Fix 1 & 2 together..

Sending Arguments To Background Worker?

You start it like this:

int value = 123;
bgw1.RunWorkerAsync(argument: value);  // the int will be boxed

and then

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
   int value = (int) e.Argument;   // the 'argument' parameter resurfaces here

   ...

   // and to transport a result back to the main thread
   double result = 0.1 * value;
   e.Result = result;
}


// the Completed handler should follow this pattern 
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e) 
{
  // check error, check cancel, then use result
  if (e.Error != null)
  {
     // handle the error
  }
  else if (e.Cancelled)
  {
     // handle cancellation
  }
  else
  {          
      double result = (double) e.Result;
      // use it on the UI thread
  }
  // general cleanup code, runs when there was an error or not.
}

How to add "active" class to wp_nav_menu() current menu item (simple way)

Just paste this code into functions.php file:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
  if (in_array('current-menu-item', $classes) ){
    $classes[] = 'active ';
  }
  return $classes;
}

More on wordpress.org:

How to get html to print return value of javascript function?

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

When does Java's Thread.sleep throw InterruptedException?

You should generally NOT ignore the exception. Take a look at the following paper:

Don't swallow interrupts

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}

See the entire paper here:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

How to cancel an $http request in AngularJS?

here is a version that handles multiple requests, also checks for cancelled status in callback to suppress errors in error block. (in Typescript)

controller level:

    requests = new Map<string, ng.IDeferred<{}>>();

in my http get:

    getSomething(): void {
        let url = '/api/someaction';
        this.cancel(url); // cancel if this url is in progress

        var req = this.$q.defer();
        this.requests.set(url, req);
        let config: ng.IRequestShortcutConfig = {
            params: { id: someId}
            , timeout: req.promise   // <--- promise to trigger cancellation
        };

        this.$http.post(url, this.getPayload(), config).then(
            promiseValue => this.updateEditor(promiseValue.data as IEditor),
            reason => {
                // if legitimate exception, show error in UI
                if (!this.isCancelled(req)) {
                    this.showError(url, reason)
                }
            },
        ).finally(() => { });
    }

helper methods

    cancel(url: string) {
        this.requests.forEach((req,key) => {
            if (key == url)
                req.resolve('cancelled');
        });
        this.requests.delete(url);
    }

    isCancelled(req: ng.IDeferred<{}>) {
        var p = req.promise as any; // as any because typings are missing $$state
        return p.$$state && p.$$state.value == 'cancelled';
    }

now looking at the network tab, i see that it works beatuifully. i called the method 4 times and only the last one went through.

enter image description here

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

"make clean" results in "No rule to make target `clean'"

I suppose you have figured it out by now. The answer is hidden in your first mail itself.

The make command by default looks for makefile, Makefile, and GNUMakefile as the input file and you are having Makefile.txt in your folder. Just remove the file extension (.txt) and it should work.

I just assigned a variable, but echo $variable shows something else

You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:

Why do I need to write "$foo"? What happens without the quotes?

$foo does not mean “take the value of the variable foo”. It means something much more complex:

  • First, take the value of the variable.
  • Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains foo * bar ? then the result of this step is the 3-element list foo, *, bar.
  • Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing foo, following by the list of files in the current directory, and finally bar. If the current directory is empty, the result is foo, *, bar.

Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception: "$@" to expand to the list of positional parameters, e.g. "$@" is equivalent to "$1" "$2" "$3" if there are three positional parameters. See What is the difference between $* and $@?)

The same happens to command substitution with $(foo) or with `foo`. On a side note, don't use `foo`: its quoting rules are weird and non-portable, and all modern shells support $(foo) which is absolutely equivalent except for having intuitive quoting rules.

The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming IFS doesn't contain digits or -).

See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.

Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.

How to delete row based on cell value

You could copy down a formula like the following in a new column...

=IF(ISNUMBER(FIND("-",A1)),1,0)

... then sort on that column, highlight all the rows where the value is 1 and delete them.

"Could not find bundler" error

The system might be running "rootless". Try to set the firmware nvram variable boot-args to "rootless=0". Try to run set of commands:

sudo nvram boot-args="rootless=0"; 
sudo reboot

After reboot completes, run:

sudo gem install bundler

How to handle the new window in Selenium WebDriver using Java?

I have an utility method to switch to the required window as shown below

public class Utility 
{
    public static WebDriver getHandleToWindow(String title){

        //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
        WebDriver popup = null;
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
          String windowHandle = s; 
          popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

        }
                System.out.println("Window Title :" + popup.getTitle());
                System.out.println();
            return popup;
        }
}

It will take you to desired window once title of the window is passed as parameter. In your case you can do.

Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");

and then again switch to parent window using the same method

Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");

This method works effectively when dealing with multiple windows.

Is there a printf converter to print in binary format?

Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.

#include <stdio.h>

void print_binary(unsigned int number)
{
    if (number >> 1) {
        print_binary(number >> 1);
    }
    putc((number & 1) ? '1' : '0', stdout);
}

To me, this is one of the cleanest solutions to the problem. If you like 0b prefix and a trailing new line character, I suggest wrapping the function.

Online demo

Change key pair for ec2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

There is a startup process on most AMIs that downloads the public ssh key and installs it in a .ssh/authorized_keys file so that you can ssh in as that user using the corresponding private ssh key.

If you want to change what ssh key you use to access an instance, you will want to edit the authorized_keys file on the instance itself and convert to your new ssh public key.

The authorized_keys file is under the .ssh subdirectory under the home directory of the user you are logging in as. Depending on the AMI you are running, it might be in one of:

/home/ec2-user/.ssh/authorized_keys
/home/ubuntu/.ssh/authorized_keys
/root/.ssh/authorized_keys

After editing an authorized_keys file, always use a different terminal to confirm that you are able to ssh in to the instance before you disconnect from the session you are using to edit the file. You don't want to make a mistake and lock yourself out of the instance entirely.

While you're thinking about ssh keypairs on EC2, I recommend uploading your own personal ssh public key to EC2 instead of having Amazon generate the keypair for you.

Here's an article I wrote about this:

Uploading Personal ssh Keys to Amazon EC2
http://alestic.com/2010/10/ec2-ssh-keys

This would only apply to new instances you run.

unique() for more than one variable

This is an addition to Josh's answer.

You can also keep the values of other variables while filtering out duplicated rows in data.table

Example:

library(data.table)

#create data table
dt <- data.table(
  V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
  V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
  V3=c(1),
  V4=c(2) )

> dt
# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# A  B  1  2
# B  A  1  2
# C  D  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2
# A  B  1  2

# set the key to all columns
setkey(dt)

# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] ) 

# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# B  A  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2

Alert: If there are different combinations of values in the other variables, then your result will be

unique combination of V1 and V2

How to parse data in JSON format?

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']

Add new line in text file with Windows batch file

You can use:

type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt

or something like this:

echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

Running Jupyter via command line on Windows

100% working solution:

Follow these steps:

  1. Open the folder where you downloaded "python-3.8.2-amd64.exe" setup or any other version of python package

  2. Double click on "python-3.8.2-amd64.exe'

  3. Click "Modify"

  4. You will see "Optional features"

  5. Click "next"

  6. Select "Add python to environment variables"

  7. Click "install"

  8. Then u can run jupyter in any desired folder u desire

    E.g  open "cmd" command prompt

    Type : 
    E: 

    E:\>jupyter notebook

    It will get started without showing

    'Jupyter' is not recognized

Thanks

Increasing the timeout value in a WCF service

Are you referring to the server side or the client side?

For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.

<system.serviceModel>
  <bindings>
    <netTcpBinding>
      <binding name="longTimeoutBinding"
        receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="None"/>
      </binding>
    </netTcpBinding>
  </bindings>

  <services>
    <service name="longTimeoutService"
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="net.tcp://localhost/longtimeout/"
        binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
    </service>
....

Of course, you have to map your desired endpoint to that particular binding.

How to install gdb (debugger) in Mac OSX El Capitan?

Install Homebrew first :

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run this : brew install gdb

What's a Good Javascript Time Picker?

You could read jQuery creator John Resig's post about it here: http://ejohn.org/blog/picking-time/.

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

What is the best IDE to develop Android apps in?

Eclipse is the best IDE. It easy to setup android and debug applications in eclipse

How to change scroll bar position with CSS?

Using CSS only:

Right/Left Flippiing: Working Fiddle

.Container
{
    height: 200px;
    overflow-x: auto;
}
.Content
{
    height: 300px;
}

.Flipped
{
    direction: rtl;
}
.Content
{
    direction: ltr;
}

Top/Bottom Flipping: Working Fiddle

.Container
{
    width: 200px;
    overflow-y: auto;
}
.Content
{
    width: 300px;
}

.Flipped, .Flipped .Content
{
    transform:rotateX(180deg);
    -ms-transform:rotateX(180deg); /* IE 9 */
    -webkit-transform:rotateX(180deg); /* Safari and Chrome */
}

Change default date time format on a single database in SQL Server

Although you can not set the default date format for a single database, you can change the default language for a login which is used to access this database:

ALTER LOGIN your_login WITH DEFAULT_LANGUAGE=British

In some cases it helps.

Why doesn't C++ have a garbage collector?

The idea behind C++ was that you would not pay any performance impact for features that you don't use. So adding garbage collection would have meant having some programs run straight on the hardware the way C does and some within some sort of runtime virtual machine.

Nothing prevents you from using some form of smart pointers that are bound to some third-party garbage collection mechanism. I seem to recall Microsoft doing something like that with COM and it didn't go to well.

How can I pass POST parameters in a URL?

First off, a disclaimer: I don't think marrying POST with URL parameters is a brilliant idea. Like others suggested, you're better off using a hidden form for passing user information.

However, a question made me curious how PHP is handling such a case. It turned out that it's possible in theory. Here's a proof:

post_url_params.html

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <form method="post" action="post_url_params.php?key1=value1">
            <input type="hidden" name="key2" value="value2">
            <input type="hidden" name="key3" value="value3">
            <input type="submit" value="click me">
        </form>
    </body>
</html>

post_url_params.php

<?php
    print_r($_POST);
    print_r($_GET);
    echo $_SERVER['REQUEST_METHOD'];
?>

Output

Array ( [key2] => value2 [key3] => value3 )
Array ( [key1] => value1 )
POST

One can clearly see that PHP stores URL parameters in the $_GET variable and form data in the $_POST variable. I suspect it's very PHP- and server-specific, though, and is definitely not a thing to rely on.

Get value from text area

$('textarea').val();

textarea.value would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).

Remove all whitespace in a string

eliminate all the whitespace from a string, on both ends, and in between words.

>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
    '', # replace with empty string (->remove)
    ''' hello
...    apple
... ''')
'helloapple'

Python docs:

Facebook API error 191

Had the same problem:

$params = array('redirect_uri' => 'facebook.com/pages/foobar-dev');
$facebook->getLoginUrl($params);

When I changed the redirect_uri from the devloper page to the live page, 191 Error came up.

So I deleted the $params:

$facebook->getLoginUrl();

After the app-request now FB redirects to the app url itself f.e.: my.domain.com

What I do now is checking in index.php of my app if I'm inside FB iframe or not. If not I redirect to the live FB page f.e.:

$app = 'facebook.com/pages/foobar-live';
$rd = (isset($_SERVER['HTTP_REFERER'])) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : false;
if ($rd == 'apps.facebook.com' || (!isset($_REQUEST['signed_request'])))  {
    echo '<script>window.parent.location = "'.$app.'";</script>';
    die();
}

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

HTML5 Pre-resize images before uploading

I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader

robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.

Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:

ImageUploader.prototype.scaleImage = function(img, completionCallback) {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);

    while (canvas.width >= (2 * this.config.maxWidth)) {
        canvas = this.getHalfScaleCanvas(canvas);
    }

    if (canvas.width > this.config.maxWidth) {
        canvas = this.scaleCanvasWithAlgorithm(canvas);
    }

    var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
    this.performUpload(imageData, completionCallback);
};

ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
    var scaledCanvas = document.createElement('canvas');

    var scale = this.config.maxWidth / canvas.width;

    scaledCanvas.width = canvas.width * scale;
    scaledCanvas.height = canvas.height * scale;

    var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
    var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);

    this.applyBilinearInterpolation(srcImgData, destImgData, scale);

    scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);

    return scaledCanvas;
};

ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
    var halfCanvas = document.createElement('canvas');
    halfCanvas.width = canvas.width / 2;
    halfCanvas.height = canvas.height / 2;

    halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);

    return halfCanvas;
};

ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
    function inner(f00, f10, f01, f11, x, y) {
        var un_x = 1.0 - x;
        var un_y = 1.0 - y;
        return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
    }
    var i, j;
    var iyv, iy0, iy1, ixv, ix0, ix1;
    var idxD, idxS00, idxS10, idxS01, idxS11;
    var dx, dy;
    var r, g, b, a;
    for (i = 0; i < destCanvasData.height; ++i) {
        iyv = i / scale;
        iy0 = Math.floor(iyv);
        // Math.ceil can go over bounds
        iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
        for (j = 0; j < destCanvasData.width; ++j) {
            ixv = j / scale;
            ix0 = Math.floor(ixv);
            // Math.ceil can go over bounds
            ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
            idxD = (j + destCanvasData.width * i) * 4;
            // matrix to vector indices
            idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
            idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
            idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
            idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
            // overall coordinates to unit square
            dx = ixv - ix0;
            dy = iyv - iy0;
            // I let the r, g, b, a on purpose for debugging
            r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
            destCanvasData.data[idxD] = r;

            g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
            destCanvasData.data[idxD + 1] = g;

            b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
            destCanvasData.data[idxD + 2] = b;

            a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
            destCanvasData.data[idxD + 3] = a;
        }
    }
};

This scales an image down to a width of config.maxWidth, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).

The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.

Should I use <i> tag for icons instead of <span>?

I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i> tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.

It does make really bad practice because when I saw it I went through the template and changed all the <i> tags to <span style="font-style:italic"> instead and then wondered why the entire template looked strange.

This is the main reason it is a bad idea to use the <i> tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code

<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">

that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i> - and also it passes W3C standard.

AngularJS dynamic routing

Here is another solution that works good.

(function() {
    'use strict';

    angular.module('cms').config(route);
    route.$inject = ['$routeProvider'];

    function route($routeProvider) {

        $routeProvider
            .when('/:section', {
                templateUrl: buildPath
            })
            .when('/:section/:page', {
                templateUrl: buildPath
            })
            .when('/:section/:page/:task', {
                templateUrl: buildPath
            });



    }

    function buildPath(path) {

        var layout = 'layout';

        angular.forEach(path, function(value) {

            value = value.charAt(0).toUpperCase() + value.substring(1);
            layout += value;

        });

        layout += '.tpl';

        return 'client/app/layouts/' + layout;

    }

})();

How to convert signed to unsigned integer in python

You could use the struct Python built-in library:

Encode:

import struct

i = -6884376
print('{0:b}'.format(i))

packed = struct.pack('>l', i)  # Packing a long number.
unpacked = struct.unpack('>L', packed)[0]  # Unpacking a packed long number to unsigned long
print(unpacked)
print('{0:b}'.format(unpacked))

Out:

-11010010000110000011000
4288082920
11111111100101101111001111101000

Decode:

dec_pack = struct.pack('>L', unpacked)  # Packing an unsigned long number.
dec_unpack = struct.unpack('>l', dec_pack)[0]  # Unpacking a packed unsigned long number to long (revert action).
print(dec_unpack)

Out:

-6884376

[NOTE]:

  • > is BigEndian operation.
  • l is long.
  • L is unsigned long.
  • In amd64 architecture int and long are 32bit, So you could use i and I instead of l and L respectively.

jQuery Ajax File Upload

<html>
    <head>
        <title>Ajax file upload</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (e) {
            $("#uploadimage").on('submit', (function(e) {
            e.preventDefault();
                    $.ajax({
                    url: "upload.php", // Url to which the request is send
                            type: "POST", // Type of request to be send, called as method
                            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                            contentType: false, // The content type used when sending data to the server.
                            cache: false, // To unable request pages to be cached
                            processData:false, // To send DOMDocument or non processed data file it is set to false
                            success: function(data)   // A function to be called if request succeeds
                            {
                            alert(data);
                            }
                    });
            }));
        </script>
    </head>
    <body>
        <div class="main">
            <h1>Ajax Image Upload</h1><br/>
            <hr>
            <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
                <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
                <hr id="line">
                <div id="selectImage">
                    <label>Select Your Image</label><br/>
                    <input type="file" name="file" id="file" required />
                    <input type="submit" value="Upload" class="submit" />
                </div>
            </form>
        </div>
    </body>
</html>

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

Don't use jsonObject.toString on a JSON object.

Check if a JavaScript string is a URL

Rely on a library: https://www.npmjs.com/package/valid-url

import { isWebUri } from 'valid-url';
// ...
if (!isWebUri(url)) {
    return "Not a valid url.";
}

Filter Pyspark dataframe column with None value

There are multiple ways you can remove/filter the null values from a column in DataFrame.

Lets create a simple DataFrame with below code:

date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())

Now you can try one of the below approach to filter out the null values.

# Approach - 1
df.filter("value is not null").show()

# Approach - 2
df.filter(col("value").isNotNull()).show()

# Approach - 3
df.filter(df["value"].isNotNull()).show()

# Approach - 4
df.filter(df.value.isNotNull()).show()

# Approach - 5
df.na.drop(subset=["value"]).show()

# Approach - 6
df.dropna(subset=["value"]).show()

# Note: You can also use where function instead of a filter.

You can also check the section "Working with NULL Values" on my blog for more information.

I hope it helps.

Mapping object to dictionary and vice versa

I'd highly recommend the Castle DictionaryAdapter, easily one of that project's best-kept secrets. You only need to define an interface with the properties you want, and in one line of code the adapter will generate an implementation, instantiate it, and synchronize its values with a dictionary you pass in. I use it to strongly-type my AppSettings in a web project:

var appSettings =
  new DictionaryAdapterFactory().GetAdapter<IAppSettings>(ConfigurationManager.AppSettings);

Note that I did not need to create a class that implements IAppSettings - the adapter does that on the fly. Also, although in this case I'm only reading, in theory if I were setting property values on appSettings, the adapter would keep the underlying dictionary in sync with those changes.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

MathGL have many plot types, C/Fortran interface and basic data analysis

What is the reason for a red exclamation mark next to my project in Eclipse?

It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.

Just once again configure the jars.

How to force a line break in a long word in a DIV?

Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks

.pre-wrap {
    white-space: pre-wrap;
    word-break: break-word;
}

DEMO

_x000D_
_x000D_
td {_x000D_
   word-break: break-word;_x000D_
   white-space: pre-wrap;_x000D_
   -moz-white-space: pre-wrap;      _x000D_
}_x000D_
_x000D_
table {_x000D_
    width: 100px;_x000D_
    border: 1px solid black;_x000D_
    display: block;_x000D_
}
_x000D_
<table>_x000D_
<tr><th>list</th>_x000D_
<td>_x000D_
1.longtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtext_x000D_
2.breaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreakline_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

remote rejected master -> master (pre-receive hook declined)

Make sure that your Rails app is in the root of the repo, the Gemfile is present and properly named. It is basically not able to detect your code base as one of the supported project types and hence failing it. Also, even if you do have a proper project, make sure it is part of the repository and you have committed it fine (git status will help you here and a ls should help you verify the project structure).

htaccess - How to force the client's browser to clear the cache?

Now the following wont help you with files that are already cached, but moving forward, you can use the following to easily force a request to get something new, without changing the actual filename.

# Rewrite all requests for JS and CSS files to files of the same name, without
# any numbers in them. This lets the JS and CSS be force out of cache easily
# by putting a number at the end of the filename
# e.g. a request for static/js/site-52.js will get the file static/js/site.js instead.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^static/(js|css)/([a-z]+)-([0-9]+)\.(js|css)$ /site/$1/$2.$4 [R=302,NC,L]
</IfModule>

Of course, the higher up in your folder structure you do this type of approach, the more you kick things out of cache with a simple change.

So for example, if you store the entire css and javascript of your site in one main folder

/assets/js
/assets/css
/assets/...

Then you can could start referencing it as "assets-XXX" in your html, and use a rule like so to kick all assets content out of cache.

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^assets-([a-z0-9]+)/(.*) /$2 [R=302,NC,L]
</IfModule> 

Note that if you do go with this, after you have it working, change the 302 to a 301, and then caching will kick in. When it's a 302 it wont cache at the browser level because it's a temporary redirect. If you do it this way, then you could bump up the expiry default time to 30 days for all assets, since you can easily kick things out of cache by simply changing the folder name in the login page.

<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault A2592000
</IfModule>

Fatal Error :1:1: Content is not allowed in prolog

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

http://en.wikipedia.org/wiki/Byte_order_mark

How to deal with SQL column names that look like SQL keywords?

These are the two ways to do it:

  1. Use back quote as here:

SELECT `from` FROM TableName

  1. You can mention with table name as:

SELECT TableName.from FROM TableName

Drop shadow for PNG image in CSS

In my case it had to work on modern mobile browsers, with a PNG image in different shapes and transparency. I created drop shadow using a duplicate of the image. That means I have two img elements of the same image, one on top of the other (using position: absolute), and the one behind has the following rules applied to it:

.image-shadow {
  filter: blur(10px) brightness(-100);
  -webkit-filter: blur(10px) brightness(-100);
  opacity: .5;
}

This includes brightness filter in order to darken the bottom image, and a blur filter in order to cast the smudgy effect drop shadow usually has. Opacity at 50% is then applied in order to soften it.

This can be applied cross browser using moz and ms flags.

Example: https://jsfiddle.net/5mLssm7o/

Create Table from JSON Data with angularjs and ng-repeat

The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:

var phonecatApp = angular.module('phonecatApp', []);   
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
 $http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
}); 
$scope.orderProp = 'age';
});

We then iterate over the phones:

<table>
  <tbody ng-repeat="i in phones">
    <tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
    <tr ng-repeat="e in i.details">
       <td>{{$index}}</td>
       <td>{{e.foo}}</td>
       <td>{{e.bar}}</td></tr>
  </tbody>
</table>

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

Correct way to write line to file?

You should use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

For Python 3 you don't need the import, since the print() function is the default.

The alternative would be to use:

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

Quoting from Python documentation regarding newlines:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

favicon not working in IE

Try something like:

Add to html:

  <link id="shortcutIcon" rel="shortcut icon" type="image/x-icon">
  <link id="icon" rel="icon" type="image/x-icon">

Add minified script after tag:

<script type="text/javascript">
(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));
</script>

where

  • '/assets/images/favicon.ico' related path to .ico
  • ?v='Math.random()*100' - to force browser update favicon.ico

Before test clear history: (ctr + shfit + del)

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.

point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>

more details in this answer: https://stackoverflow.com/a/37465080/473040

How do I delete a local repository in git?

Delete the .git directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).

If you want to delete everything (git-data, code, etc), just delete the whole directory.

.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.

MongoDB not equal to

If there is a null in an array and you want to avoid it:

db.test.find({"contain" : {$ne :[] }}).pretty()

How can I convert uppercase letters to lowercase in Notepad++

In my notepad++ I press

Ctrl+A = To select all words

Ctrl+U = To convert lowercase

Ctrl+Shift+U = To convert uppercase

Hope to help you!

Determine which element the mouse pointer is on top of in JavaScript

Let me start out by saying that I don't recommend using the method I'm about to suggest. It's much better to use event driven development and bind events only to the elements you're interested in knowing whether or not the mouse is over with mouseover, mouseout, mouseenter, mouseleave, etc.

If you absolutely must have the ability to know which element the mouse is over, you'd need to write a function that binds the mouseover event to everything in the DOM, and then store whatever the current element is in some variable.

You could so something like this:

window.which_element_is_the_mouse_on = (function() {

    var currentElement;

    $("body *").on('mouseover', function(e) {
        if(e.target === e.currentTarget) {
            currentElement = this;
        }
    });

    return function() {
        console.log(currentElement);
    }
}());

Basically, I've created an immediate function which sets the event on all elements and stores the current element within the closure to minimize your footprint.

Here's a working demo that calls window.which_element_is_the_mouse_on every second and logs what element the mouse is currently over to the console.

http://jsfiddle.net/LWFpJ/1/

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

Datetime in C# add days

Use this:

DateTime dateTime =  DateTime.Now;
DateTime? newDateTime = null;
TimeSpan numberOfDays = new TimeSpan(2, 0, 0, 0, 0);
newDateTime = dateTime.Add(numberOfDays);

Trigger 404 in Spring-MVC controller?

Since Spring 3.0.2 you can return ResponseEntity<T> as a result of the controller's method:

@RequestMapping.....
public ResponseEntity<Object> handleCall() {
    if (isFound()) {
        // do what you want
        return new ResponseEntity<>(HttpStatus.OK);
    }
    else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

(ResponseEntity<T> is a more flexible than @ResponseBody annotation - see another question)

Strip all non-numeric characters from string in JavaScript

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

1238

changing visibility using javascript

Use display instead of visibility. display: none for invisible and no setting for visible.

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

how to take user input in Array using java?

import java.util.Scanner;

class Example{

//Checks to see if a string is consider an integer.

public static boolean isInteger(String s){

    if(s.isEmpty())return false;

    for (int i = 0; i <s.length();++i){

        char c = s.charAt(i);

        if(!Character.isDigit(c) && c !='-')

            return false;
    }

    return true;
}

//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.

public static int getInteger(String prompt){
    Scanner input = new Scanner(System.in);
    String in = "";
    System.out.println(prompt);
    in = input.nextLine();
    while(!isInteger(in)){
        System.out.println(prompt);
        in = input.nextLine();
    }
    input.close();
    return Integer.parseInt(in);
}

public static void main(String[] args){
    int [] a = new int[6];
    for (int i = 0; i < a.length;++i){
        int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
        a[i] = tmp;
    }

}

}

os.walk without digging into directories below

The suggestion to use listdir is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next().

The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))

How to hide form code from view code/inspect element browser?

if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line.

File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}

NOTE:

To convert an active record database to csv would be something like this I think

CSV.open(fn, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values
  end
end

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0
CSV.open(fn, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
    else
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

How can I create a text box for a note in markdown?

The following methods work on GitHub, on GitLab... and on Stackoverflow, which now uses CommonMark!


> One-Line Box made with Blockquote

One-Line Box made with Blockquote


`One-Line Box made with Backticks`

One-Line Box made with Backticks


```
Box made with Triple Backticks
```

Box made with Triple Backticks  


~ ~ ~
Box made with Triple Tildes
(remove the spaces between the tildes to make this work)
~ ~ ~

Box made with Triple Tildes


Box made with Four Spaces at the start of each line:

    “Sometimes we must let go of our pride and do what is requested of us.”
    Padmé Amidala


... or use horizontal lines?

Three dashes (---) make a horizontal line:


Note: “ Your focus determines your reality.” – Qui-Gon Jinn.


For more configurations, I strongly advise the excellent GitLab Markdown Guide.
You can also check the less detailed GitHub basic formatting syntax.
You can compare Markdown implementations using Babelmark.

Useful hints :

  • to force a newline, put two spaces at the end of the line;

  • to escape special characters, use \.

How to set a Timer in Java?

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to semantically add heading to a list

a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:

<div class="mydiv">
    <h3>The heading</h3>
    <ul>
       <li>item</li>
       <li>item</li>
       <li>item</li>
    </ul>
</div>

then you can use the following css to style everything together as one unit

.mydiv{}
.mydiv h3{}
.mydiv ul{}
.mydiv ul li{}
etc...

Best /Fastest way to read an Excel Sheet into a DataTable?

I have always used OLEDB for this, something like...

    Dim sSheetName As String
    Dim sConnection As String
    Dim dtTablesList As DataTable
    Dim oleExcelCommand As OleDbCommand
    Dim oleExcelReader As OleDbDataReader
    Dim oleExcelConnection As OleDbConnection

    sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""

    oleExcelConnection = New OleDbConnection(sConnection)
    oleExcelConnection.Open()

    dtTablesList = oleExcelConnection.GetSchema("Tables")

    If dtTablesList.Rows.Count > 0 Then
        sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
    End If

    dtTablesList.Clear()
    dtTablesList.Dispose()

    If sSheetName <> "" Then

        oleExcelCommand = oleExcelConnection.CreateCommand()
        oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
        oleExcelCommand.CommandType = CommandType.Text

        oleExcelReader = oleExcelCommand.ExecuteReader

        nOutputRow = 0

        While oleExcelReader.Read

        End While

        oleExcelReader.Close()

    End If

    oleExcelConnection.Close()

The ACE.OLEDB provider will read both .xls and .xlsx files and I have always found the speed quite good.

get the value of "onclick" with jQuery?

Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.

But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.

$("#google").click(function() {
    if (situation) {
        // ...
    } else {
        // ...
    }
});

Amazon Interview Question: Design an OO parking lot

Here is a quick start to get the gears turning...

ParkingLot is a class.

ParkingSpace is a class.

ParkingSpace has an Entrance.

Entrance has a location or more specifically, distance from Entrance.

ParkingLotSign is a class.

ParkingLot has a ParkingLotSign.

ParkingLot has a finite number of ParkingSpaces.

HandicappedParkingSpace is a subclass of ParkingSpace.

RegularParkingSpace is a subclass of ParkingSpace.

CompactParkingSpace is a subclass of ParkingSpace.

ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.

ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()

Parker is a class.

Parker can Park().

Parker can Unpark().

Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.

Parker has a ParkingSpace.

Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().

Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().

HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)

In this solution, it is possible that Parker should be renamed to be Car.

PHP XML Extension: Not installed

I solved this issue with commands bellow:

$ sudo apt-get install php7.3-intl

$ sudo /etc/init.d/php7.3-fpm restart

These commands works for me in homestead with php7.3

Bootstrap row class contains margin-left and margin-right which creates problems

The .row is meant to be used inside a container. Since the container has padding to adjust the negative margin in the .row, grid columns used inside the .row can then adjust to the full width of the container. See the Bootstrap docs: http://getbootstrap.com/css/#grid

Here's an example to illustrate: http://bootply.com/131054

So, a better solution may for you to place your .row inside a .container or .container-fluid

Convert Bitmap to File

Hope it will help u:

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

Git: Could not resolve host github.com error while cloning remote repository in git

In my case, on a Windows box, my TCP/IP stack seems to have needed to be reset. Resetting the TCP/IP stack of the client PC caused git to start behaving properly again. Run this command in Administrator mode at a command prompt and retry the git command:

netsh int ip reset

Manually disabling and re-enabling the network adapter via the Control Panel produces a similar result.

I suspect DNS resolution problems inside the TCP stack on my Windows box.

How to sum array of numbers in Ruby?

Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):

array.inject(0){|sum,x| sum + x.amount}

Android Studio is slow (how to speed up)?

I followed this post and it worked great for me.

EDIT:

Following tips have been mentioned in the above post.

In gradle.properties, put this:

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true

And in build.gradle, put this (Note this will disable lint check):

tasks.whenTaskAdded { task ->
    if (task.name.equals("lint")) {
        task.enabled = false
    }
}

failed to find target with hash string android-23

I fixed the issue for me by opening the Android SDK Manager and installing the build tools for all 23.x.x versions.

See the screenshot.

enter image description here

Where is Android Studio layout preview?

  1. Go to File->Invalidate Caches/ Restart. After restarting the preview window will come.

  2. Still the preview window is not opened, Go to View -> Tool window -> click Preview

C# Creating and using Functions

You should either make your Add function static like so:

static public int Add(int x, int y)
{ 
    int result = x + y;
    return result;
 } //END   Add

static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.

or you should create in instance of your Program class, and then call Add on this instance. Like so:

Program prog = new Program();
prog.Add(5,10);

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

ImageView in circular through xml

The following is one of the simplest ways to do it, use the following code:

Dependencies

dependencies {
    ...
    compile 'de.hdodenhof:circleimageview:2.1.0'      // use this or use the latest compile version. In case u get bug.
}

XML Code

<de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="96dp"             //  here u can adjust the width 
    android:layout_height="96dp"            //  here u can adjust the height 
    android:src="@drawable/profile"         //  here u can change the image 
    app:civ_border_width="2dp"              //  here u can adjust the border of the circle.  
    app:civ_border_color="#FF000000"/>      //  here u can adjust the border color

Screenshot:

Screenshot

Source: Circular ImageView GitHub Repository

enter image description here

Get name of current class?

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

It is accessible from within the very definition of a class or a function, so for instance:

class Foo:
    print(__qualname__)

will effectively print Foo. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the . character.

However, there is no way to get an actual handle on the class being defined.

>>> class Foo:
...     print('Foo' in globals())
... 
False

Why do Twitter Bootstrap tables always have 100% width?

<table style="width: auto;" ... works fine. Tested in Chrome 38 , IE 11 and Firefox 34.

jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/

npm install Error: rollbackFailedOptional

I tried following options to fix this issue and it worked.

  1. Uninstall Node.js version 8.
  2. Install Node.js version 6.11.4
  3. Use the registry option along with command to install any package.

For example to install express I used following command.

npm install express --registry http://registry.npmjs.org/

or

npm install express -g --registry http://registry.npmjs.org/

If you want to install locally in any specific folder then use below command. Below command will install express on path C:\Sample\Example1 .

C:\Sample1\Example1> npm install /Sample/Example1 express --registry http://registry.npmjs.org/

Note: If you are installing locally in a specific location then first go to that directory using command and then run above command. If you are not inside that directory and giving only path in command that will not work.

If you get package.json missing error then run below command before installing package locally

C:\Sample\Example1> npm init

above command will create package.json file. No need to provide any data. just hit enter.

Note: If you are behind a firewall then you may need to set a proxy.

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

Download the Android SDK components for offline install

You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.

It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons, if you don't know where the files has to go.

Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's

Jquery in React is not defined

Try add jQuery to your project, like

npm i jquery --save

or if you use bower

bower i jquery --save

then

import $ from 'jquery'; 

Is there a difference between "throw" and "throw ex"?

int a = 0;
try {
    int x = 4;
    int y ;
    try {
        y = x / a;
    } catch (Exception e) {
        Console.WriteLine("inner ex");
        //throw;   // Line 1
        //throw e;   // Line 2
        //throw new Exception("devide by 0");  // Line 3
    }
} catch (Exception ex) {
    Console.WriteLine(ex);
    throw ex;
}
  1. if all Line 1 ,2 and 3 are commented - Output - inner ex

  2. if all Line 2 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

  3. if all Line 1 and 2 are commented - Output - inner ex System.Exception: devide by 0 ----

  4. if all Line 1 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

and StackTrace will be reset in case of throw ex;

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

ERROR 1148: The used command is not allowed with this MySQL version

I had the same issue while importing the CSV file in AWS MySQL 8.0 RDS.

mysql> LOAD DATA LOCAL INFILE '/tmp/your.csv' INTO TABLE test.demo2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;

ERROR 1148 (42000): The used command is not allowed with this MySQL version

1) Check for local_infile parameter

mysql> SHOW VARIABLES LIKE 'local_infile';

2) Log out from client and re-login using below parameter.

mysql -u root -p -h rdsendpoint --local-infile=1

3) Run the same command

mysql> LOAD DATA LOCAL INFILE '/tmp/your.csv' INTO TABLE test.demo2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;


Query OK, 300 rows affected (0.01 sec)

Records: 300  Deleted: 0  Skipped: 0  Warnings: 0

jQuery $(document).ready and UpdatePanels?

FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {... 

Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.

Cheers

How do I display todays date on SSRS report?

Just simple use

=Format(today(), "dd/MM/yyyy")

will solve your problem.

How can I label points in this scatterplot?

You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.

Javascript to display the current date and time

_x000D_
_x000D_
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Noon';
  } else {
    hour = 12;
    prepand = ' PM';
  }
}
if (hour === 0 && prepand === ' AM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Midnight';
  } else {
    hour = 12;
    prepand = ' AM';
  }
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
_x000D_
_x000D_

Java - ignore exception and continue

It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.

However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Laravel orderBy on a relationship

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

Run Java Code Online

Zamples is another site where you write a java code and run it online. Here you have possibility to choose jdk version also. http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl

Eclipse : Failed to connect to remote VM. Connection refused.

Which server are you using?

Like already said:

  1. In your debug configuration you'll have to define the right port of your server (GF:9009 / Tomcat:8000)
  2. You'll have to set the JVM property of the server to debug

For Glassfish:

    Log in to admin-console > Configurations > server-config > JVM-Settings > check DEBUG checkbox > restart server

For Tomcat:

create file debug.bat/.sh (depending on your OS) in %TOMCAT_HOME%/bin directory and write

    set JPDA_ADDRESS=8000
    set JPDA_TRANSPORT=dt_socket
    catalina.bat jpda start

in it.

After you've created this file start server by executing debug.bat/.sh.

Now you should be able to debug remotely in Eclipse after you set the necessary properties in your debug configuration.

Hope this helped! Have Fun!

EDIT

If you're running tomcat in a Win environment as a service you don't have a catalina.bat file in the bin-directory of your tomcat installation.
To set your server into debug-mode please try the following:

  1. Run the Configuration option in Windows Menu or run %catalina_home%/bin/tomcat6w.exe
  2. In Java tab, add this line to Java:

options:-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.

From one commenter:

... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.

Read more

The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.

For more information and updates, see this SO question. Here's the official issue.

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

Change visibility of ASP.NET label with JavaScript

Try this.

<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />

<script type="text/javascript">
    function ShowButton() {
        var buttonID = '<%= myButton.ClientID %>';
        var button = document.getElementById(buttonID);
        if(button) { button.style.display = 'inherit'; }
    }
</script>

Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.

The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.

Get current category ID of the active page

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

Is it safe to store a JWT in localStorage with ReactJS?

I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.

The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit evil.com and it manages to send a POST http://example.com/delete-my-account, it will not be able to send my authn token, so the request is ignored.

Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.

Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.

How do you log content of a JSON object in Node.js?

Try this one:

console.log("Session: %j", session);

If the object could be converted into JSON, that will work.

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

Random number between 0 and 1 in python

random.randrange(0,2) this works!

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

How to hide a column (GridView) but still access its value?

If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:

<asp:TemplateField HeaderText="OutlookID">
    <ItemTemplate>
        <asp:Label ID="blah" runat="server">Existing Control</asp:Label>
        <asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
    </ItemTemplate>
</asp:TemplateField>

Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:

string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;

Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.

Concatenating string and integer in python

Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.

s = "string"
i = 0

print (s + repr(i))

The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.

Hope this helps.

Caitlin

The difference between sys.stdout.write and print?

In Python 2, if you need to pass around a function, then you can assign os.sys.stdout.write to a variable. You cannot do this (in the REPL) with print.

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>

That works as expected.

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

That does not work. print is a magical function.

Python and pip, list all versions of a package that's available?

Here's my answer that sorts the list inside jq (for those who use systems where sort -V is not avalable) :

$ pythonPackage=certifi
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )'
  ............. 
  "2019.3.9",
  "2019.6.16",
  "2019.9.11",
  "2019.11.28",
  "2020.4.5",
  "2020.4.5.1",
  "2020.4.5.2",
  "2020.6.20",
  "2020.11.8"
]

And to fetch the last version number of the package :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )[-1]'
2020.11.8

or a bit faster :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | max_by( split(".") | map(tonumber) )'
2020.11.8

Or even more simple :) :

$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r .info.version
2020.11.8

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I'm using ASP.Net CORE 2.1 and I got this error when I ran by selecting a .csproj from a list of about 40 in a big repo. When I opened the csproj file individually, the error was resolved. Something with how the program was launched was different when the csproj was opened.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

I do think requests is the best option. Also note the possibility of setting encoding manually.

import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Simplified:

DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();

Jackson enum Serializing and DeSerializer

Note that as of this commit in June 2015 (Jackson 2.6.2 and above) you can now simply write:

public enum Event {
    @JsonProperty("forgot password")
    FORGOT_PASSWORD;
}

The behavior is documented here: https://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonProperty.html

Starting with Jackson 2.6 this annotation may also be used to change serialization of Enum like so:

 public enum MyEnum {
      @JsonProperty("theFirstValue") THE_FIRST_VALUE,
      @JsonProperty("another_value") ANOTHER_VALUE;
 }

as an alternative to using JsonValue annotation.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

How to correctly save instance state of Fragments in back stack?

This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.

public final class MyFragment extends Fragment {
    private TextView vstup;
    private Bundle savedState = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.whatever, null);
        vstup = (TextView)v.findViewById(R.id.whatever);

        /* (...) */

        /* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
        /* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle(App.STAV);
        }
        if(savedState != null) {
            vstup.setText(savedState.getCharSequence(App.VSTUP));
        }
        savedState = null;

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState(); /* vstup defined here for sure */
        vstup = null;
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence(App.VSTUP, vstup.getText());
        return state;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
        /* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
        /* => (?:) operator inevitable! */
        outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
    }

    /* (...) */

}

Alternatively, it is always a possibility to keep the data displayed in passive Views in variables and using the Views only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.

How to remove unique key from mysql table

There are two method two remove index in mysql. First method is GUI. In this method you have to open GUI interface of MYSQL and then go to that database and then go to that particular table in which you want to remove index.

After that click on the structure option, Then you can see table structure and below you can see table indexes. You can remove indexes by clicking on drop option

enter image description here

Second method by

ALTER TABLE student_login_credentials DROP INDEX created_at;

here student_login_credentials is table name and created_at is column name

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

What is the difference between "px", "dip", "dp" and "sp"?

sp: scale independent pixel

You should use it with texts because it is automatically scaled according to the font size that is being used by the user in his device.

px: pixel or picture element is the single point on the screen

Fatal error: Class 'PHPMailer' not found

Doesn't sound like all the files needed to use that class are present. I would start over:

  1. Download the package from https://github.com/PHPMailer/PHPMailer by clicking on the "Download ZIP" button on the far lower right of the page.
  2. extract the zip file
  3. upload the language folder, class.phpmailer.php, class.pop3.php, class.smtp.php, and PHPMailerAutoload.php all into the same directory on your server, I like to create a directory on the server called phpmailer to place all of these into.
  4. Include the class in your PHP project: require_once('phpmailer/PHPMailerAutoload.php');

How to close current tab in a browser window?

Try this

<a href="javascript:window.open('','_self').close();">close</a>