Programs & Examples On #Password storage

Password storage is often a tricky issue - where do you keep it so that it is well protected? This tag deals with problems relating to the management of user credentials in a system.

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1

How do I create and store md5 passwords in mysql

PHP has a method called md5 ;-) Just $password = md5($passToEncrypt);

If you are searching in a SQL u can use a MySQL Method MD5() too....

 SELECT * FROM user WHERE Password='. md5($password) .'

or SELECT * FROM ser WHERE Password=MD5('. $password .')

To insert it u can do it the same way.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

"Z" doesn't stand for "Zulu"

I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How to get the selected date value while using Bootstrap Datepicker?

I was able to find the moment.js object for the selected date with the following:

$('#datepicker').data('DateTimePicker').date()

More info about moment.js and how to format the date using the moment.js object

Java: Reading a file into an array

You should be able to use forward slashes in Java to refer to file locations.

The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.

Toolkit's use of BufferedReader is probably what you need.

How to get Tensorflow tensor dimensions (shape) as int values?

In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape to get the shape of the tensor.

tensor_shape = tensor.shape
print(tensor_shape)

How to avoid Python/Pandas creating an index in a saved csv?

Use index=False.

df.to_csv('your.csv', index=False)

SQL grouping by all the columns

He is trying find and display the duplicate rows in a table.

SELECT *, COUNT(*) AS NoOfOccurrences
FROM TableName GROUP BY *
HAVING COUNT(*) > 1

Do we have a simple way to accomplish this?

maximum value of int

#include <climits>
#include <iostream>
using namespace std;

int main() {
  cout << INT_MAX << endl;
}

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

How do I view the SQL generated by the Entity Framework?

To have the query always handy, without changing code add this to your DbContext and check it on the output window in visual studio.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.Log = (query)=> Debug.Write(query);
    }

Similar to @Matt Nibecker answer, but with this you do not have to add it in your current code, every time you need the query.

jQuery: Test if checkbox is NOT checked

if($("#checkbox1").prop('checked') == false){
    alert('checkbox is not checked');
    //do something
}
else
{ 
    alert('checkbox is checked');
}

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

cartesian product in pandas

Minimal code needed for this one. Create a common 'key' to cartesian merge the two:

df1['key'] = 0
df2['key'] = 0

df_cartesian = df1.merge(df2, how='outer')

Regular expressions inside SQL Server

You can write queries like this in SQL Server:

--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'

How to solve a timeout error in Laravel 5

it's a pure PHP setting. The alternative is to increase the execution time limit only for specific php scripts, by inserting on top of that php file, the following:

ini_set('max_execution_time', 180); //3 minutes

How to print to console in pytest?

Short Answer

Use the -s option:

pytest -s

Detailed answer

From the docs:

During test execution any output sent to stdout and stderr is captured. If a test or a setup method fails its according captured output will usually be shown along with the failure traceback.

pytest has the option --capture=method in which method is per-test capturing method, and could be one of the following: fd, sys or no. pytest also has the option -s which is a shortcut for --capture=no, and this is the option that will allow you to see your print statements in the console.

pytest --capture=no     # show print statements in console
pytest -s               # equivalent to previous command

Setting capturing methods or disabling capturing

There are two ways in which pytest can perform capturing:

  1. file descriptor (FD) level capturing (default): All writes going to the operating system file descriptors 1 and 2 will be captured.

  2. sys level capturing: Only writes to Python files sys.stdout and sys.stderr will be captured. No capturing of writes to filedescriptors is performed.

pytest -s            # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd  # also point filedescriptors 1 and 2 to temp file

How to split a data frame?

subset() is also useful:

subset(DATAFRAME, COLUMNNAME == "")

For a survey package, maybe the survey package is pertinent?

http://faculty.washington.edu/tlumley/survey/

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How to remove all the null elements inside a generic list in one go?

I do not know of any in-built method, but you could just use linq:

parameterList = parameterList.Where(x => x != null).ToList();

Correct use of flush() in JPA/Hibernate

Can em.flush() cause any harm when using it within a transaction?

Yes, it may hold locks in the database for a longer duration than necessary.

Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.

Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Here is a comparison with np.einsum to show how the indices are projected

np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b)        # True 
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b)        # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b))   # True

error: expected class-name before ‘{’ token

I know it is a bit late to answer this question, but it is the first entry in google, so I think it is worth to answer it.

The problem is not a coding problem, it is an architecture problem.

You have created an interface class Event: public Item to define the methods which all events should implement. Then you have defined two types of events which inherits from class Event: public Item; Arrival and Landing and then, you have added a method Landing* createNewLanding(Arrival* arrival); from the landing functionality in the class Event: public Item interface. You should move this method to the class Landing: public Event class because it only has sense for a landing. class Landing: public Event and class Arrival: public Event class should know class Event: public Item but event should not know class Landing: public Event nor class Arrival: public Event.

I hope this helps, regards, Alberto

Build not visible in itunes connect

To update @cdescours' answer, uploaded builds can now be seen in the "Activity" tab in "Processing" state.

pop/remove items out of a python tuple

ok I figured out a crude way of doing it.

I store the "n" value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

Any other suggestions are welcome too.

What do the icons in Eclipse mean?

I can't find a way to create a table with icons in SO, so I am uploading 2 images. Objects Icons

Decorator icons

Accessing the last entry in a Map

When using numbers as the key, I suppose you could also try this:

        Map<Long, String> map = new HashMap<>();
        map.put(4L, "The First");
        map.put(6L, "The Second");
        map.put(11L, "The Last");

        long lastKey = 0;
        //you entered Map<Long, String> entry
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            lastKey = entry.getKey();
        }
        System.out.println(lastKey); // 11

How do I disable Git Credential Manager for Windows?

you can just delete the Credential Manager.

C:\Users\<USER>\AppData\Local\Programs\Git\mingw64\libexec\git-core

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Known bug with Xcode 11.2 can cause this issue. Xcode 11.2 has been deprecated.

Downloading Xcode 11.2.1 solved the issue.

Apple 11.2 Bug Forum

I also updated real device to current iOS, but i don't think that was the issue.

Unable to compile simple Java 10 / Java 11 project with Maven

Alright so for me nothing worked.
I was using spring boot with hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected.

You still need to add the above plugin tough
Hope it helps!

How to send string from one activity to another?

You can send data from one actvity to another with an Intent

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

Then all you have to do is call setText on your TextView and use that string.

Why do people write #!/usr/bin/env python on the first line of a Python script?

Expanding a bit on the other answers, here's a little example of how your command line scripts can get into trouble by incautious use of /usr/bin/env shebang lines:

$ /usr/local/bin/python -V
Python 2.6.4
$ /usr/bin/python -V
Python 2.5.1
$ cat my_script.py 
#!/usr/bin/env python
import json
print "hello, json"
$ PATH=/usr/local/bin:/usr/bin
$ ./my_script.py 
hello, json
$ PATH=/usr/bin:/usr/local/bin
$ ./my_script.py 
Traceback (most recent call last):
  File "./my_script.py", line 2, in <module>
    import json
ImportError: No module named json

The json module doesn't exist in Python 2.5.

One way to guard against that kind of problem is to use the versioned python command names that are typically installed with most Pythons:

$ cat my_script.py 
#!/usr/bin/env python2.6
import json
print "hello, json"

If you just need to distinguish between Python 2.x and Python 3.x, recent releases of Python 3 also provide a python3 name:

$ cat my_script.py 
#!/usr/bin/env python3
import json
print("hello, json")

Warning - Build path specifies execution environment J2SE-1.4

If you have Java 1.8 then

You need this xml part in pom.xml and update project.

 <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

Is it possible to use JS to open an HTML select to show its option list?

The solution I present is safe, simple and compatible with Internet Explorer, FireFox and Chrome.

This approach is new and complete. I not found nothing equal to that solution on the internet. Is simple, cross-browser (Internet Explorer, Chrome and Firefox), preserves the layout, use the select itself and is easy to use.

Note: JQuery is required.

HTML CODE

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CustonSelect</title>
<script type="text/javascript" src="./jquery-1.3.2.js"></script>
<script type="text/javascript" src="./CustomSelect.js"></script>
</head>
<div id="testDiv"></div>
<body>
    <table>
        <tr>
            <td>
                <select id="Select0" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select1" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select2" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select3" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select4" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
    </table>
    <input type="button" id="Button0" value="MoveLayout!"/>
</body>
</html>

JAVASCRIPT CODE

var customSelectFields = new Array();


// Note: The list of selects to be modified! By Questor
customSelectFields[0] = "Select0";
customSelectFields[1] = "Select1";
customSelectFields[2] = "Select2";
customSelectFields[3] = "Select3";
customSelectFields[4] = "Select4";

$(document).ready(function()
{


    //Note: To debug! By Questor
    $("#Button0").click(function(event){ AddTestDiv(); });

    StartUpCustomSelect(null);  

});


//Note: To test! By Questor
function AddTestDiv()
{
    $("#testDiv").append("<div style=\"width:100px;height:100px;\"></div>");
}


//Note: Startup selects customization scheme! By Questor
function StartUpCustomSelect(what)
{

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

        $("#" + customSelectFields[i] + "").click(function(event){ UpCustomSelect(this); });
        $("#" + customSelectFields[i] + "").wrap("<div id=\"selectDiv_" + customSelectFields[i] + "\" onmouseover=\"BlockCustomSelectAgain();\" status=\"CLOSED\"></div>").parent().after("<div id=\"coverSelectDiv_" + customSelectFields[i] + "\" onclick=\"UpOrDownCustomSelect(this);\" onmouseover=\"BlockCustomSelectAgain();\"></div>");


        //Note: Avoid breaking the layout when the CSS is modified from "position" to "absolute" on the select! By Questor
        $("#" + customSelectFields[i] + "").parent().css({'width': $("#" + customSelectFields[i] + "")[0].offsetWidth + 'px', 'height': $("#" + customSelectFields[i] + "")[0].offsetHeight + 'px'});

        BlockCustomSelect($("#" + customSelectFields[i] + ""));

    }
}


//Note: Repositions the div that covers the select using the "onmouseover" event so 
//Note: if element on the screen move the div always stand over it (recalculate! By Questor
function BlockCustomSelectAgain(what)
{
    for (i = 0; i < customSelectFields.length; i++)
    {
        if($("#" + customSelectFields[i] + "").parent().attr("status") == "CLOSED")
        {
            BlockCustomSelect($("#" + customSelectFields[i] + ""));
        }
    }
}


//Note: Does not allow the select to be clicked or clickable! By Questor
function BlockCustomSelect(what)
{

    var coverSelectDiv = $(what).parent().next();


    //Note: Ensures the integrity of the div style! By Questor
    $(coverSelectDiv).removeAttr('style');


    //Note: To resolve compatibility issues! By Questor
    var backgroundValue = "";
    var filerValue = "";
    if(navigator.appName == "Microsoft Internet Explorer")
    {
        backgroundValue = 'url(fakeimage)';
        filerValue = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=\'scale\', src=\'fakeimage\' )';
    }


    //Note: To debug! By Questor
    //'border': '5px #000 solid',

    $(coverSelectDiv).css({
        'position': 'absolute', 
        'top': $(what).offset().top + 'px', 
        'left': $(what).offset().left + 'px', 
        'width': $(what)[0].offsetWidth + 'px', 
        'height': $(what)[0].offsetHeight + 'px', 
        'background': backgroundValue,
        '-moz-background-size':'cover',
        '-webkit-background-size':'cover',
        'background-size':'cover',
        'filer': filerValue
    });

}


//Note: Allow the select to be clicked or clickable! By Questor
function ReleaseCustomSelect(what)
{

    var coverSelectDiv = $(what).parent().next();

    $(coverSelectDiv).removeAttr('style');
    $(coverSelectDiv).css({'display': 'none'});

}


//Note: Open the select! By Questor
function DownCustomSelect(what)
{


    //Note: Avoid breaking the layout. Avoid that select events be overwritten by the others! By Questor
    $(what).css({
        'position': 'absolute', 
        'z-index': '100'
    });


    //Note: Open dropdown! By Questor
    $(what).attr("size","10");

    ReleaseCustomSelect(what);


    //Note: Avoids the side-effect of the select loses focus.! By Questor
    $(what).focus();


    //Note: Allows you to select elements using the enter key when the select is on focus! By Questor
    $(what).keyup(function(e){
        if(e.keyCode == 13)
        {
            UpCustomSelect(what);
        }
    });


    //Note: Closes the select when loses focus! By Questor
    $(what).blur(function(e){
        UpCustomSelect(what);
    });

    $(what).parent().attr("status", "OPENED");

}


//Note: Close the select! By Questor
function UpCustomSelect(what)
{

    $(what).css("position","static");


    //Note: Close dropdown! By Questor
    $(what).attr("size","1");

    BlockCustomSelect(what);

    $(what).parent().attr("status", "CLOSED");

}


//Note: Closes or opens the select depending on the current status! By Questor
function UpOrDownCustomSelect(what)
{

    var customizedSelect = $($(what).prev().children()[0]);

    if($(what).prev().attr("status") == "CLOSED")
    {
        DownCustomSelect(customizedSelect);
    }
    else if($(what).prev().attr("status") == "OPENED")
    {
        UpCustomSelect(customizedSelect);
    }

}

Spring RequestMapping for controllers that produce and consume JSON

The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.

@RequestMapping is supported at both the type level and at the method level.

When you put @RequestMapping at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping to a type. I've summarized this for each attribute below:

  • name: Value at Type level is concatenated with value at method level using '#' as a separator.
  • value: Value at Type level is inherited by method.
  • path: Value at Type level is inherited by method.
  • method: Value at Type level is inherited by method.
  • params: Value at Type level is inherited by method.
  • headers: Value at Type level is inherited by method.
  • consumes: Value at Type level is overridden by method.
  • produces: Value at Type level is overridden by method.

Here is a brief example Controller that showcases how you could use this:

package com.example;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path = "/", 
        consumes = MediaType.APPLICATION_JSON_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE, 
        method = {RequestMethod.GET, RequestMethod.POST})
public class JsonProducingEndpoint {

    private FooService fooService;

    @RequestMapping(path = "/foo", method = RequestMethod.POST)
    public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
        fooService.saveTheFoo(theFoo);
        return "http://myservice.com/foo/1";
    }

    @RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
    public ThisIsAFoo getAFoo(@PathVariable String id) {
        ThisIsAFoo foo = fooService.getAFoo(id);
        return foo;
    }

    @RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
    public ThisIsAFooXML getAFooXml(@PathVariable String id) {
        ThisIsAFooXML foo = fooService.getAFoo(id);
        return foo;
    }
}

What is the best open source help ticket system?

TRAC. Open source, Python-based

Position Relative vs Absolute?

Putting an answer , as my reputation aint enough to comment. But dont look at this as an answer, just a additional info, as myself, had some problems with both footer, and positioning.

When setting up the page, so that my footer always stays at the bottom, with position absolute, and main container/wrapper with relative position.

I then found some issues with my text content, and a menu inside the same content(white part of page between header and footer), when setting these to absolute, footer no longer stays down.

Postitioning is, as you say a complex theme.

My solution, to the content I wanted in 'absolute' positon in my webpage, and not be pushed to the side, when in example opening a drop down menu, was to actually give it postition relative, and putting it 35em below my drop down menu. (35em is the heigth of my dropdown menu, when fully extended)

Then, Top:-35em, for the content that before was pushed to the side. And then adding margin-bottom:-35em. This way, the content is "below" my drop down menu, but visually it is side by side with my drop down menu! And the white space below down to the footer, is with only 10em margin, as it was before starting to play around with this. So my solution to this was like this :

 html, body {
    margin:0;
    padding:0;
    height:100%;

}
h1 {
    margin:0;
}
    #webpage {
    position:relative;
    min-height:100%;
    margin:0;
    overflow:auto;
}
     #header {
    height:5em;
    width:100%;
    padding:0;
    margin:0;
}
     #text {
    position:relative;
   margin-bottom:-32em;
    padding-top:2em;
    padding-right:2em;
    padding-bottom:10em;
    background-repeat:no-repeat;
    width:70%;
    padding-left:auto;
    margin-left:auto;
    margin-right:auto;
    right:10em;
    float:right;
    top:-32em;
      }
#dropdown {

position:absolute;
    left:0;
    width:20%;
    clear:both;
    display:block;
    position:relative;
    top:1em;
    height:35em;

}
    #footer {
    position:absolute;
    width:100%;
    right:0;
    bottom:0;
    height:5em;
    margin:0;
     margin-top:5em;
}

I see your question is answered good, but after alot of troubleing I found this to be a very good solution, and a way to understand better how positioning works.. When I place my text content, below my drop down menu, it doesn't push my text to the side. If I changed the text to position absolute, the footer did not stay in place. As I can believe this is an issue for more people then me, I add this here. What in fact happends, is I put the text, 35ems, below my drop down.

Then, I visually put it right next to eachother, with relative position, and top:-35em;, and evening out the huge space below, with margin:-35em;

negative values are underestimated at times, very good functionality, when one understands these positions better!

Natually, fixed position, also seemed logic for my footer, but I do really want the footer to go below the viewport, if the text, or content, is longer than the viewport. And to stay at the bottom, if there is little content on the page.

This setupp fixed that very nicely, and remember to use 'em', not 'px' for a more fluid/dynamic page layout! :)

(there may be better solutions, but this works for me cross platforms, as well as devices).

Operation is not valid due to the current state of the object, when I select a dropdown list

From http://codecorner.galanter.net/2012/06/04/solution-for-operation-is-not-valid-due-to-the-current-state-of-the-object-error/

Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.

This can be done in your application Web.Config in the <appSettings> section (create the section directly under <configuration> if it doesn’t exist). Add 2 lines similar to the lines below to the section:

<add key="aspnet:MaxHttpCollectionKeys" value="2000" />
<add key="aspnet:MaxJsonDeserializerMembers" value="2000" />

The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.

Node.js: How to send headers with form data using request module?

I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.

You should add method: 'POST' and your code will work if your backend receive the post method.

var req = require('request');

req.post({
   url: 'someUrl',
   form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
   headers: { 
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
      'Content-Type' : 'application/x-www-form-urlencoded' 
   },
   method: 'POST'
  },

  function (e, r, body) {
      console.log(body);
  });

IOException: Too many open files

The problem comes from your Java application (or a library you are using).

First, you should read the entire outputs (Google for StreamGobbler), and pronto!

Javadoc says:

The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Secondly, waitFor() your process to terminate. You then should close the input, output and error streams.

Finally destroy() your Process.

My sources:

'tuple' object does not support item assignment

A tuple is immutable and thus you get the error you posted.

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

In your specific case, as correctly pointed out in other answers, you should write:

pixel = (pixel[0] + 20, pixel[1], pixel[2])

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

Select multiple value in DropDownList using ASP.NET and C#

In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

<asp:ListBox runat="server" SelectionMode="Multiple" >
  <asp:ListItem Text="test1"></asp:ListItem>
  <asp:ListItem Text="test2"></asp:ListItem>
  <asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>

ImageView rounded corners

I use extend ImageView:

public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);
         } else {
            throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
        }
        clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}

Two Radio Buttons ASP.NET C#

Set the GroupName property of both radio buttons to the same value. You could also try using a RadioButtonGroup, which does this for you automatically.

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

How do you synchronise projects to GitHub with Android Studio?

Github with android studio

/*For New - Run these command in terminal*/
echo "# Your Repository" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/username/repository.git
git push -u origin master

/*For Exist - Run these command in terminal*/
git remote add origin https://github.com/username/repository.git
git push -u origin master
//git push -f origin master
//git push origin master --force

/*For Update - Run these command in terminal*/
git add .
git commit -m "your message"
git push

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

ECLIPSE PHOTON ON MAC

  1. Get your current JAVA_HOME path /Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home

  2. open /Users/you/eclipse/jee-photon/Eclipse.app/Contents/Eclipse/ and click on package content. Then open eclipse.ini file using any text file editor.

  3. Edit your -VM argument as below( Make sure the Java Path is same as $JAVA_HOME)

-vm

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/bin

  1. save and start your eclipse.

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

How to open a file / browse dialog using javascript?

I know this is an old post, but another simple option is using the INPUT TYPE="FILE" tag according to compatibility most major browser support this feature.

What is the best way to dump entire objects to a log in C#?

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...

jQuery: how do I animate a div rotation?

Make use of WebkitTransform / -moz-transform: rotate(Xdeg). This will not work in IE, but Matt's zachstronaut solution doesn't work in IE either.

If you want to support IE too, you'll have to look into using a canvas like I believe Raphael does.

Here is a simple jQuery snippet that rotates the elements in a jQuery object. Rotation can be started and stopped:

_x000D_
_x000D_
$(function() {_x000D_
    var $elie = $("img"), degree = 0, timer;_x000D_
    rotate();_x000D_
    function rotate() {_x000D_
        _x000D_
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  _x000D_
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});                      _x000D_
        timer = setTimeout(function() {_x000D_
            ++degree; rotate();_x000D_
        },5);_x000D_
    }_x000D_
    _x000D_
    $("input").toggle(function() {_x000D_
        clearTimeout(timer);_x000D_
    }, function() {_x000D_
        rotate();_x000D_
    });_x000D_
}); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<input type="button" value=" Toggle Spin " />_x000D_
<br/><br/><br/><br/>_x000D_
<img src="http://i.imgur.com/ABktns.jpg" />
_x000D_
_x000D_
_x000D_

Split string using a newline delimiter with Python

Here you go:

>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split()  # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>> 

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

const mongoose = require('mongoose');

mongoose
  .connect(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log("connected to db");
  });

try to use this

Detecting a mobile browser

How about:

if (typeof window.orientation !== 'undefined') { ... }

...since smartphones usually support this property and desktop browsers don't.

EDIT: As @Gajus pointed out, this solution is now deprecated and shouldn't be used (https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation)

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

JavaScript and Threads

There's no true threading in JavaScript. JavaScript being the malleable language that it is, does allow you to emulate some of it. Here is an example I came across the other day.

How to unzip gz file using Python

It is very simple.. Here you go !!

import gzip

#path_to_file_to_be_extracted

ip = sample.gzip

#output file to be filled

op = open("output_file","w") 

with gzip.open(ip,"rb") as ip_byte:
    op.write(ip_byte.read().decode("utf-8")
    wf.close()

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

How to set menu to Toolbar in Android

In XML add one line inside <Toolbar/>

<com.google.android.material.appbar.MaterialToolbar
app:menu="@menu/main_menu"/>

In java file, replace this:

 setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("Main Page");
        }

with this:

toolbar.setTitle("Main Page")

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

Closure in Java 7

A closure implementation for Java 5, 6, and 7

http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html

It contains all one could ask for...

How to use Class<T> in Java?

I have found class<T> useful when I create service registry lookups. E.g.

<T> T getService(Class<T> serviceClass)
{
    ...
}

.substring error: "is not a function"

You can use substr

for example:

new Date().getFullYear().toString().substr(-2)

How to get jSON response into variable from a jquery script

Here's the script, rewritten to use the suggestions above and a change to your no-cache method.

<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>

//the script above returns this:
{"response":"error","comment":"test comment here"}

<script type="text/javascript">
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    dataType: "json",
    success: function (data) {
        if (data.response == 'captcha') {
            alert('captcha');
        } else if (data.response == 'success') {
            alert('success');
        } else {
            alert('sorry there was an error');
        }
    }

}); // Semi-colons after all declarations, IE is picky on these things.
</script>

The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log the value of data and make sure the property you are looking for is there.

Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.

What is the most effective way to get the index of an iterator of an std::vector?

Beside int float string etc., you can put extra data to .second when using diff. types like:

std::map<unsigned long long int, glm::ivec2> voxels_corners;
std::map<unsigned long long int, glm::ivec2>::iterator it_corners;

or

struct voxel_map {
    int x,i;
};

std::map<unsigned long long int, voxel_map> voxels_corners;
std::map<unsigned long long int, voxel_map>::iterator it_corners;

when

long long unsigned int index_first=some_key; // llu in this case...
int i=0;
voxels_corners.insert(std::make_pair(index_first,glm::ivec2(1,i++)));

or

long long unsigned int index_first=some_key;
int index_counter=0;
voxel_map one;
one.x=1;
one.i=index_counter++;

voxels_corners.insert(std::make_pair(index_first,one));

with right type || structure you can put anything in the .second including a index number that is incremented when doing an insert.

instead of

it_corners - _corners.begin()

or

std::distance(it_corners.begin(), it_corners)

after

it_corners = voxels_corners.find(index_first+bdif_x+x_z);

the index is simply:

int vertice_index = it_corners->second.y;

when using the glm::ivec2 type

or

int vertice_index = it_corners->second.i;

in case of the structure data type

Task continuation on UI thread

With async you just do:

await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);

However:

await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Extending loading Timeout Limit will not solve the problem which caused the error, it just will avoid the system to show the message but performance will be affected whatsoever.

Actual reason: You may be linking files or images to remote locations, and those resources are taking too long to load. (this is likely the most common error)

Definitive solution: move all the scripts, images and css needed to some local folders and load them locally ...

Performance will be increased and error will be effectively solved.

Running Selenium WebDriver python bindings in chrome

For Windows' IDE:

If your path doesn't work, you can try to add the chromedriver.exe to your project, like in this project structure.

chromedriver.exe

Then you should load the chromedriver.exe in your main file. As for me, I loaded the driver.exe in driver.py.

def get_chrome_driver():
return webdriver.Chrome("..\\content\\engine\\chromedriver.exe",
                            chrome_options='--no-startup-window')

.. means driver.py's upper directory

. means the directory where the driver.py is located

Hope this will be helpful.

How to group by week in MySQL?

The accepted answer above did not work for me, because it ordered the weeks by alphabetical order, not chronological order:

2012/1
2012/10
2012/11
...
2012/19
2012/2

Here's my solution to count and group by week:

SELECT CONCAT(YEAR(date), '/', WEEK(date)) AS week_name, 
       YEAR(date), WEEK(date), COUNT(*)
FROM column_name
GROUP BY week_name
ORDER BY YEAR(DATE) ASC, WEEK(date) ASC

Generates:

YEAR/WEEK   YEAR   WEEK   COUNT
2011/51     2011    51      15
2011/52     2011    52      14
2012/1      2012    1       20
2012/2      2012    2       14
2012/3      2012    3       19
2012/4      2012    4       19

String MinLength and MaxLength validation don't work (asp.net mvc)

    [StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
    [Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
    public string Password { get; set; }

Save resource like this

"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

In bash, how to store a return value in a variable?

The answer above suggests changing the function to echo data rather than return it so that it can be captured.

For a function or program that you can't modify where the return value needs to be saved to a variable (like test/[, which returns a 0/1 success value), echo $? within the command substitution:

# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"

# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"

E.g.

$ echo $REMOTE_ADDR

$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0

For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:

# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []

# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0

One line if statement not working

From what I know

3 one-liners

  1. a = 10 if <condition>

example:

a = 10 if true # a = 10
b = 10 if false # b = nil
  1. a = 10 unless <condition>

example:

a = 10 unless false # a = 10
b = 10 unless true # b = nil
  1. a = <condition> ? <a> : <b>

example:

a = true ? 10 : 100 # a = 10
a = false ? 10 : 100 # a = 100

I hope it helps.

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

This worked for me. may help some one. Turn off firewall. on RHEL 7

systemctl stop  firewalld

How to set background color in jquery

$(this).css('background-color', 'red');

Where are the recorded macros stored in Notepad++?

Go to %appdata%\Notepad++ folder.

The macro definitions are held in shortcuts.xml inside the <Macros> tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

Spring MVC Multipart Request with JSON

We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.

Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.

public Class UserDTO {
    private String firstName;
    private String lastName;
    private FileDTO profilePic; 
}

public class FileDTO {
    private String base64;
    // just base64 string is enough. If you want, send additional details
    private String name;
    private String type;
    private String lastModified;
}

@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
    byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
    ....
}

JS code to convert file to base64 string:

var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {

  const userDTO = {
    firstName: "John",
    lastName: "Wick",
    profilePic: {
      base64: reader.result,
      name: file.name,
      lastModified: file.lastModified,
      type: file.type
    }
  }
  
  // post userDTO
};
reader.onerror = function (error) {
  console.log('Error: ', error);
};

jQuery .search() to any string

search() is a String method.

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

Example:

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

The ternary (conditional) operator in C

The ternary operator is a syntactic and readability convenience, not a performance shortcut. People are split on the merits of it for conditionals of varying complexity, but for short conditions, it can be useful to have a one-line expression.

Moreover, since it's an expression, as Charlie Martin wrote, that means it can appear on the right-hand side of a statement in C. This is valuable for being concise.

What characters are allowed in an email address?

A good read on the matter.

Excerpt:

These are all valid email addresses!

"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/[email protected]
\[email protected]
!def!xyz%[email protected]
[email protected]

Why isn't my Pandas 'apply' function referencing multiple columns working?

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.

How to concatenate two numbers in javascript?

Use "" + 5 + 6 to force it to strings. This works with numerical variables too:

_x000D_
_x000D_
var a = 5;_x000D_
var b = 6;_x000D_
console.log("" + a + b);
_x000D_
_x000D_
_x000D_

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

In my.cnf file check below 2 steps.

  • check this value -

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure

    [mysqld] section should be like this.

How to tell if a connection is dead in python

If I'm not mistaken this is usually handled via a timeout.

How to type a new line character in SQL Server Management Studio

If you are trying to enter data directly into the table in grid view (presumably Right Click TableName and Select Open Table), then you can enter your unicode text string and wherever you want a carriage return just type 13 with the alt key pressed in the numeric keypad.

That would be Alt+13. This works only from the numeric keypad and does not work with the number keys on the top of the keyboard. The carriage return will be stored as a square

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Disable form autofill in Chrome without disabling autocomplete

autocomplete="off" on the input now working on Chrome V44 (and Canary V47)

How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

Auto-loading lib files in Rails 4

I think this may solve your problem:

  1. in config/application.rb:

    config.autoload_paths << Rails.root.join('lib')
    

    and keep the right naming convention in lib.

    in lib/foo.rb:

    class Foo
    end
    

    in lib/foo/bar.rb:

    class Foo::Bar
    end
    
  2. if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:

    in config/initializers/require.rb:

    require "#{Rails.root}/lib/extensions" 
    

P.S.

What is the iBeacon Bluetooth Profile

It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/

How to compare 2 dataTables

If you have the tables in a database, you can make a full outer join to get the differences. Example:

select t1.Field1, t1.Field2, t2.Field1, t2.Field2
from Table1 t1
full outer join Table2 t2 on t1.Field1 = t2.Field1 and t1.Field2 = t2.Field2
where t1.Field1 is null or t2.Field2 is null

All records that are identical are filtered out. There is data either in the first two or the last two fields, depending on what table the record comes from.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

Best way to encode text data for XML

This might be the case where you could benefit from using the WriteCData method.

public override void WriteCData(string text)
    Member of System.Xml.XmlTextWriter

Summary:
Writes out a <![CDATA[...]]> block containing the specified text.

Parameters:
text: Text to place inside the CDATA block.

A simple example would look like the following:

writer.WriteStartElement("name");
writer.WriteCData("<unsafe characters>");
writer.WriteFullEndElement();

The result looks like:

<name><![CDATA[<unsafe characters>]]></name>

When reading the node values the XMLReader automatically strips out the CData part of the innertext so you don't have to worry about it. The only catch is that you have to store the data as an innerText value to an XML node. In other words, you can't insert CData content into an attribute value.

How can I give the Intellij compiler more heap space?

I like to share a revelation that I had. When you build a project, Intellij Idea runs a java process that resides in its core(ex: C:\Program Files\JetBrains\IntelliJ IDEA 2020.3\jbr\bin). The "build process heap size", as mentioned by many others, changes the heap size of this java process. However, the main java process is triggered later by the Idea's java process, hence have different VM arguments. I noticed that the max heap size of this process is 1/3 of the Idea's java process, while min heap is the half of max(1/6). To round up:

When you set 9g heap on "build process heap size" the actual heap size for the compiler is max 3g and min 1,5g. And no need for restart is neccessary.

PS: tested on version 2020.3

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

<select name="country" formControlName="country" id="country" 
       class="formcontrol form-control-element" [(ngModel)]="country">
   <option value="90">Turkey</option>
   <option value="1">USA</option>
   <option value="30">Greece</option>
</select>
name="country"
formControlName="country" 
[(ngModel)]="country" 

Those are the three things need to use ngModel inside a formGroup directive.

Note that same name should be used.

Set and Get Methods in java?

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}

Issue pushing new code in Github

A simpler answer is to manually upload the README.MD file from your computer to GitHub. Worked very well for me.

Calling a class method raises a TypeError in Python

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

How to execute an .SQL script file using c#

There are two points to considerate.

1) This source code worked for me:

private static string Execute(string credentials, string scriptDir, string scriptFilename)
{ 
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.WorkingDirectory = scriptDir;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.FileName = "sqlplus";
  process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
  process.StartInfo.CreateNoWindow = true;

  process.Start();
  string output = process.StandardOutput.ReadToEnd();
  process.WaitForExit();

  return output;
}

I set the working directory to the script directory, so that sub scripts within the script also work.

Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

2) You have to finalize your SQL script with the statement EXIT;

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

How to declare a global variable in C++

I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.

According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.


Possibility 1

Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:

a.cpp

int x = 5; // declaration and definition of my global variable

b.cpp

// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)

void foo() {
   cout << x;  // OK
}

Typically you'd place extern int x; in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x.


Possibility 2

Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const ([C++11: 3.5/3]):

a.cpp

const int x = 5; // file-`static` by default, because `const`

b.cpp

extern const int x;    // says there's a `x` that we can use somewhere...

void foo() {
   cout << x;    // ... but actually there isn't. So, linker error.
}

You could fix this by applying extern to the definition, too:

a.cpp

extern const int x = 5;

This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

Refresh (reload) a page once using jQuery?

To reload, you can try this:

window.location.reload(true);

Remove large .pack file created by git

I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/

jQuery and TinyMCE: textarea value doesn't submit

I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:

$("textarea[id='id_answer']").change(function(){
    var editor_id = $(this).attr('id');
    var editor = tinymce.get(editor_id);
    editor.setContent($(this).val()).save();
});

It works for me.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

$(".answer").hide();
$(".coupon_question").click(function() {
    if($(this).is(":checked")) {
        $(".answer").show(300);
    } else {
        $(".answer").hide(200);
    }
});

FIDDLE

What's the difference between passing by reference vs. passing by value?

First and foremost, the "pass by value vs. pass by reference" distinction as defined in the CS theory is now obsolete because the technique originally defined as "pass by reference" has since fallen out of favor and is seldom used now.1

Newer languages2 tend to use a different (but similar) pair of techniques to achieve the same effects (see below) which is the primary source of confusion.

A secondary source of confusion is the fact that in "pass by reference", "reference" has a narrower meaning than the general term "reference" (because the phrase predates it).


Now, the authentic definition is:

  • When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.

  • When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.

Things to note in this definition are:

  • "Variable" here means the caller's (local or global) variable itself -- i.e. if I pass a local variable by reference and assign to it, I'll change the caller's variable itself, not e.g. whatever it is pointing to if it's a pointer.

    • This is now considered bad practice (as an implicit dependency). As such, virtually all newer languages are exclusively, or almost exclusively pass-by-value. Pass-by-reference is now chiefly used in the form of "output/inout arguments" in languages where a function cannot return more than one value.
  • The meaning of "reference" in "pass by reference". The difference with the general "reference" term is that this "reference" is temporary and implicit. What the callee basically gets is a "variable" that is somehow "the same" as the original one. How specifically this effect is achieved is irrelevant (e.g. the language may also expose some implementation details -- addresses, pointers, dereferencing -- this is all irrelevant; if the net effect is this, it's pass-by-reference).


Now, in modern languages, variables tend to be of "reference types" (another concept invented later than "pass by reference" and inspired by it), i.e. the actual object data is stored separately somewhere (usually, on the heap), and only "references" to it are ever held in variables and passed as parameters.3

Passing such a reference falls under pass-by-value because a variable's value is technically the reference itself, not the referred object. However, the net effect on the program can be the same as either pass-by-value or pass-by-reference:

  • If a reference is just taken from a caller's variable and passed as an argument, this has the same effect as pass-by-reference: if the referred object is mutated in the callee, the caller will see the change.
    • However, if a variable holding this reference is reassigned, it will stop pointing to that object, so any further operations on this variable will instead affect whatever it is pointing to now.
  • To have the same effect as pass-by-value, a copy of the object is made at some point. Options include:
    • The caller can just make a private copy before the call and give the callee a reference to that instead.
    • In some languages, some object types are "immutable": any operation on them that seems to alter the value actually creates a completely new object without affecting the original one. So, passing an object of such a type as an argument always has the effect of pass-by-value: a copy for the callee will be made automatically if and when it needs a change, and the caller's object will never be affected.
      • In functional languages, all objects are immutable.

As you may see, this pair of techniques is almost the same as those in the definition, only with a level of indirection: just replace "variable" with "referenced object".

There's no agreed-upon name for them, which leads to contorted explanations like "call by value where the value is a reference". In 1975, Barbara Liskov suggested the term "call-by-object-sharing" (or sometimes just "call-by-sharing") though it never quite caught on. Moreover, neither of these phrases draws a parallel with the original pair. No wonder the old terms ended up being reused in the absence of anything better, leading to confusion.4


NOTE: For a long time, this answer used to say:

Say I want to share a web page with you. If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.

If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.

This is mostly correct except the narrower meaning of "reference" -- it being both temporary and implicit (it doesn't have to, but being explicit and/or persistent are additional features, not a part of the pass-by-reference semantic, as explained above). A closer analogy would be giving you a copy of a document vs inviting you to work on the original.


1Unless you are programming in Fortran or Visual Basic, it's not the default behavior, and in most languages in modern use, true call-by-reference is not even possible.

2A fair amount of older ones support it, too

3In several modern languages, all types are reference types. This approach was pioneered by the language CLU in 1975 and has since been adopted by many other languages, including Python and Ruby. And many more languages use a hybrid approach, where some types are "value types" and others are "reference types" -- among them are C#, Java, and JavaScript.

4There's nothing bad with recycling a fitting old term per se, but one has to somehow make it clear which meaning is used each time. Not doing that is exactly what keeps causing confusion.

How do I configure PyCharm to run py.test tests?

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the 'unittests' test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

Inserting multiple rows in mysql

If you have your data in a text-file, you can use LOAD DATA INFILE.

When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.

Optimizing INSERT Statements

You can find more tips on how to speed up your insert statements on the link above.

How to reference static assets within vue javascript

What system are you using? Webpack? Vue-loader?

I'll only brainstorming here...

Because .png is not a JavaScript file, you will need to configure Webpack to use file-loader or url-loader to handle them. The project scaffolded with vue-cli has also configured this for you.

You can take a look at webpack.conf.js in order to see if it's well configured like

...
    {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
...

/assets is for files that are handles by webpack during bundling - for that, they have to be referenced somewhere in your javascript code.

Other assets can be put in /static, the content of this folder will be copied to /dist later as-is.

I recommend you to try to change:

iconUrl: './assets/img.png'

to

iconUrl: './dist/img.png'

You can read the official documentation here: https://vue-loader.vuejs.org/en/configurations/asset-url.html

Hope it helps to you!

Can I run HTML files directly from GitHub, instead of just viewing their source?

If you have an angular or react project in github, you can use https://stackblitz.com/ to run the application online in your browser.

Enter your Github username and repository name to view the application online - stackblitz.com/github/{GITHUB_USERNAME}/{REPO_NAME}

This works even without Node_Modules uploaded to Github

Currently support projects using @angular/cli and create-react-app. Support for Ionic, Vue, and custom webpack configs are coming soon!

How do I create a branch?

Create a new branch using the svn copy command as follows:

$ svn copy svn+ssh://host.example.com/repos/project/trunk \
           svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \
      -m "Creating a branch of project"

Which loop is faster, while or for?

Isn't a For Loop technically a Do While?

E.g.

for (int i = 0; i < length; ++i)
{
   //Code Here.
}

would be...

int i = 0;
do 
{
  //Code Here.
} while (++i < length);

I could be wrong though...

Also when it comes to for loops. If you plan to only retrieve data and never modify data you should use a foreach. If you require the actual indexes for some reason you'll need to increment so you should use the regular for loop.

for (Data d : data)
{
       d.doSomething();
}

should be faster than...

for (int i = 0; i < data.length; ++i)
{
      data[i].doSomething();
}

PowerShell: Run command from script's directory

I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running

$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path

import-module "$currentPath\sqlps.ps1"

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

Powershell 2 copy-item which creates a folder if doesn't exist

function Copy-File ([System.String] $sourceFile, [System.String] $destinationFile, [Switch] $overWrite) {

    if ($sourceFile -notlike "filesystem::*") {
        $sourceFile = "filesystem::$sourceFile" 
    }

    if ($destinationFile -notlike "filesystem::*") {
        $destinationFile = "filesystem::$destinationFile" 
    }

    $destinationFolder = $destinationFile.Replace($destinationFile.Split("\")[-1],"")

    if (!(Test-Path -path $destinationFolder)) {
        New-Item $destinationFolder -Type Directory
    }

    try {
        Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
        Return $true 
    } catch [System.IO.IOException] {
        # If overwrite enabled, then delete the item from the destination, and try again:
        if ($overWrite) {
            try {
                Remove-Item -Path $destinationFile -Recurse -Force        
                Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force 
                Return $true
            } catch {
                Write-Error -Message "[Copy-File] Overwrite error occurred!`n$_" -ErrorAction SilentlyContinue
                #$PSCmdlet.WriteError($Global:Error[0])
                Return $false
            }
        } else {
            Write-Error -Message "[Copy-File] File already exists!" -ErrorAction SilentlyContinue
            #$PSCmdlet.WriteError($Global:Error[0])
            Return $false
        }
    } catch {
        Write-Error -Message "[Copy-File] File move failed!`n$_" -ErrorAction SilentlyContinue
        #$PSCmdlet.WriteError($Global:Error[0]) 
        Return $false
    } 
}

How do I get rid of an element's offset using CSS?

Quick fix:

position: relative;
top: -12px;
left: -2px;

this should balance out those offsets, but maybe you should take a look at your whole layout and see how that box interacts with other boxes.

As for terminology, left, right, top and bottom are CSS offset properties. They are used for positioning elements at a specific location (when used with absolute or fixed positioning), or to move them relative to their default location (when used with relative positioning). Margins on the other hand specify gaps between boxes and they sometimes collapse, so they can't be reliably used as offsets.

But note that in your case that offset may not be computed (solely) from CSS offsets.

sed edit file in place

You could use vi

vi -c '%s/foo/bar/g' my.txt -c 'wq'

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

LINQ Where with AND OR condition

Well, you're going to have to check for null somewhere. You could do something like this:

from item in db.vw_Dropship_OrderItems
         where (listStatus == null || listStatus.Contains(item.StatusCode)) 
            && (listMerchants == null || listMerchants.Contains(item.MerchantId))
         select item;

How to test an Oracle Stored Procedure with RefCursor return type?

I think this link will be enough for you. I found it when I was searching for the way to execute oracle procedures.

The link to the page

Short Description:

--cursor variable declaration 
variable Out_Ref_Cursor refcursor;
--execute procedure 
execute get_employees_name(IN_Variable,:Out_Ref_Cursor);
--display result referenced by ref cursor.
print Out_Ref_Cursor;

Function is not defined - uncaught referenceerror

Your issue here is that you're not understanding the scope that you're setting.

You are passing the ready function a function itself. Within this function, you're creating another function called codeAddress. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I've replaced $(document).ready() with its shortcut of just $() (http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById with the jQuery object.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case, I am using a tiny .exe that reloads the referenced DLLs via Reflection. So I just do these steps which saves my day:

From project properties on solution explorer, at build tab, I choose target platfrom x86

#if DEBUG vs. Conditional("DEBUG")

Usually you would need it in Program.cs where you want to decide to run either Debug on Non-Debug code and that too mostly in Windows Services. So I created a readonly field IsDebugMode and set its value in static constructor as shown below.

static class Program
{

    #region Private variable
    static readonly bool IsDebugMode = false;
    #endregion Private variable

    #region Constrcutors
    static Program()
    {
 #if DEBUG
        IsDebugMode = true;
 #endif
    }
    #endregion

    #region Main

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main(string[] args)
    {

        if (IsDebugMode)
        {
            MyService myService = new MyService(args);
            myService.OnDebug();             
        }
        else
        {
            ServiceBase[] services = new ServiceBase[] { new MyService (args) };
            services.Run(args);
        }
    }

    #endregion Main        
}

How to round a number to significant figures in Python

The sigfig package/library covers this. After installing you can do the following:

>>> from sigfig import round
>>> round(1234, 1)
1000
>>> round(0.12, 1)
0.1
>>> round(0.012, 1)
0.01
>>> round(0.062, 1)
0.06
>>> round(6253, 1)
6000
>>> round(1999, 1)
2000

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

Fatal error: Call to undefined function mysql_connect()

For CPanel users, if you see this error and you already have PHP 5.x selected for the site, there might be a CPanel update that disabled mysql and mysqli PHP extensions.

To check and enable the extensions:

  1. Go to Select PHP Version in CPanel
  2. Make sure you have PHP 5.x selected
  3. Make sure mysql and mysqli PHP extensions are checked

How to solve maven 2.6 resource plugin dependency?

If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).

To fix this you can either

  • Clear (parts of) your .m2 repo
  • Run maven with -U to force an update

C# try catch continue execution

In your second function remove the e variable in the catch block then add throw.

This will carry over the generated exception the the final function and output it.

Its very common when you dont want your business logic code to throw exception but your UI.

jQuery 1.9 .live() is not a function

If you happen to be using the Ruby on Rails' jQuery gem jquery-rails and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3 and you can lock it by using the following syntax on your Gemfile:

gem 'jquery-rails', '~> 2.1', '= 2.1.3'

then you can use the following command to update:

bundle update jquery-rails

I hope that help others facing a similar issue.

How to count the NaN values in a column in pandas DataFrame

To count zeroes:

df[df == 0].count(axis=0)

To count NaN:

df.isnull().sum()

or

df.isna().sum()

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I'm adding an answer with the same direction as the accepted answer but with small (important) differences and adding more details.

Consider the configuration below:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::<Bucket-Name>"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": ["arn:aws:s3:::<Bucket-Name>/*"]
    }
  ]
}

The policy grants programmatic write-delete access and is separated into two parts:
The ListBucket action provides permissions on the bucket level and the other PutObject/DeleteObject actions require permissions on the objects inside the bucket.

The first Resource element specifies arn:aws:s3:::<Bucket-Name> for the ListBucket action so that applications can list all objects in the bucket.

The second Resource element specifies arn:aws:s3:::<Bucket-Name>/* for the PutObject, and DeletObject actions so that applications can write or delete any objects in the bucket.

The separation into two different 'arns' is important from security reasons in order to specify bucket-level and object-level fine grained permissions.

Notice that if I would have specified just GetObject in the 2nd block what would happen is that in cases of programmatic access I would receive an error like:

Upload failed: <file-name> to <bucket-name>:<path-in-bucket> An error occurred (AccessDenied) when calling the PutObject operation: Access Denied.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

Good article here: Cross-domain communication with iframes

Also you can directly set document.domain the same in both frames (even

document.domain = document.domain;

code has sense because resets port to null), but this trick is not general-purpose.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

How to pass data between fragments

That depends on how the fragment is structured. If you can have some of the methods on the Fragment Class B static and also the target TextView object static, you can call the method directly on Fragment Class A. This is better than a listener as the method is performed instantaneously, and we don't need to have an additional task that performs listening throughout the activity. See example below:

Fragment_class_B.setmyText(String yourstring);

On Fragment B you can have the method defined as:

public static void setmyText(final String string) {
myTextView.setText(string);
}

Just don't forget to have myTextView set as static on Fragment B, and properly import the Fragment B class on Fragment A.

Just did the procedure on my project recently and it worked. Hope that helped.

Why can't I use a list as a dict key in python?

Your awnser can be found here:

Why Lists Can't Be Dictionary Keys

Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.

Source & more info: http://wiki.python.org/moin/DictionaryKeys

Is it possible to get element from HashMap by its position?

If you, for some reason, have to stick with the hashMap, you can convert the keySet to an array and index the keys in the array to get the values in the map like so:

Object[] keys = map.keySet().toArray();

You can then access the map like:

map.get(keys[i]);

regular expression for finding 'href' value of a <a> link

 HTMLDocument DOC = this.MySuperBrowser.Document as HTMLDocument;
 public IHTMLAnchorElement imageElementHref;
 imageElementHref = DOC.getElementById("idfirsticonhref") as IHTMLAnchorElement;

Simply try this code

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

I found two potential ways of solving this specific problem:

  1. Use Chosen

  2. Target mozilla browsers using @-moz-document url-prefix() like so:

@-moz-document url-prefix() {
  select {
    padding: 5px;
  }
}

How to map with index in Ruby?

I often do this:

arr = ["a", "b", "c"]

(0...arr.length).map do |int|
  [arr[int], int + 2]
end

#=> [["a", 2], ["b", 3], ["c", 4]]

Instead of directly iterating over the elements of the array, you're iterating over a range of integers and using them as the indices to retrieve the elements of the array.

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

PHP Checking if the current date is before or after a set date

Here's a list of all possible checks for …

"Did a date pass?"

Possible ways to obtain the value

$date = strtotime( $date );

$date > date( "U" )
$date > mktime( 0, 0, 0 )
$date > strtotime( 'now' )
$date > time()
$date > abs( intval( $_SERVER['REQUEST_TIME'] ) )

Performance Test Result (PHP 5.4.7)

I did some performance test on 1.000.000 iterations and calculated the average – Ordered fastest to slowest.

+---------------------+---------------+
|        method       |     time      |
+---------------------+---------------+
|        time()       | 0.0000006732  |
|       $_SERVER      | 0.0000009131  |
|      date("U")      | 0.0000028951  |
|     mktime(0,0,0)   | 0.000003906   |
|   strtotime("now")  | 0.0000045032  |
| new DateTime("now") | 0.0000053365  |
+---------------------+---------------+

ProTip: You can easily remember what's fastest by simply looking at the length of the function. The longer, the slower the function is.

Performance Test Setup

The following loop was run for each of the above mentioned possibilities. I converted the values to non-scientific notation for easier readability.

$loops = 1000000;
$start = microtime( true );
for ( $i = 0; $i < $loops; $i++ )
    date( "U" );
printf(
    '|    date("U")     | %s  |'."\n",
    rtrim( sprintf( '%.10F', ( microtime( true ) - $start ) / $loops ), '0' )
);

Conclusion

time() still seems to be the fastest.

Use sed to replace all backslashes with forward slashes

for just translating one char into another throughout a string, tr is the best tool:

tr '\\' '/'

VB.NET Empty String Array

The array you created by Dim s(0) As String IS NOT EMPTY

In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.

You should instead try using System.Collections.Specialized.StringCollection or (even better) System.Collections.Generic.List(Of String). They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.

If you really want an empty string array, declare it like this:

Dim s As String()

or

Dim t() As String

How to make a Bootstrap accordion collapse when clicking the header div?

Actually my panel had this collapse state arrow icon and I tried other answers in this post , but icon position changed, so here is the solution with collapse state arrow icon.

Add this Custom CSS

 .panel-heading 
  {
   cursor: pointer;
   padding: 0;
  }

 a.accordion-toggle 
 {
  display: block;
  padding: 10px  15px;
 }

Credit's goes to this post answerer.

Hope helps.

if else in a list comprehension

Like in [a if condition1 else b for i in list1 if condition2], the two ifs with condition1 and condition2 doing two different things. The part (a if condition1 else b) is from a lambda expression:

lambda x: a if condition1 else b

while the other condition2 is another lambda:

lambda x: condition2

Whole list comprehension can be regard as combination of map and filter:

map(lambda x: a if condition1 else b, filter(lambda x: condition2, list1))

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

How to encrypt a large file in openssl using public key

To safely encrypt large files (>600MB) with openssl smime you'll have to split each file into small chunks:

# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.

# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE

For the sake of information, here is how to decrypt and put all pieces together:

# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec

# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

How to access remote server with local phpMyAdmin client?

As stated in answer c.hill answer, if you want a secure solution I would advise to open an SSH tunnel to your server.

Here is the way to do it for Windows users:

  1. Download Plink and Putty from the Putty website and place the files in the folder of your choice (In my example C:\Putty)

  2. Open the Windows console and cd to Plink folder: cd C:\Putty

  3. Open the SSH tunnel and redirect to the port 3307:

    plink -L 3307:localhost:3306 username@server_ip -i path_to_your_private_key.ppk

Where:

  • 3307 is the local port you want to redirect to
  • localhost is the address of the MySQL DB on the remote server (localhost by default)
  • 3306 is the port use for PhpMyAdmin on the remote server (3306 by default)

Finally you can setup PhpMyAdmin:

  1. Add the remote server to your local PhpMyAdmin configuration by adding the following line at the end of config.inc.php

Lines to add:

$i++;   
$cfg['Servers'][$i]['verbose']          = 'Remote Dev server';
$cfg['Servers'][$i]['host']             = 'localhost';
$cfg['Servers'][$i]['port']             = '3307';
$cfg['Servers'][$i]['connect_type']     = 'tcp';
$cfg['Servers'][$i]['extension']        = 'mysqli';
$cfg['Servers'][$i]['compress']         = FALSE;
$cfg['Servers'][$i]['auth_type']        = 'cookie';
  1. You should be able to connect now at http://127.0.0.1/phpmyadmin

If you do not want to open the console each time you need to connect to your remote server, just create a batch file (by saving the 2 command lines in a .bat file).

How can you create multiple cursors in Visual Studio Code

Same issue on Ubuntu-MATE, but here you resolve it by:

gsettings set org.mate.Marco.general mouse-button-modifier "<Super>"

How to create a multi line body in C# System.Net.Mail.MailMessage

As per the comment by drris, if IsBodyHtml is set to true then a standard newline could potentially be ignored by design, I know you mention avoiding HTML but try using <br /> instead, even if just to see if this 'solves' the problem - then you can rule out by what you know:

var message = new System.Net.Mail.MailMessage();
message.Body = "First Line <br /> second line";

You may also just try setting IsBodyHtml to false and determining if newlines work in that instance, although, unless you set it to true explicitly I'm pretty sure it defaults to false anyway.

Also as a side note, avoiding HTML in emails is not necessarily any aid in getting the message through spam filters, AFAIK - if anything, the most you do by this is ensure cross-mail-client compatibility in terms of layout. To 'play nice' with spam filters, a number of other things ought to be taken into account; even so much as the subject and content of the mail, who the mail is sent from and where and do they match et cetera. An email simply won't be discriminated against because it is marked up with HTML.

Bootstrap 3 Align Text To Bottom of Div

I think your best bet would be to use a combination of absolute and relative positioning.

Here's a fiddle: http://jsfiddle.net/PKVza/2/

given your html:

<div class="row">
    <div class="col-sm-6">
        <img src="~/Images/MyLogo.png" alt="Logo" />
    </div>
    <div class="bottom-align-text col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

use the following CSS:

@media (min-width: 768px ) {
  .row {
      position: relative;
  }

  .bottom-align-text {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}

EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.

Could not complete the operation due to error 80020101. IE

I dont know why but it worked for me. If you have comments like

//Comment

Then it gives this error. To fix this do

/*Comment*/

Doesn't make sense but it worked for me.

What Ruby IDE do you prefer?

Once I found Geany (Ubuntu), I switched from TextMate (OSX) and never looked back. Geany is a lean, clean, speedy IDE that can be used either as a text editor or a light-weight IDE. It supports not only text editing features (syntax highlighting, code folding, auto-completion, auto-closing, symbol lists, code navigation, directory tree, multi-tabbed open files etc.) but also normal IDE features such as simple project management, compile-build-run within the main window. Unlike TextMate, it has a Terminal screen within its own window; you do not have to go back and force between your editor window and terminal window. Unlike TextMate, it supports international languages. Unlike TextMate, it supports multi-platforms, Unlike TextMate, it is open-source and free. Geany is now my favorite C/Ruby/XML development tool.

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

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

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

ansible: lineinfile for several lines?

It's not ideal, but you're allowed multiple calls to lineinfile. Using that with insert_after, you can get the result you want:

- name: Set first line at EOF (1/3)
  lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
  lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
  lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"

PHP memcached Fatal error: Class 'Memcache' not found

There are two extensions for memcached in PHP, "memcache" and "memcached".

It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

Sending POST parameters with Postman doesn't work, but sending GET parameters does

I was setting the url in Postman to be http:// but Apache was redirecting to https:// and somehow the POST variables were being dropped along the way.

After I changed it to https://, the POST variables worked properly.

See also: https://stackoverflow.com/a/28461500/704803

Extract parameter value from url using regular expressions

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

Git commit in terminal opens VIM, but can't get back to terminal

You need to return to normal mode and save the commit message with either

<Esc>:wq

or

<Esc>:x

or

<Esc>ZZ

The Esc key returns you from insert mode to normal mode. The :wq, :x or ZZ sequence writes the changes and exits the editor.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

var a = [];

it is use for brackets for an array of simple values. eg.

var name=["a","b","c"]

var a={}

is use for value arrays and objects/properties also. eg.

var programmer = { 'name':'special', 'url':'www.google.com'}

Checking if a key exists in a JS object

map.has(key) is the latest ECMAScript 2015 way of checking the existance of a key in a map. Refer to this for complete details.

Why java.security.NoSuchProviderException No such provider: BC?

For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:

<weblogic_jdk_home>\jre\lib\ext

Create PostgreSQL ROLE (user) if it doesn't exist

Some answers suggested to use pattern: check if role does not exist and if not then issue CREATE ROLE command. This has one disadvantage: race condition. If somebody else creates a new role between check and issuing CREATE ROLE command then CREATE ROLE obviously fails with fatal error.

To solve above problem, more other answers already mentioned usage of PL/pgSQL, issuing CREATE ROLE unconditionally and then catching exceptions from that call. There is just one problem with these solutions. They silently drop any errors, including those which are not generated by fact that role already exists. CREATE ROLE can throw also other errors and simulation IF NOT EXISTS should silence only error when role already exists.

CREATE ROLE throw duplicate_object error when role already exists. And exception handler should catch only this one error. As other answers mentioned it is a good idea to convert fatal error to simple notice. Other PostgreSQL IF NOT EXISTS commands adds , skipping into their message, so for consistency I'm adding it here too.

Here is full SQL code for simulation of CREATE ROLE IF NOT EXISTS with correct exception and sqlstate propagation:

DO $$
BEGIN
CREATE ROLE test;
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;

Test output (called two times via DO and then directly):

$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.

postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE:  42710: role "test" already exists, skipping
LOCATION:  exec_stmt_raise, pl_exec.c:3165
DO
postgres=# 
postgres=# CREATE ROLE test;
ERROR:  42710: role "test" already exists
LOCATION:  CreateRole, user.c:337

javax.websocket client simple example

TooTallNate has a simple client side https://github.com/TooTallNate/Java-WebSocket

Just add the java_websocket.jar in the dist folder into your project.

 import org.java_websocket.client.WebSocketClient;
 import org.java_websocket.drafts.Draft_10;
 import org.java_websocket.handshake.ServerHandshake;
 import org.json.JSONException;
 import org.json.JSONObject;

  WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() )
{
                    @Override
                    public void onMessage( String message ) {
                     JSONObject obj = new JSONObject(message);
                     String channel = obj.getString("channel");
                    }

                    @Override
                    public void onOpen( ServerHandshake handshake ) {
                        System.out.println( "opened connection" );
                    }

                    @Override
                    public void onClose( int code, String reason, boolean remote ) {
                        System.out.println( "closed connection" );
                    }

                    @Override
                    public void onError( Exception ex ) {
                        ex.printStackTrace();
                    }

                };
 //open websocket
 mWs.connect();
 JSONObject obj = new JSONObject();
 obj.put("event", "addChannel");
 obj.put("channel", "ok_btccny_ticker");
 String message = obj.toString();
 //send message
 mWs.send(message);

// and to close websocket

 mWs.close();

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Basically <key>ITSAppUsesNonExemptEncryption</key><false/> stands for a Boolean value equal to NO.

info.plist value

Update by @JosepH: This value means that the app uses no encryption, or only exempt encryption. If your app uses encryption and is not exempt, you must set this value to YES/true.

It seems debatable sometimes when an app is considered to use encryption.

Jenkins / Hudson environment variables

Here is what i did on ubuntu 18.04 LTS with Jenkins 2.176.2

I created .bash_aliases file and added there path, proxy variables and so on.

In beginning of .bashrc there was this defined.

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

So it's checking that if we are start non-interactive shell then we don't do nothing here.

bottom of the .bashrc there was include for .bash_aliases

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

so i moved .bash_aliases loading first at .bashrc just above non-interactive check.

This didn't work first but then i disconnected slave and re-connected it so it's loading variables again. You don't need to restart whole jenkins if you are modifying slave variables. just disconnect and re-connect.

How to select an item from a dropdown list using Selenium WebDriver with java?

WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
   if("Germany".equals(option.getText()))
       option.click();   
}

How do I specify local .gem files in my Gemfile?

This isn't strictly an answer to your question about installing .gem packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.

Specifying a :path attribute will install the gem from that path on your local machine.

gem "foreman", path: "/Users/pje/my_foreman_fork"

Alternately, specifying a :git attribute will install the gem from a remote git repository.

gem "foreman", git: "git://github.com/pje/foreman.git"

# ...or at a specific SHA-1 ref
gem "foreman", git: "git://github.com/pje/foreman.git", ref: "bf648a070c"

# ...or branch
gem "foreman", git: "git://github.com/pje/foreman.git", branch: "jruby"

# ...or tag
gem "foreman", git: "git://github.com/pje/foreman.git", tag: "v0.45.0"

(As @JHurrah mentioned in his comment.)

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

How to solve static declaration follows non-static declaration in GCC C code?

This error can be caused by an unclosed set of brackets.

int main {
  doSomething {}
  doSomething else {
}

Not so easy to spot, even in this 4 line example.

This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.

Can you find all classes in a package using reflection?

Hello. I always have had some issues with the solutions above (and on other sites).
I, as a developer, am programming a addon for a API. The API prevents the use of any external libraries or 3rd party tools. The setup also consists of a mixture of code in jar or zip files and class files located directly in some directories. So my code had to be able to work arround every setup. After a lot of research I have come up with a method that will work in at least 95% of all possible setups.

The following code is basically the overkill method that will always work.

The code:

This code scans a given package for all classes that are included in it. It will only work for all classes in the current ClassLoader.

/**
 * Private helper method
 * 
 * @param directory
 *            The directory to start with
 * @param pckgname
 *            The package name to search for. Will be needed for getting the
 *            Class object.
 * @param classes
 *            if a file isn't loaded but still is in the directory
 * @throws ClassNotFoundException
 */
private static void checkDirectory(File directory, String pckgname,
        ArrayList<Class<?>> classes) throws ClassNotFoundException {
    File tmpDirectory;

    if (directory.exists() && directory.isDirectory()) {
        final String[] files = directory.list();

        for (final String file : files) {
            if (file.endsWith(".class")) {
                try {
                    classes.add(Class.forName(pckgname + '.'
                            + file.substring(0, file.length() - 6)));
                } catch (final NoClassDefFoundError e) {
                    // do nothing. this class hasn't been found by the
                    // loader, and we don't care.
                }
            } else if ((tmpDirectory = new File(directory, file))
                    .isDirectory()) {
                checkDirectory(tmpDirectory, pckgname + "." + file, classes);
            }
        }
    }
}

/**
 * Private helper method.
 * 
 * @param connection
 *            the connection to the jar
 * @param pckgname
 *            the package name to search for
 * @param classes
 *            the current ArrayList of all classes. This method will simply
 *            add new classes.
 * @throws ClassNotFoundException
 *             if a file isn't loaded but still is in the jar file
 * @throws IOException
 *             if it can't correctly read from the jar file.
 */
private static void checkJarFile(JarURLConnection connection,
        String pckgname, ArrayList<Class<?>> classes)
        throws ClassNotFoundException, IOException {
    final JarFile jarFile = connection.getJarFile();
    final Enumeration<JarEntry> entries = jarFile.entries();
    String name;

    for (JarEntry jarEntry = null; entries.hasMoreElements()
            && ((jarEntry = entries.nextElement()) != null);) {
        name = jarEntry.getName();

        if (name.contains(".class")) {
            name = name.substring(0, name.length() - 6).replace('/', '.');

            if (name.contains(pckgname)) {
                classes.add(Class.forName(name));
            }
        }
    }
}

/**
 * Attempts to list all the classes in the specified package as determined
 * by the context class loader
 * 
 * @param pckgname
 *            the package name to search
 * @return a list of classes that exist within that package
 * @throws ClassNotFoundException
 *             if something went wrong
 */
public static ArrayList<Class<?>> getClassesForPackage(String pckgname)
        throws ClassNotFoundException {
    final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    try {
        final ClassLoader cld = Thread.currentThread()
                .getContextClassLoader();

        if (cld == null)
            throw new ClassNotFoundException("Can't get class loader.");

        final Enumeration<URL> resources = cld.getResources(pckgname
                .replace('.', '/'));
        URLConnection connection;

        for (URL url = null; resources.hasMoreElements()
                && ((url = resources.nextElement()) != null);) {
            try {
                connection = url.openConnection();

                if (connection instanceof JarURLConnection) {
                    checkJarFile((JarURLConnection) connection, pckgname,
                            classes);
                } else if (connection instanceof FileURLConnection) {
                    try {
                        checkDirectory(
                                new File(URLDecoder.decode(url.getPath(),
                                        "UTF-8")), pckgname, classes);
                    } catch (final UnsupportedEncodingException ex) {
                        throw new ClassNotFoundException(
                                pckgname
                                        + " does not appear to be a valid package (Unsupported encoding)",
                                ex);
                    }
                } else
                    throw new ClassNotFoundException(pckgname + " ("
                            + url.getPath()
                            + ") does not appear to be a valid package");
            } catch (final IOException ioex) {
                throw new ClassNotFoundException(
                        "IOException was thrown when trying to get all resources for "
                                + pckgname, ioex);
            }
        }
    } catch (final NullPointerException ex) {
        throw new ClassNotFoundException(
                pckgname
                        + " does not appear to be a valid package (Null pointer exception)",
                ex);
    } catch (final IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for "
                        + pckgname, ioex);
    }

    return classes;
}

These three methods provide you with the ability to find all classes in a given package.
You use it like this:

getClassesForPackage("package.your.classes.are.in");

The explanation:

The method first gets the current ClassLoader. It then fetches all resources that contain said package and iterates of these URLs. It then creates a URLConnection and determines what type of URl we have. It can either be a directory (FileURLConnection) or a directory inside a jar or zip file (JarURLConnection). Depending on what type of connection we have two different methods will be called.

First lets see what happens if it is a FileURLConnection.
It first checks if the passed File exists and is a directory. If that's the case it checks if it is a class file. If so a Class object will be created and put in the ArrayList. If it is not a class file but is a directory, we simply iterate into it and do the same thing. All other cases/files will be ignored.

If the URLConnection is a JarURLConnection the other private helper method will be called. This method iterates over all Entries in the zip/jar archive. If one entry is a class file and is inside of the package a Class object will be created and stored in the ArrayList.

After all resources have been parsed it (the main method) returns the ArrayList containig all classes in the given package, that the current ClassLoader knows about.

If the process fails at any point a ClassNotFoundException will be thrown containg detailed information about the exact cause.

How to convert ZonedDateTime to Date?

Here is an example converting current system time to UTC. It involves formatting ZonedDateTime as a String and then the String object will be parsed into a date object using java.text DateFormat.

    ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC);
    final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
    final DateFormat FORMATTER_YYYYMMDD_HH_MM_SS = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    String dateStr = zdt.format(DATETIME_FORMATTER);

    Date utcDate = null;
    try {
        utcDate = FORMATTER_YYYYMMDD_HH_MM_SS.parse(dateStr);
    }catch (ParseException ex){
        ex.printStackTrace();
    }

jQuery or JavaScript auto click

You are trying to make a popup work maybe? I don't know how to emulate click, maybe you can try to fire click event somehow, but I don't know if it is possible. More than likely such functionality is not implemented, because of security and privacy concerns.

You can use div with position:absolute to emulate popup at the same page. If you insist creating another page, I cannot help you. Maybe somebody else with more experience will add his 15 cents.

How do I see all foreign keys to a table or column?

A quick way to list your FKs (Foreign Key references) using the

KEY_COLUMN_USAGE view:

SELECT CONCAT( table_name, '.',
column_name, ' -> ',
referenced_table_name, '.',
referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;

This query does assume that the constraints and all referenced and referencing tables are in the same schema.

Add your own comment.

Source: the official mysql manual.

window.location.href doesn't redirect

window.location.href wasn't working in Android. I cleared cache in Android Chrome and it works fine. Suggest trying this first before getting involved in various coding.

PHP: How to check if a date is today, yesterday or tomorrow

<?php 
 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
 if($difference==0)
 {
    echo 'today';
 }
 else if($difference > 1)
 {
    echo 'Future Date';
 }
 else if($difference > 0)
 {
    echo 'tomorrow';
 }
 else if($difference < -1)
 {
    echo 'Long Back';
 }
 else
 {
    echo 'yesterday';
 }  
?>

ImportError: No module named 'selenium'

Navigate to your scripts folder in Python directory (C:\Python27\Scripts) and open command line there (Hold shift and right click then select open command window here). Run pip install -U selenium
If you don't have pip installed, go ahead and install pip first

Import Excel spreadsheet columns into SQL Server database

You could use OPENROWSET, something like:

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
  'Excel 8.0;IMEX=1;HDR=NO;DATABASE=C:\FILE.xls', 'Select * from [Sheet1$]'

Just make sure the path is a path on the server, not your local machine.

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Following worked for me.

  1. Open another instance of Application Loader. ( Select "Application Loader" under the "Xcode -> Open Developer Tool" menu)

  2. "Agree" to the terms.

  3. After completing Step 2. First instance of Application Loader proceeded to the next step and build got submitted.

Creating InetAddress object in Java

From the API for InetAddress

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

Embed an External Page Without an Iframe?

Or you could use the object tag:

http://jsfiddle.net/7MaXx/

<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->

<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->

Position buttons next to each other in the center of page

jsFiddle:http://jsfiddle.net/7Laf8/1302/

I hope this answers your question.

_x000D_
_x000D_
.wrapper {_x000D_
  text-align: center;_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <button class="button">Hello</button>_x000D_
  <button class="button">Another One</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_