Programs & Examples On #Activation record

jQuery Clone table row

Is very simple to clone the last row with jquery pressing a button:

Your Table HTML:

<table id="tableExample">
    <thead>
        <tr>
            <th>ID</th>
            <th>Header 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Line 1</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2"><button type="button" id="addRowButton">Add row</button></td>
        </tr>
    </tfoot>
</table>

JS:

$(document).on('click', '#addRowButton', function() {
    var table = $('#tableExample'),
        lastRow = table.find('tbody tr:last'),
        rowClone = lastRow.clone();

    table.find('tbody').append(rowClone);
});

Regards!

What happened to Lodash _.pluck?

Ah-ha! The Lodash Changelog says it all...

"Removed _.pluck in favor of _.map with iteratee shorthand"

var objects = [{ 'a': 1 }, { 'a': 2 }];

// in 3.10.1
_.pluck(objects, 'a'); // ? [1, 2]
_.map(objects, 'a'); // ? [1, 2]

// in 4.0.0
_.map(objects, 'a'); // ? [1, 2]

How to cancel a Task in await?

Or, in order to avoid modifying slowFunc (say you don't have access to the source code for instance):

var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code

//original code: await task;  
await Task.WhenAny(task, completionSource.Task); //New code

You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:

await Task.WhenAny(task, source.Token.AsTask());

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

Regular expression for a hexadecimal number?

The exact syntax depends on your exact requirements and programming language, but basically:

/[0-9a-fA-F]+/

or more simply, i makes it case-insensitive.

/[0-9a-f]+/i

If you are lucky enough to be using Ruby, you can do:

/\h+/

EDIT - Steven Schroeder's answer made me realise my understanding of the 0x bit was wrong, so I've updated my suggestions accordingly. If you also want to match 0x, the equivalents are

/0[xX][0-9a-fA-F]+/
/0x[0-9a-f]+/i
/0x[\h]+/i

ADDED MORE - If 0x needs to be optional (as the question implies):

/(0x)?[0-9a-f]+/i

How to use OKHTTP to make a post request?

If you want to post parameter in okhttp as body content which can be encrypted string with content-type as "application/x-www-form-urlencoded" you can first use URLEncoder to encode the data and then use :

final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/x-www-form-urlencoded");

okhttp3.Request request = new okhttp3.Request.Builder()
    .url(urlOfServer)
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, yourBodyDataToPostOnserver))
    .build();

you can add header according to your requirement.

Check if value already exists within list of dictionaries?

Maybe this helps:

a = [{ 'main_color': 'red', 'second_color':'blue'},
     { 'main_color': 'yellow', 'second_color':'green'},
     { 'main_color': 'yellow', 'second_color':'blue'}]

def in_dictlist((key, value), my_dictlist):
    for this in my_dictlist:
        if this[key] == value:
            return this
    return {}

print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)

How to get Client location using Google Maps API v3?

It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:

google.loader.ClientLocation.address.city

SQL Developer with JDK (64 bit) cannot find JVM

Create directory bin in

D:\sqldeveloper\jdk\

Copy

msvcr100.dll

from

D:\sqldeveloper\jdk\jre\bin

to

D:\sqldeveloper\jdk\bin

How to parse the AndroidManifest.xml file inside an .apk package

Check this following WPF Project which decodes the properties correctly.

How to use sed to remove the last n lines of a file

With the answers here you'd have already learnt that sed is not the best tool for this application.

However I do think there is a way to do this in using sed; the idea is to append N lines to hold space untill you are able read without hitting EOF. When EOF is hit, print the contents of hold space and quit.

sed -e '$!{N;N;N;N;N;N;H;}' -e x

The sed command above will omit last 5 lines.

Convert array values from string to int?

Not sure if this is faster but flipping an array twice will cast numeric strings to integers:

$string = "1,2,3,bla";
$ids = array_flip(array_flip(explode(',', $string)));
var_dump($ids);

Important: Do not use this if you are dealing with duplicate values!

How do I pull my project from github?

Since you have wiped out your computer and want to checkout your project again, you could start by doing the below initial settings:

git config --global user.name "Your Name"
git config --global user.email [email protected]

Login to your github account, go to the repository you want to clone, and copy the URL under "Clone with HTTPS".

You can clone the remote repository by using HTTPS, even if you had setup SSH the last time:

git clone https://github.com/username/repo-name.git

NOTE:

If you had setup SSH for your remote repository previously, you will have to add that key to the known hosts ssh file on your PC; if you don't and try to do git clone [email protected]:username/repo-name.git, you will see an error similar to the one below:

Cloning into 'repo-name'...
The authenticity of host 'github.com (192.30.255.112)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXDoJWGl7E1IGOCspZomTxdCARLviMw6E5SY8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,192.30.255.112' (RSA) to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Using HTTPS is a easier than SSH in this case.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Try writting the lambda with the same conditions as the delegate. like this:

  List<AnalysisObject> analysisObjects = 
    analysisObjectRepository.FindAll().Where(
    (x => 
       (x.ID == packageId)
    || (x.Parent != null && x.Parent.ID == packageId)
    || (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
    ).ToList();

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(System.in);
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char) System.in.read();

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I was getting this when the app deployed. In my case, I chose "This is a full trust application" on the project security tab, and that fixed it.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

  • In my case, it was gradle issue. I solved it by refreshing gradle :

  • Firstly, Click on gradle icon which right side on Android Studio

  • Then click on the refresh button

Unable to create Genymotion Virtual Device

I solved the problem.It was my mistake.
It works fine by running genymotion with administrative privileges.

Maven: The packaging for this project did not assign a file to the build artifact

While @A_Di-Matteo answer does work for non multimodule I have a solution for multimodules.

The solution is to override every plugin configuration so that it binds to the phase of none with the exception of the jar/war/ear plugin and of course the deploy plugin. Even if you do have a single module my rudimentary tests show this to be a little faster (for reasons I don't know) performance wise.

Thus the trick is to make a profile that does the above that is activated when you only want to deploy.

Below is an example from one of my projects which uses the shade plugin and thus I had to re-override the jar plugin not to overwrite:

    <profile>
      <id>deploy</id>
      <activation>
        <property>
          <name>buildStep</name>
          <value>deploy</value>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <executions>
              <execution>
                <id>default-compile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testCompile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>test-compile</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <executions>
              <execution>
                <id>default-test</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
              <execution>
                <id>default-install</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
              <execution>
                <id>default-resources</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testResources</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
              <execution>
                <id>default</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
              <execution>
                <id>default-jar</id>
                <configuration>
                  <forceCreation>false</forceCreation>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Now if I run mvn deploy -Pdeploy it will only run the jar and deploy plugins.

How you can figure out which plugins you need to override is to run deploy and look at the log to see which plugins are running. Make sure to keep track of the id of the plugin configuration which is parens after the name of the plugin.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I had the same problem, and the registry answers here didn't work.

I had a browser control in new version of my program that worked fine on XP, failed in Windows 7 (64 bit). The old version worked on both XP and Windows 7.

The webpage displayed in the browser uses some strange plugin for showing old SVG maps (I think its a Java applet).

Turns out the problem is related to DEP protection in Windows 7.

Old versions of dotnet 2 didn't set the DEP required flag in the exe, but from dotnet 2, SP 1 onwards it did (yep, the compiling behaviour and hence runtime behaviour of exe changed depending on which machine you compiled on, nice ...).

It is documented on a MSDN blog NXCOMPAT and the C# compiler. To quote : This will undoubtedly surprise a few developers...download a framework service pack, recompile, run your app, and you're now getting IP_ON_HEAP exceptions.

Adding the following to the post build in Visual Studio, turns DEP off for the exe, and everything works as expected:

all "$(DevEnvDir)..\tools\vsvars32.bat"
editbin.exe /NXCOMPAT:NO "$(TargetPath)"

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

you can use this way

 map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: { lat: parseFloat(lat), lng: parseFloat(lng) },
        mapTypeId: 'terrain', 
        disableDefaultUI: true
 });

EX : center: { lat: parseFloat(lat), lng: parseFloat(lng) },

HTML -- two tables side by side

You can place your tables in a div and add style to your table "float: left"

<div>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

or simply use css:

div>table {
  float: left
}

How do I keep the screen on in my App?

You need to use Power Manager to acquire a wake lock in your application.

Most probably you are interested in a FULL_WAKE_LOCK:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
....
wl.release();

Access-Control-Allow-Origin Multiple Origin Domains?

Here is what i did for a PHP application which is being requested by AJAX

$request_headers        = apache_request_headers();
$http_origin            = $request_headers['Origin'];
$allowed_http_origins   = array(
                            "http://myDumbDomain.example"   ,
                            "http://anotherDumbDomain.example"  ,
                            "http://localhost"  ,
                          );
if (in_array($http_origin, $allowed_http_origins)){  
    @header("Access-Control-Allow-Origin: " . $http_origin);
}

If the requesting origin is allowed by my server, return the $http_origin itself as value of the Access-Control-Allow-Origin header instead of returning a * wildcard.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

Java 8 stream map on entry set

On Java 9 or later, Map.entry can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry (as suggested in another answer) or AbstractMap.SimpleImmutableEntry would be the way to go.

private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
   int subLength = prefix.length();
   return input.entrySet().stream().map(e -> 
      Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
   }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

How to make HTML element resizable using pure Javascript?

Is simple:

Example:https://jsfiddle.net/RainStudios/mw786v1w/

var element = document.getElementById('element');
//create box in bottom-left
var resizer = document.createElement('div');
resizer.style.width = '10px';
resizer.style.height = '10px';
resizer.style.background = 'red';
resizer.style.position = 'absolute';
resizer.style.right = 0;
resizer.style.bottom = 0;
resizer.style.cursor = 'se-resize';
//Append Child to Element
element.appendChild(resizer);
//box function onmousemove
resizer.addEventListener('mousedown', initResize, false);

//Window funtion mousemove & mouseup
function initResize(e) {
   window.addEventListener('mousemove', Resize, false);
   window.addEventListener('mouseup', stopResize, false);
}
//resize the element
function Resize(e) {
   element.style.width = (e.clientX - element.offsetLeft) + 'px';
   element.style.height = (e.clientY - element.offsetTop) + 'px';
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
    window.removeEventListener('mousemove', Resize, false);
    window.removeEventListener('mouseup', stopResize, false);
}

How to refresh token with Google API client?

I used the example by smartcodes with the current version of the Google API, but that one didn't work. I think his API is too outdated.

So, I just wrote my own version, based on one of the API examples... It outputs access token, request token, token type, ID token, expiration time and creation time as strings

If your client credentials and developer key are correct, this code should work out of the box.

<?php
// Call set_include_path() as needed to point to your client library.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("Get Token");
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    return;
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['token']);
    $client->revokeToken();
}
?>
<!doctype html>
<html>
    <head><meta charset="utf-8"></head>
    <body>
        <header><h1>Get Token</h1></header>
        <?php
        if ($client->getAccessToken()) {
            $_SESSION['token'] = $client->getAccessToken();
            $token = json_decode($_SESSION['token']);
            echo "Access Token = " . $token->access_token . '<br/>';
            echo "Refresh Token = " . $token->refresh_token . '<br/>';
            echo "Token type = " . $token->token_type . '<br/>';
            echo "Expires in = " . $token->expires_in . '<br/>';
            echo "ID Token = " . $token->id_token . '<br/>';
            echo "Created = " . $token->created . '<br/>';
            echo "<a class='logout' href='?logout'>Logout</a>";
        } else {
            $authUrl = $client->createAuthUrl();
            print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }
        ?>
    </body>
</html>

Resize image in PHP

private function getTempImage($url, $tempName){
  $tempPath = 'tempFilePath' . $tempName . '.png';
  $source_image = imagecreatefrompng($url); // check type depending on your necessities.
  $source_imagex = imagesx($source_image);
  $source_imagey = imagesy($source_image);
  $dest_imagex = 861; // My default value
  $dest_imagey = 96;  // My default value

  $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);

  imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

  imagejpeg($dest_image, $tempPath, 100);

  return $tempPath;

}

This is an adapted solution based on this great explanation. This guy made a step by step explanation. Hope all enjoy it.

Selecting all text in HTML text input when clicked

I know this is old, but the best option is to now use the new placeholder HTML attribute if possible:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

Android saving file to external storage

Try This :

  1. Check External storage device
  2. Write File
  3. Read File
public class WriteSDCard extends Activity {

    private static final String TAG = "MEDIA";
    private TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        checkExternalMedia();
        writeToSDFile();
        readRaw();
    }

    /**
     * Method to check whether external media available and writable. This is
     * adapted from
     * http://developer.android.com/guide/topics/data/data-storage.html
     * #filesExternal
     */
    private void checkExternalMedia() {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Can't read or write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
            + " writable=" + mExternalStorageWriteable);
    }

    /**
     * Method to write ascii text characters to file on SD card. Note that you
     * must add a WRITE_EXTERNAL_STORAGE permission to the manifest file or this
     * method will throw a FileNotFound Exception because you won't have write
     * permission.
     */
    private void writeToSDFile() {
        // Find the root of the external storage.
        // See http://developer.android.com/guide/topics/data/data-
        // storage.html#filesExternal
        File root = android.os.Environment.getExternalStorageDirectory();
        tv.append("\nExternal file system root: " + root);
        // See
        // http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
        File dir = new File(root.getAbsolutePath() + "/download");
        dir.mkdirs();
        File file = new File(dir, "myData.txt");
        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println("Hi , How are you");
            pw.println("Hello");
            pw.flush();
            pw.close();
            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i(TAG, "******* File not found. Did you"
                + " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
        } catch (IOException e) {
            e.printStackTrace();
        }
        tv.append("\n\nFile written to " + file);
    }

    /**
     * Method to read in a text file placed in the res/raw directory of the
     * application. The method reads in all lines of the file sequentially.
     */
    private void readRaw() {
        tv.append("\nData read from res/raw/textfile.txt:");
        InputStream is = this.getResources().openRawResource(R.raw.textfile);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
        // size
        // More efficient (less readable) implementation of above is the
        // composite expression
        /*
         * BufferedReader br = new BufferedReader(new InputStreamReader(
         * this.getResources().openRawResource(R.raw.textfile)), 8192);
         */
        try {
            String test;
            while (true) {
                test = br.readLine();
                // readLine() returns null if no more lines in the file
                if (test == null) break;
                tv.append("\n" + "    " + test);
            }
            isr.close();
            is.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        tv.append("\n\nThat is all");
    }
}

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Can't connect to docker from docker-compose

if you are using docker-machine then you have to activate the environment using env variable. incase you are not using docker-machine then run your commands with sudo

How to make Java work with SQL Server?

Do not put both the old sqljdbc.jar and the new sqljdbc4.jar in your classpath - this will make it (more or less) unpredictable which classes are being used, if both of those JARs contain classes with the same qualified names.

You said you put sqljdbc4.jar in your classpath - did you remove the old sqljdbc.jar from the classpath? You said "it didn't work", what does that mean exactly? Are you sure you don't still have the old JAR in your classpath somewhere (maybe not explicitly)?

How do I prevent a Gateway Timeout with FastCGI on Nginx

If you use unicorn.

Look at top on your server. Unicorn likely is using 100% of CPU right now. There are several reasons of this problem.

  • You should check your HTTP requests, some of their can be very hard.

  • Check unicorn's version. May be you've updated it recently, and something was broken.

Compiling problems: cannot find crt1.o

If you're using Debian's Testing version, called 'wheezy', then you may have been bitten by the move to multiarch. More about Debian's multiarch here: http://wiki.debian.org/Multiarch

Basically, what is happening is various architecture specific libraries are being moved from traditional places in the file system to new architecture specific places. This is why /usr/bin/ld is confused.

You will find crt1.o in both /usr/lib64/ and /usr/lib/i386-linux-gnu/ now and you'll need to tell your toolchain about that. Here is some documentation on how to do that; http://wiki.debian.org/Multiarch/LibraryPathOverview

Note that merely creating a symlink will only give you one architecture and you'd be essentially disabling multiarch. While this may be what you want it might not be the optimal solution.

Scroll to a specific Element Using html

<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>

/*CSS*/
html { scroll-behavior: smooth; } 

Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.

Open web in new tab Selenium + Python

tabs = {}

def new_tab():
    global browser
    hpos = browser.window_handles.index(browser.current_window_handle)
    browser.execute_script("window.open('');")
    browser.switch_to.window(browser.window_handles[hpos + 1])
    return(browser.current_window_handle)
    
def switch_tab(name):
    global tabs
    global browser
    if not name in tabs.keys():
        tabs[name] = {'window_handle': new_tab(), 'url': url+name}
        browser.get(tabs[name]['url'])
    else:
        browser.switch_to.window(tabs[name]['window_handle'])

Disabling SSL Certificate Validation in Spring RestTemplate

Java code example for HttpClient > 4.3

package com.example.teocodownloader;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class Example {
    public static void main(String[] args) {
        CloseableHttpClient httpClient
                = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    }
}

By the way, don't forget to add the following dependencies to the pom file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

You could find Java code example for HttpClient < 4.3 as well.

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

How to easily resize/optimize an image size with iOS?

According to this session, iOS Memory Deep Dive, we had better use ImageIO to downscale images.

The bad of using UIImage downscale images.

  • Will decompress original image into memory
  • Internal coordinate space transforms are expensive

Use ImageIO

  • ImageIO can read image sizes and metadata information without dirtying memory.

  • ImageIO can resize images at cost of resized image only.

About Image in memory

  • Memory use is related to the dimensions of the images, not the file size.
  • UIGraphicsBeginImageContextWithOptions always uses SRGB rendering-format, which use 4 bytes per pixel.
  • A image have load -> decode -> render 3 phases.
  • UIImage is expensive for sizing and to resizing

For the following image, if you use UIGraphicsBeginImageContextWithOptions we only need 590KB to load a image, while we need 2048 pixels x 1536 pixels x 4 bytes per pixel = 10MB when decoding enter image description here

while UIGraphicsImageRenderer, introduced in iOS 10, will automatically pick the best graphic format in iOS12. It means, you may save 75% of memory by replacing UIGraphicsBeginImageContextWithOptions with UIGraphicsImageRenderer if you don't need SRGB.

This is my article about iOS images in memory

func resize(url: NSURL, maxPixelSize: Int) -> CGImage? {
    let imgSource = CGImageSourceCreateWithURL(url, nil)
    guard let imageSource = imgSource else {
        return nil
    }

    var scaledImage: CGImage?
    let options: [NSString: Any] = [
            // The maximum width and height in pixels of a thumbnail.
            kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
            kCGImageSourceCreateThumbnailFromImageAlways: true,
            // Should include kCGImageSourceCreateThumbnailWithTransform: true in the options dictionary. Otherwise, the image result will appear rotated when an image is taken from camera in the portrait orientation.
            kCGImageSourceCreateThumbnailWithTransform: true
    ]
    scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary)

    return scaledImage
}


let filePath = Bundle.main.path(forResource:"large_leaves_70mp", ofType: "jpg")

let url = NSURL(fileURLWithPath: filePath ?? "")

let image = resize(url: url, maxPixelSize: 600)

or

// Downsampling large images for display at smaller size
func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage {
    let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions)!
    let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
    let downsampleOptions =
        [kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceShouldCacheImmediately: true,
        // Should include kCGImageSourceCreateThumbnailWithTransform: true in the options dictionary. Otherwise, the image result will appear rotated when an image is taken from camera in the portrait orientation.
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
    let downsampledImage =
        CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!
    return UIImage(cgImage: downsampledImage)
}

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

Spring application context external properties?

<context:property-placeholder location="classpath*:spring/*.properties" />

If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above

<property name="locations" value ="config/springcontext.properties" />

this will be pointing to web-inf/classes/config/springcontext.properties

Insert image after each list item

ul li + li:before
{
    content:url(imgs/separator.gif);
}

C++: How to round a double to an int?

It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) x truncates the decimal value of x. As in your example, if x = 3.9995, the .9995 gets truncated and x = 3.

As proposed by many others, one solution is to add 0.5 to x, and then cast.

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

<data>
    <variable
        name="listener"
        type="my_package.MyListener" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/moreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> listener.onClick()}"
        android:text="@string/login"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}

Setting the height of a SELECT in IE

There is no work-around for this aside from ditching the select element.

How to position a DIV in a specific coordinates?

You don't have to use Javascript to do this. Using plain-old css:

div.blah {
  position:absolute;
  top: 0; /*[wherever you want it]*/
  left:0; /*[wherever you want it]*/
}

If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":

var blahclass =  $('.blah'); 
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it

Alternatively, if you must use regular old-javascript you can grab by id

var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever 
domElement.style.left = 0; // or whatever

Determine if char is a num or letter

If (theChar >= '0' && theChar <='9') it's a digit. You get the idea.

MongoDB: How to query for records where field is null or not set?

You can also try this:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()

Android Material: Status bar color won't change

The status bar is a system window owned by the operating system. On pre-5.0 Android devices, applications do not have permission to alter its color, so this is not something that the AppCompat library can support for older platform versions. The best AppCompat can do is provide support for coloring the ActionBar and other common UI widgets within the application.

How can I change the Y-axis figures into percentages in a barplot?

Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:

scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))

This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).

git still shows files as modified after adding to .gitignore

Simply add git rm -r --cached <folder_name/file_name>

Sometimes, you update the .gitignore file after the commit command of files. So, the files get cached in the memory. To remove the cached files, use the above command.

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

How to ignore the first line of data when processing CSV data?

I would convert csvreader to list, then pop the first element

import csv        

with open(fileName, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        data = list(csvreader)               # Convert to list
        data.pop(0)                          # Removes the first row

        for row in data:
            print(row)

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

import httplib ImportError: No module named httplib

If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

enter image description here

How do I change the figure size for a seaborn plot?

This can be done using:

plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

Binding a generic list to a repeater - ASP.NET

It is surprisingly simple...

Code behind:

// Here's your object that you'll create a list of
private class Products
{
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductPrice { get; set; }
}

// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{   
    // The the LIST as the DataSource
    this.rptItemsInCart.DataSource = ListOfSelectedProducts;

    // Then bind the repeater
    // The public properties become the columns of your repeater
    this.rptItemsInCart.DataBind();
}

ASPX code:

<asp:Repeater ID="rptItemsInCart" runat="server">
  <HeaderTemplate>
    <table>
      <thead>
        <tr>
            <th>Product Name</th>
            <th>Product Description</th>
            <th>Product Price</th>
        </tr>
      </thead>
      <tbody>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><%# Eval("ProductName") %></td>
      <td><%# Eval("ProductDescription")%></td>
      <td><%# Eval("ProductPrice")%></td>
    </tr>
  </ItemTemplate>
  <FooterTemplate>
    </tbody>
    </table>
  </FooterTemplate>
</asp:Repeater>

I hope this helps!

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

How can I check MySQL engine type for a specific table?

or just

show table status;

just that this will llist all tables on your database.

How to pass model attributes from one Spring MVC controller to another controller?

Add all model attributes to the redirecting URL as query string.

Is there a way to force npm to generate package-lock.json?

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

Is it possible to overwrite a function in PHP

I would include all functions of one case in an include file, and the others in another include.

For instance simple.inc would contain function boofoo() { simple } and really.inc would contain function boofoo() { really }

It helps the readability / maintenance of your program, having all functions of the same kind in the same inc.

Then at the top of your main module

  if ($_GET['foolevel'] == 10) {
    include "really.inc";
  }
  else {
    include "simple.inc";
  }

How to enable LogCat/Console in Eclipse for Android?

In the Window menu, open Show View -> Other ... and type log to find it.

How can I use iptables on centos 7?

With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.

It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:

systemctl stop firewalld
systemctl mask firewalld

Then, install the iptables-services package:

yum install iptables-services

Enable the service at boot-time:

systemctl enable iptables

Managing the service

systemctl [stop|start|restart] iptables

Saving your firewall rules can be done as follows:

service iptables save

or

/usr/libexec/iptables/iptables.init save

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

How to fit Windows Form to any screen resolution?

Set the form property to open in maximized state.

this.WindowState = FormWindowState.Maximized;

How do I Convert DateTime.now to UTC in Ruby?

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009

Loop through each row of a range in Excel

Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

how to implement Pagination in reactJs

I recently created this Pagination component that implements paging logic like Google's search results:

import React, { PropTypes } from 'react';
 
const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number   
}
 
const defaultProps = {
    initialPage: 1
}
 
class Pagination extends React.Component {
    constructor(props) {
        super(props);
        this.state = { pager: {} };
    }
 
    componentWillMount() {
        this.setPage(this.props.initialPage);
    }
 
    setPage(page) {
        var items = this.props.items;
        var pager = this.state.pager;
 
        if (page < 1 || page > pager.totalPages) {
            return;
        }
 
        // get new pager object for specified page
        pager = this.getPager(items.length, page);
 
        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
 
        // update state
        this.setState({ pager: pager });
 
        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }
 
    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;
 
        // default page size is 10
        pageSize = pageSize || 10;
 
        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);
 
        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }
 
        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
 
        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);
 
        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
 
    render() {
        var pager = this.state.pager;
 
        return (
            <ul className="pagination">
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(1)}>First</a>
                </li>
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
                </li>
                {pager.pages.map((page, index) =>
                    <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                        <a onClick={() => this.setPage(page)}>{page}</a>
                    </li>
                )}
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
                </li>
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.totalPages)}>Last</a>
                </li>
            </ul>
        );
    }
}
 
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;

And here's an example App component that uses the Pagination component to paginate a list of 150 example items:

import React from 'react';
import Pagination from './Pagination';
 
class App extends React.Component {
    constructor() {
        super();
 
        // an example array of items to be paged
        var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
 
        this.state = {
            exampleItems: exampleItems,
            pageOfItems: []
        };
 
        // bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
        this.onChangePage = this.onChangePage.bind(this);
    }
 
    onChangePage(pageOfItems) {
        // update state with new page of items
        this.setState({ pageOfItems: pageOfItems });
    }
 
    render() {
        return (
            <div>
                <div className="container">
                    <div className="text-center">
                        <h1>React - Pagination Example with logic like Google</h1>
                        {this.state.pageOfItems.map(item =>
                            <div key={item.id}>{item.name}</div>
                        )}
                        <Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
                    </div>
                </div>
                <hr />
                <div className="credits text-center">
                    <p>
                        <a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
                    </p>
                </div>
            </div>
        );
    }
}
 
export default App;

For more details and a live demo you can check out this post

changing visibility using javascript

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

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Perhaps something like this for the first problem, you can simply access the columns by their names:

>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
          b         e
1  0.071146  0.132145
2  0.495152  0.420219

For the second problem:

>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556,  0.13214495],
       [ 0.49515157,  0.42021946]])

How to start automatic download of a file in Internet Explorer?

Back to the roots, i use this:

<meta http-equiv="refresh" content="0; url=YOURFILEURL"/>

Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.

Greetings Tom :)

How to implement WiX installer upgrade?

I'm using the latest version of WiX (3.0) and couldn't get the above working. But this did work:

<Product Id="*" UpgradeCode="PUT-GUID-HERE" ... >

<Upgrade Id="PUT-GUID-HERE">
  <UpgradeVersion OnlyDetect="no" Property="PREVIOUSFOUND"
     Minimum="1.0.0.0"  IncludeMinimum="yes"
     Maximum="99.0.0.0" IncludeMaximum="no" />
</Upgrade>

Note that PUT-GUID-HERE should be the same as the GUID that you have defined in the UpgradeCode property of the Product.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

Updated 2020...

Bootstrap 5

In Bootstrap 5 (alpha) there is a new -xxl- size:

col-* - 0 (xs)
col-sm-* - 576px
col-md-* - 768px
col-lg-* - 992px
col-xl-* - 1200px
col-xxl-* - 1400px

Bootstrap 5 Grid Demo


Bootstrap 4

In Bootstrap 4 there is a new -xl- size, see this demo. Also the -xs- infix has been removed, so smallest columns are simply col-1, col-2.. col-12, etc..

col-* - 0 (xs)
col-sm-* - 576px
col-md-* - 768px
col-lg-* - 992px
col-xl-* - 1200px

Bootstrap 4 Grid Demo

Additionally, Bootstrap 4 includes new auto-layout columns. These also have responsive breakpoints (col, col-sm, col-md, etc..), but don't have defined % widths. Therefore, the auto-layout columns fill equal width across the row.


Bootstrap 3

The Bootstrap 3 grid comes in 4 tiers (or "breakpoints")...

  • Extra small (for smartphones .col-xs-*)
  • Small (for tablets .col-sm-*)
  • Medium (for laptops .col-md-*)
  • Large (for laptops/desktops .col-lg-*).

These grid sizes enable you to control grid behavior on different widths. The different tiers are controlled by CSS media queries.

So in Bootstrap's 12-column grid...

col-sm-3 is 3 of 12 columns wide (25%) on a typical small device width (> 768 pixels)

col-md-3 is 3 of 12 columns wide (25%) on a typical medium device width (> 992 pixels)


The smaller tier (xs, sm or md) also defines the size for larger screen widths. So, for the same size column on all tiers, just set the width for the smallest viewport...

<div class="col-lg-3 col-md-3 col-sm-3">..</div> is the same as,

<div class="col-sm-3">..</div>

Larger tiers are implied. Because col-sm-3 means 3 units on sm-and-up, unless specifically overridden by a larger tier that uses a different size.

xs(default) > overridden by sm > overridden by md > overridden by lg


Combine the classes to use change column widths on different grid sizes. This creates a responsive layout.

<div class="col-md-3 col-sm-6">..</div>

The sm, md and lg grids will all "stack" vertically on screens/viewports less than 768 pixels. This is where the xs grid fits in. Columns that use the col-xs-* classes will not stack vertically, and continue to scale down on the smallest screens.

Resize your browser using this demo and you'll see the grid scaling effects.


This article explains more about how the Bootstrap grid

Error: Specified cast is not valid. (SqlManagerUI)

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf' 

How to Animate Addition or Removal of Android ListView Rows

Just sharing another approach:

First set the list view's android:animateLayoutChanges to true:

<ListView
        android:id="@+id/items_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"/>

Then I use a handler to add items and update the listview with delay:

Handler mHandler = new Handler();
    //delay in milliseconds
    private int mInitialDelay = 1000;
    private final int DELAY_OFFSET = 1000;


public void addItem(final Integer item) {
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mDataSet.add(item);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }).start();

        }
    }, mInitialDelay);
    mInitialDelay += DELAY_OFFSET;
}

Find and Replace text in the entire table using a MySQL query

I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin (4.5.0.2) who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…

Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…

UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid` 
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

To test the expected result you may want to use :

SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

How can you encode a string to Base64 in JavaScript?

if you need to encode HTML image object, you can write simple function like:

function getBase64Image(img) {  
  var canvas = document.createElement("canvas");  
  canvas.width = img.width;  
  canvas.height = img.height;  
  var ctx = canvas.getContext("2d");  
  ctx.drawImage(img, 0, 0);  
  var dataURL = canvas.toDataURL("image/png");  
  // escape data:image prefix
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");  
  // or just return dataURL
  // return dataURL
}  

To get base64 of image by id:

function getBase64ImageById(id){  
  return getBase64Image(document.getElementById(id));  
} 

more here

Get a list of URLs from a site

So, in an ideal world you'd have a spec for all pages in your site. You would also have a test infrastructure that could hit all your pages to test them.

You're presumably not in an ideal world. Why not do this...?

  1. Create a mapping between the well known old URLs and the new ones. Redirect when you see an old URL. I'd possibly consider presenting a "this page has moved, it's new url is XXX, you'll be redirected shortly".

  2. If you have no mapping, present a "sorry - this page has moved. Here's a link to the home page" message and redirect them if you like.

  3. Log all redirects - especially the ones with no mapping. Over time, add mappings for pages that are important.

Delete default value of an input text on click

I didn't see any really simple answers like this one, so maybe it will help someone out.

var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }

how to change default python version?

Do right thing, do thing right!

--->Zero Open your terminal,

--Firstly input python -V, It likely shows:

Python 2.7.10

-Secondly input python3 -V, It likely shows:

Python 3.7.2

--Thirdly input where python or which python, It likely shows:

/usr/bin/python

---Fourthly input where python3 or which python3, It likely shows:

/usr/local/bin/python3

--Fifthly add the following line at the bottom of your PATH environment variable file in ~/.profile file or ~/.bash_profile under Bash or ~/.zshrc under zsh.

alias python='/usr/local/bin/python3'

OR

alias python=python3

-Sixthly input source ~/.bash_profile under Bash or source ~/.zshrc under zsh.

--Seventhly Quit the terminal.

---Eighthly Open your terminal, and input python -V, It likely shows:

Python 3.7.2

I had done successfully try it.

Others, the ~/.bash_profile under zsh is not that ~/.bash_profile.

The PATH environment variable under zsh instead ~/.profile (or ~/.bash_file) via ~/.zshrc.

Help you guys!

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

How to both read and write a file in C#

var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);

...

fs.Close();
//or sw.Close();

The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.

Check if input value is empty and display an alert

$('#submit').click(function(){
   if($('#myMessage').val() == ''){
      alert('Input can not be left blank');
   }
});

Update

If you don't want whitespace also u can remove them using jQuery.trim()

Description: Remove the whitespace from the beginning and end of a string.

$('#submit').click(function(){
   if($.trim($('#myMessage').val()) == ''){
      alert('Input can not be left blank');
   }
});

How to make the 'cut' command treat same sequental delimiters as one?

Try:

tr -s ' ' <text.txt | cut -d ' ' -f4

From the tr man page:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence
                        of that character

How to compile the finished C# project and then run outside Visual Studio?

In the project file is folder "bin/debug/your_appliacion_name.exe". This is final executable program file.

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

pull out p-values and r-squared from a linear regression

r-squared: You can return the r-squared value directly from the summary object summary(fit)$r.squared. See names(summary(fit)) for a list of all the items you can extract directly.

Model p-value: If you want to obtain the p-value of the overall regression model, this blog post outlines a function to return the p-value:

lmp <- function (modelobject) {
    if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
    f <- summary(modelobject)$fstatistic
    p <- pf(f[1],f[2],f[3],lower.tail=F)
    attributes(p) <- NULL
    return(p)
}

> lmp(fit)
[1] 1.622665e-05

In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same.

Coefficient p-values: If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:

summary(fit)$coefficients[,4]  

Alternatively, you can grab the p-value of coefficients from the anova(fit) object in a similar fashion to the summary object above.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

How do I hide the status bar in a Swift iOS app?

 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true);
    navigationController?.navigationBar.hidden = true // for navigation bar hide
    UIApplication.sharedApplication().statusBarHidden=true; // for status bar hide
}

Get an element by index in jQuery

You can use the eq method or selector:

$('ul').find('li').eq(index).css({'background-color':'#343434'});

Pass data from Activity to Service using an Intent

If you bind your service, you will get the Extra in onBind(Intent intent).

Activity:

 Intent intent = new Intent(this, LocationService.class);                                                                                     
 intent.putExtra("tour_name", mTourName);                    
 bindService(intent, mServiceConnection, BIND_AUTO_CREATE); 

Service:

@Override
public IBinder onBind(Intent intent) {
    mTourName = intent.getStringExtra("tour_name");
    return mBinder;
}

How to stop java process gracefully?

Here is a bit tricky, but portable solution:

  • In your application implement a shutdown hook
  • When you want to shut down your JVM gracefully, install a Java Agent that calls System.exit() using the Attach API.

I implemented the Java Agent. It is available on Github: https://github.com/everit-org/javaagent-shutdown

Detailed description about the solution is available here: https://everitorg.wordpress.com/2016/06/15/shutting-down-a-jvm-process/

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

"sed" command in bash

It reads Hello World (cat), replaces all (g) occurrences of % by $ and (over)writes it to /etc/init.d/dropbox as root.

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Escape regex special characters in a Python string

Use re.escape

>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com

Repeating it here:

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

As of Python 3.7 re.escape() was changed to escape only characters which are meaningful to regex operations.

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

In my case, I need to set the path of openssl.cnf file manually on the command using config option. So the command

openssl req -x509 -config "C:\Users\sk\Downloads\openssl-0.9.8k_X64\openssl.cnf" -newkey rsa:4096 -keyout key.pem -out cert.pem -nodes -days 900

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

MySQL root access from all hosts

if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file. an example:

[mysqld]
bind-address = 127.100.10.234

this ip is from a ethX configuration.

How to get UTF-8 working in Java webapps?

About CharsetFilter mentioned in @kosoant answer ....

There is a build in Filter in tomcat web.xml (located at conf/web.xml). The filter is named setCharacterEncodingFilter and is commented by default. You can uncomment this ( Please remember to uncomment its filter-mapping too )

Also there is no need to set jsp-config in your web.xml (I have test it for Tomcat 7+ )

How can I generate Javadoc comments in Eclipse?

At a place where you want javadoc, type in /**<NEWLINE> and it will create the template.

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

Error CS1705: "which has a higher version than referenced assembly"

In our team we were working on different computers with git. Someone updated a dll and I didn't had it. I just updated my dependencies references and the problem solved.

What strategies and tools are useful for finding memory leaks in .NET?

I just had a memory leak in a windows service, that I fixed.

First, I tried MemProfiler. I found it really hard to use and not at all user friendly.

Then, I used JustTrace which is easier to use and gives you more details about the objects that are not disposed correctly.

It allowed me to solve the memory leak really easily.

How to $watch multiple variable change in angular

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Create comma separated strings C#?

You could override your object's ToString() method:

public override string ToString ()
{
    return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}

Drop rows containing empty cells from a pandas DataFrame

You can use this variation:

import pandas as pd
vals = {
    'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
    'gender' : ['m', 'f', 'f', 'f',  'f', 'c', 'c'],
    'age' : [39, 12, 27, 13, 36, 29, 10],
    'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe

This will output(** - highlighting only desired rows):

   age education gender name
0   39        ma      m   n1 **
1   12      None      f   n2    
2   27    school      f   n3 **
3   13      None      f   n4
4   36        ba      f   n5 **
5   29      None      c   n6
6   10      None      c   n7

So to drop everything that does not have an 'education' value, use the code below:

df_vals = df_vals[~df_vals['education'].isnull()] 

('~' indicating NOT)

Result:

   age education gender name
0   39        ma      m   n1
2   27    school      f   n3
4   36        ba      f   n5

What is the MySQL JDBC driver connection string?

For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-

class DBConnection {
   private static Connection con = null;
   private static String USERNAME = "your_mysql_username";
   private static String PASSWORD = "your_mysql_password";
   private static String DRIVER = "com.mysql.jdbc.Driver";
   private static String URL = "jdbc:mysql://localhost:3306/database_name";

   public static Connection getDatabaseConnection(){
       Class.forName(DRIVER);
       return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
   }
}

How to round the double value to 2 decimal points?

import java.text.DecimalFormat;

public class RoundTest {
    public static void main(String[] args) {
        double i = 2;    
        DecimalFormat twoDForm = new DecimalFormat("#.00");
        System.out.println(twoDForm.format(i));
        double j=3.1;
        System.out.println(twoDForm.format(j));
        double k=4.144456;
        System.out.println(twoDForm.format(k));
    }
}

jQuery if Element has an ID?

Simply use:

$(".parent a[id]");

How to use a class from one C# project with another C# project

I had an issue with different target frameworks.

I was doing everything right, but just couldn't use the reference in P2. After I set the same target framework for P1 and P2, it worked like a charm.

Hope it will help someone

What is the best way to concatenate two vectors?

Based on Kiril V. Lyadvinsky answer, I made a new version. This snippet use template and overloading. With it, you can write vector3 = vector1 + vector2 and vector4 += vector3. Hope it can help.

template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
    std::vector<T> AB;
    AB.reserve(A.size() + B.size());                // preallocate memory
    AB.insert(AB.end(), A.begin(), A.end());        // add A;
    AB.insert(AB.end(), B.begin(), B.end());        // add B;
    return AB;
}

template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
    A.reserve(A.size() + B.size());                // preallocate memory without erase original data
    A.insert(A.end(), B.begin(), B.end());         // add B;
    return A;                                        // here A could be named AB
}

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

What is "android.R.layout.simple_list_item_1"?

Zakaria, that is a reference to an built-in XML layout document that is part of the Android OS, rather than one of your own XML layouts.

Here is a further list of layouts that you can use: http://developer.android.com/reference/android/R.layout.html
(Updated link thanks @Estel: https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout )

You can actually view the code for the layouts.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

The configuration of the memory depends on the nature of your app.

What are you doing?

What's the amount of transactions precessed?

How much data are you loading?

etc.

etc.

etc

Probably you could profile your app and start cleaning up some modules from your app.

Apparently this can occur after redeploying an application a few times

Tomcat has hot deploy but it consumes memory. Try restarting your container once in a while. Also you will need to know the amount of memory needed to run in production mode, this seems a good time for that research.

Tooltips with Twitter Bootstrap

Add this into your header

<script>
    //tooltip
    $(function() {
        var tooltips = $( "[title]" ).tooltip();
        $(document)(function() {
            tooltips.tooltip( "open" );
        });
    });
</script>

Then just add the attribute title="your tooltip" to any element

Invoking a static method using reflection

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

How to calculate the time interval between two time strings

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.

Command-line svn for Windows?

You can use Apache Subversion. It is owner of subversion . You can download from here . After install it, you have to restart pc to use svn from command line.

What is the point of the diamond operator (<>) in Java 7?

The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.

The only difference if you specify in Java 5 and 6,

List<String> list = new ArrayList();

is that you have to specify @SuppressWarnings("unchecked") to the list (otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.

Custom Authentication in ASP.Net-Core

I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:

First of all, you should change signature of SignIn method in UserManager class from:

public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

to:

public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

It's because you should never use async void, especially if you work with HttpContext. Source: Microsoft Docs

The last, but not least, your Configure() method in Startup.cs should contains app.UseAuthorization and app.UseAuthentication in proper order:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Getting a count of rows in a datatable that meet certain criteria

If the data is stored in a database it will be faster to send the query to the database instead of getting all data and query it in memory.

A third way to do it will be linq to datasets, but i doubt any of these 3 methods differ much in performance.

What causes a Python segmentation fault?

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

    gdb python
    (gdb) run /path/to/script.py
    ## wait for segfault ##
    (gdb) backtrace
    ## stack trace of the c code
    

Set ANDROID_HOME environment variable in mac

As a noob I was struggling a lot with setting up the variable.I was creating copies of .bash_profile files, the text in file was not saving etc ..

So I documented the the steps that worked for me. It is simple and foolproof( but little lengthy ) way to do it ?

Step1. Go to Finder >Go(on top) , click on users, then your user account you will see something like this :

{https://i.stack.imgur.com/8e9qX.png}

Step2. Now hold down ⌘ + ? + . (dot) , this will now display hidden files and folders. It will look something like this:

{https://i.stack.imgur.com/apOoO.png}

PS: If the ⌘ + ? +. does not work, please look up the keyboard shortcut relevant for your Mac Operating system name

Step3.

Scenario A :If .bash_profile already exists

Step3.A.1 :Double click the .bash_profile. It should open up with TextEdit ( or alternatively right click >open with >TextEdit)

Step3.A.2 : Paste the variable text in the .bash_profile file using ⌘ + V

Step3.A.3 :Save the .bash_profile file using ⌘ + S

Scenario B :If .bash_profile does NOT exist This is kind silly way of doing it , but it worked perfectly for noob like me

Step3.B.1 : Download free BBEdit text editor which is pretty light weight. Whats special about this editor is that it lets you save file that starts with ". "

Step3.B.2 : Create a new file

Step3.B.3 : Save the file in your account folder . A warning will pop up , which looks something like this:

{https://i.stack.imgur.com/KLZmL.png}

Click Use"." button. Then the blank .bash_profile file will be saved

Step3.B.4 : Paste the variable text in the .bash_profile file using ⌘ + V

Step3.B.5 :Save the .bash_profile file using ⌘ + S

Step 4: Last and final step is to check if the above steps worked. Open the bash and type echo $ANDROID_HOME

Your ANDROID_HOME variable should be now set.

How can I pass some data from one controller to another peer controller

You need to use

 $rootScope.$broadcast()

in the controller that must send datas. And in the one that receive those datas, you use

 $scope.$on

Here is a fiddle that i forked a few time ago (I don't know who did it first anymore

http://jsfiddle.net/patxy/RAVFM/

Pandas: Return Hour from Datetime Column Directly

Assuming timestamp is the index of the data frame, you can just do the following:

hours = sales.index.hour

If you want to add that to your sales data frame, just do:

import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)

Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:

hours = sales['date'].hour

Edit2: If you want to adjust a column in your data frame you have to include dt:

sales['datehour'] = sales['date'].dt.hour

how to toggle attr() in jquery

This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!

Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:

$('.list-sort')[$('.list-sort').hasAttr('colspan') ? 
    'removeAttr' : 'attr']('colspan', 6);

an extra variable can be used in these cases, when you need to use the reference more than once:

var $listSort = $('.list-sort'); 
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);

CSS: create white glow around image

@tamir; you cna do it with css3 property.

img{
-webkit-box-shadow: 0px 0px 3px 5px #f2e1f2;
-moz-box-shadow: 0px 0px 3px 5px #f2e1f2;
box-shadow: 0px 0px 3px 5px #f2e1f2; 
}

check the fiddle http://jsfiddle.net/XUC5q/1/ & your can generate from here http://css3generator.com/

If you need it to work in older versions of IE, you can use CSS3 PIE to emulate the box-shadow in those browsers & you can use filter as kyle said like this

filter:progid:DXImageTransform.Microsoft.Glow(color='red', Strength='5')

you can generate your filter from here http://samples.msdn.microsoft.com/workshop/samples/author/filter/Glow.htm

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.

difference between new String[]{} and new String[] in java

You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.

Function for Factorial in Python

Easiest way is to use math.factorial (available in Python 2.6 and above):

import math
math.factorial(1000)

If you want/have to write it yourself, you can use an iterative approach:

def factorial(n):
    fact = 1
    for num in range(2, n + 1):
        fact *= num
    return fact

or a recursive approach:

def factorial(n):
    if n < 2:
        return 1
    else:
        return n * factorial(n-1)

Note that the factorial function is only defined for positive integers so you should also check that n >= 0 and that isinstance(n, int). If it's not, raise a ValueError or a TypeError respectively. math.factorial will take care of this for you.

How can I remove a commit on GitHub?

if you want to remove do interactive rebase,

git rebase -i HEAD~4

4 represents total number of commits to display count your commit andchange it accordingly

and delete commit you want from list...

save changes by Ctrl+X(ubuntu) or :wq(centos)

2nd method, do revert,

git revert 29f4a2 #your commit ID

this will revert specific commit

twitter bootstrap text-center when in xs mode

Responsive text alignment has been added in Bootstrap V4:

https://getbootstrap.com/docs/4.0/utilities/text/#text-alignment

For left, right, and center alignment, responsive classes are available that use the same viewport width breakpoints as the grid system.

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>

Python memory leaks

To detect and locate memory leaks for long running processes, e.g. in production environments, you can now use stackimpact. It uses tracemalloc underneath. More info in this post.

enter image description here

List<String> to ArrayList<String> conversion issue

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Can Mockito stub a method without regard to the argument?

Use like this:

when(
  fooDao.getBar(
    Matchers.<Bazoo>any()
  )
).thenReturn(myFoo);

Before you need to import Mockito.Matchers

How to control the line spacing in UILabel

Here is a subclass of UILabel that sets lineHeightMultiple and makes sure the intrinsic height is large enough to not cut off text.

@IBDesignable
class Label: UILabel {
    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        let padding = (1.0 - lineHeightMultiple) * font.pointSize
        size.height += padding
        return size
    }

    override var text: String? {
        didSet {
            updateAttributedText()
        }
    }

    @IBInspectable var lineHeightMultiple: CGFloat = 1.0 {
        didSet {
            updateAttributedText()
        }
    }

    private func updateAttributedText() {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = lineHeightMultiple
        attributedText = NSAttributedString(string: text ?? "", attributes: [
            .font: font,
            .paragraphStyle: paragraphStyle,
            .foregroundColor: textColor
        ])
        invalidateIntrinsicContentSize()
    }
}

How do you give iframe 100% height

You can do it with CSS:

<iframe style="position: absolute; height: 100%; border: none"></iframe>

Be aware that this will by default place it in the upper-left corner of the page, but I guess that is what you want to achieve. You can position with the left,right, top and bottom CSS properties.

Get Cell Value from a DataTable in C#

If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.

var s  = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();

Hope this helps

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

Is it possible to disable the network in iOS Simulator?

Just turn off your WiFi in Mac OSX this works a treat!

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

How to get index of an item in java.util.Set

One solution (though not very pretty) is to use Apache common List/Set mutation

import org.apache.commons.collections.list.SetUniqueList;

final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());

it is a list without duplicates

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html

Difference between maven scope compile and provided for JAR packaging

For a jar file, the difference is in the classpath listed in the MANIFEST.MF file included in the jar if addClassPath is set to true in the maven-jar-plugin configuration. 'compile' dependencies will appear in the manifest, 'provided' dependencies won't.

One of my pet peeves is that these two words should have the same tense. Either compiled and provided, or compile and provide.

How do I plot in real-time in a while loop using matplotlib?

An example use-case to plot CPU usage in real-time.

import time
import psutil
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

i = 0
x, y = [], []

while True:
    x.append(i)
    y.append(psutil.cpu_percent())

    ax.plot(x, y, color='b')

    fig.canvas.draw()

    ax.set_xlim(left=max(0, i - 50), right=i + 50)
    fig.show()
    plt.pause(0.05)
    i += 1

JavaScript Extending Class

For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

     function AbstractClass() {
      this.superclass_method = function(message) {
          // do something
        };
     }

     function Child() {
         AbstractClass.apply(this);
         // Now Child will have superclass_method()
     }

Example on angularjs:

http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview

app.service('noisyThing', 
  ['notify',function(notify){
    this._constructor = function() {
      this.scream = function(message) {
          message = message + " by " + this.get_mouth();
          notify(message); 
          console.log(message);
        };

      this.get_mouth = function(){
        return 'abstract mouth';
      }
    }
  }])
  .service('cat',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.meow = function() {
      this.scream('meooooow');
    }
    this.get_mouth = function(){
      return 'fluffy mouth';
    }
  }])
  .service('bird',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.twit = function() {
      this.scream('fuuuuuuck');
    }
  }])

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here
            }
        });

Firebase cloud messaging notification not received by device

Call super.OnMessageReceived() in the Overriden method. This worked for me! Finally!

jQuery AJAX cross domain

I use Apache server, so I've used mod_proxy module. Enable modules:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Then add:

ProxyPass /your-proxy-url/ http://service-url:serviceport/

Finally, pass proxy-url to your script.

How to set selected value from Combobox?

A possible solution:

cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;

Convert InputStream to JSONObject

you could use an Entity:

FileEntity entity = new FileEntity(jsonFile, "application/json");
String jsonString = EntityUtils.toString(entity)

How to check if two words are anagrams

This could be the simple function call

A mix of functional Code and Imperative style of code

static boolean isAnagram(String a, String b) {
    
    String sortedA = "";
    Object[] aArr = a.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
    for (Object o: aArr) {
        sortedA = sortedA.concat(o.toString());
    }
    
    
    String sortedB = "";
    Object[] bArr = b.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
    for (Object o: bArr) {
        sortedB = sortedB.concat(o.toString());
    }
    
    if(sortedA.equals(sortedB))    
        return true;
    else
        return false;    
}

Scanner vs. StringTokenizer vs. String.Split

If you have a String object you want to tokenize, favor using String's split method over a StringTokenizer. If you're parsing text data from a source outside your program, like from a file, or from the user, that's where a Scanner comes in handy.

Customizing Bootstrap CSS template

The best thing to do is.

1. fork twitter-bootstrap from github and clone locally.

they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.

2. Do not modify the bootstrap.css file

It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).

3. Create your own css file and overwrite whenever you want original bootstrap stuff

if they set a topbar with, let's say, color: black; but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">. If you declare your css file after bootstrap.css, this will overwrite whatever you want to.

Entity Framework Core: A second operation started on this context before a previous operation completed

In my case I was using a lock which does not allow the use of await and does not create compiler warning when you don't await an async.

The problem:

lock (someLockObject) {
    // do stuff
    context.SaveChangesAsync();
}

// some other code somewhere else doing await context.SaveChangesAsync() shortly after the lock gets the concurrency error

The fix: Wait for the async inside the lock by making it blocking with a .Wait()

lock (someLockObject) {
    // do stuff
    context.SaveChangesAsync().Wait();
}

Retrieve the commit log for a specific line in a file?

Simplifying @matt's answer -

git blame -L14,15 -- <file_path>

Here you will get a blame for a lines 14 to 15.

Since -L option expects Range as a param we can't get a Blame for a single line using the -L option`.

Reference

How to prevent colliders from passing through each other?

I have a pinball prototype that also gave me much trouble in the same areas. These are all the steps I've taken to almost (but not yet entirely) solve these problems:

For fast moving objects:

  • Set the rigidbody's Interpolate to 'Interpolate' (this does not affect the actual physics simulation, but updates the rendering of the object properly - use this only on important objects from a rendering point of view, like the player, or a pinball, but not for projectiles)

  • Set Collision Detection to Continuous Dynamic

  • Attach the script DontGoThroughThings (https://www.auto.tuwien.ac.at/wordpress/?p=260) to your object. This script cleverly uses the Raycasting solution I posted in my other answer to pull back offending objects to before the collision points.

In Edit -> Project Settings -> Physics:

  • Set Min Penetration for Penalty to a very low value. I've set mine to 0.001

  • Set Solver Iteration Count to a higher value. I've set mine to 50, but you can probably do ok with much less.

All that is going to have a penalty in performace, but that's unavoidable. The defaults values are soft on performance but are not really intented for proper simulation of small and fast-moving objects.

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

Don't understand why UnboundLocalError occurs (closure)

To modify a global variable inside a function, you must use the global keyword.

When you try to do this without the line

global counter

inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.

Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.

jQuery Mobile: document ready vs. page events

This is the correct way:

To execute code that will only be available to the index page, we could use this syntax:

$(document).on('pageinit', "#index",  function() {
    ...
});

File Explorer in Android Studio

As of Android Studio 2.4 Preview, it seems that they introduced "Device File Explorer" directly into the IDE, so we can finally say goodbye to DDMS. You can enable it from the menu under "View >> Tool Windows".

Jquery, Clear / Empty all contents of tbody element?

Without use ID (<tbody id="tbodyid">) , it is a great way to cope with this issue

$('#table1').find("tr:gt(0)").remove();

PS:To remove specific row number as following example

$('#table1 tr').eq(1).remove();

or

$('#tr:nth-child(2)').remove();

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        }
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        }
        alert('Login successful');

    } 

  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

Sorting a list using Lambda/Linq to objects

Adding to what @Samuel and @bluish did. This is much shorter as the Enum was unnecessary in this case. Plus as an added bonus when the Ascending is the desired result, you can pass only 2 parameters instead of 3 since true is the default answer to the third parameter.

public void Sort<TKey>(ref List<Person> list, Func<Person, TKey> sorter, bool isAscending = true)
{
    list = isAscending ? list.OrderBy(sorter) : list.OrderByDescending(sorter);
}

SVN "Already Locked Error"

After discussing with the hosting of my SVN repository they gave me the following answer.

Apparently my repository is replicated to a remote repository using SVNSYNC. SVNSYNC has known limitations with enforcing locking across the replicated repositories and this is where the problem lies.

The locks were introduced by the AnkhSVN plugin in Visual Studio.

As the locks appears to be on the remote repository this explains why I can't actually see them using SVN commands.

The locks are being removed via the hosting company and hopefully all will soon be well again.

How to obtain a QuerySet of all rows, with specific fields for each one of them?

You can use values_list alongside filter like so;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)

More details here

For each row return the column name of the largest value

One solution could be to reshape the date from wide to long putting all the departments in one column and counts in another, group by the employer id (in this case, the row number), and then filter to the department(s) with the max value. There are a couple of options for handling ties with this approach too.

library(tidyverse)

# sample data frame with a tie
df <- data_frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,5))

# If you aren't worried about ties:  
df %>% 
  rownames_to_column('id') %>%  # creates an ID number
  gather(dept, cnt, V1:V3) %>% 
  group_by(id) %>% 
  slice(which.max(cnt)) 

# A tibble: 3 x 3
# Groups:   id [3]
  id    dept    cnt
  <chr> <chr> <dbl>
1 1     V3       9.
2 2     V1       8.
3 3     V2       5.


# If you're worried about keeping ties:
df %>% 
  rownames_to_column('id') %>%
  gather(dept, cnt, V1:V3) %>% 
  group_by(id) %>% 
  filter(cnt == max(cnt)) %>% # top_n(cnt, n = 1) also works
  arrange(id)

# A tibble: 4 x 3
# Groups:   id [3]
  id    dept    cnt
  <chr> <chr> <dbl>
1 1     V3       9.
2 2     V1       8.
3 3     V2       5.
4 3     V3       5.


# If you're worried about ties, but only want a certain department, you could use rank() and choose 'first' or 'last'
df %>% 
  rownames_to_column('id') %>%
  gather(dept, cnt, V1:V3) %>% 
  group_by(id) %>% 
  mutate(dept_rank  = rank(-cnt, ties.method = "first")) %>% # or 'last'
  filter(dept_rank == 1) %>% 
  select(-dept_rank) 

# A tibble: 3 x 3
# Groups:   id [3]
  id    dept    cnt
  <chr> <chr> <dbl>
1 2     V1       8.
2 3     V2       5.
3 1     V3       9.

# if you wanted to keep the original wide data frame
df %>% 
  rownames_to_column('id') %>%
  left_join(
    df %>% 
      rownames_to_column('id') %>%
      gather(max_dept, max_cnt, V1:V3) %>% 
      group_by(id) %>% 
      slice(which.max(max_cnt)), 
    by = 'id'
  )

# A tibble: 3 x 6
  id       V1    V2    V3 max_dept max_cnt
  <chr> <dbl> <dbl> <dbl> <chr>      <dbl>
1 1        2.    7.    9. V3            9.
2 2        8.    3.    6. V1            8.
3 3        1.    5.    5. V2            5.

How to convert an xml string to a dictionary?

This is a great module that someone created. I've used it several times. http://code.activestate.com/recipes/410469-xml-as-dictionary/

Here is the code from the website just in case the link goes bad.

from xml.etree import cElementTree as ElementTree

class XmlListConfig(list):
    def __init__(self, aList):
        for element in aList:
            if element:
                # treat like dict
                if len(element) == 1 or element[0].tag != element[1].tag:
                    self.append(XmlDictConfig(element))
                # treat like list
                elif element[0].tag == element[1].tag:
                    self.append(XmlListConfig(element))
            elif element.text:
                text = element.text.strip()
                if text:
                    self.append(text)


class XmlDictConfig(dict):
    '''
    Example usage:

    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)

    Or, if you want to use an XML string:

    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)

    And then use xmldict for what it is... a dict.
    '''
    def __init__(self, parent_element):
        if parent_element.items():
            self.update(dict(parent_element.items()))
        for element in parent_element:
            if element:
                # treat like dict - we assume that if the first two tags
                # in a series are different, then they are all different.
                if len(element) == 1 or element[0].tag != element[1].tag:
                    aDict = XmlDictConfig(element)
                # treat like list - we assume that if the first two tags
                # in a series are the same, then the rest are the same.
                else:
                    # here, we put the list in dictionary; the key is the
                    # tag name the list elements all share in common, and
                    # the value is the list itself 
                    aDict = {element[0].tag: XmlListConfig(element)}
                # if the tag has attributes, add those to the dict
                if element.items():
                    aDict.update(dict(element.items()))
                self.update({element.tag: aDict})
            # this assumes that if you've got an attribute in a tag,
            # you won't be having any text. This may or may not be a 
            # good idea -- time will tell. It works for the way we are
            # currently doing XML configuration files...
            elif element.items():
                self.update({element.tag: dict(element.items())})
            # finally, if there are no child tags and no attributes, extract
            # the text
            else:
                self.update({element.tag: element.text})

Example usage:

tree = ElementTree.parse('your_file.xml')
root = tree.getroot()
xmldict = XmlDictConfig(root)

//Or, if you want to use an XML string:

root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)

Compile to stand alone exe for C# app in Visual Studio 2010

Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

How do you create a read-only user in PostgreSQL?

Reference taken from this blog:

Script to Create Read-Only user:

CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234' 
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';

Assign permission to this read only user:

GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User;
GRANT USAGE ON SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User;

Assign permissions to read all newly tables created in the future

ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User;

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

For IntelHAXM to install you have to activate Intel Virtual Technology.

To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.

After enabling it, reinstall IntelHAXM. That should solve the problem.

Why does adb return offline after the device string?

What did me in is was that multiple unrelated software packages just happened to install adb.exe -- in particular for me (on Windoze), the phone OEM driver installation package "helpfully" also installed adb.exe into C:\windows, and this directory appears in %PATH% long before the platform-tools directory of my android SDK. Unsurprisingly, the adb.exe included in the phone OEM driver package is MUCH older than the one in the updated android sdk. So adb worked just fine for me until one day something caused me to update the windows drivers for my phone. Once I did that, absolutely NOTHING would make my phone status change from "offline" -- but the problem had nothing to do with the driver. It was simply that the driver package had installed a different adb.exe - and a MUCH older one - into a directory with higher precedence. To fix my installation I simply altered the PATH environment variable to make the sdk's adb.exe have priority. A quick check suggested to me that "lots" of different packages include adb.exe, so be careful not to insert an older one into your toolchain unintentionally.

I must really be getting old: I don't ever remember such a stupid issue taking so endlessly long to uncover.

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

How can I get npm start at a different directory?

Per this npm issue list, one work around could be done through npm config

name: 'foo'
config: { path: "baz" },
scripts: { start: "node ./$npm_package_config_path" }

Under windows, the scripts could be { start: "node ./%npm_package_config_path%" }

Then run the command line as below

npm start --foo:path=myapp

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Undefined or null for AngularJS

lodash provides a shorthand method to check if undefined or null: _.isNil(yourVariable)

Xcode 4: How do you view the console?

The console is no extra window anymore but it is under the texteditor area. You can set the preferences to always show this area. Go to "General" "Run Start" and activate "Show Debugger". Under "Run completes" the Debugger is set to hide again. You should deactivate that option. Now the console will remain visible.

EDIT

In the latest GM Release you can show and hide the console via a button in the toolbar. Very easy.

Check whether a string contains a substring

Case Insensitive Substring Example

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";
} 

Which sort algorithm works best on mostly sorted data?

Based on the highly scientific method of watching animated gifs I would say Insertion and Bubble sorts are good candidates.