Programs & Examples On #Scalability

Scalability is the ability of a system, network, or process, to handle growing amount of work in a capable manner or its ability to be enlarged to accommodate that growth.

Difference between scaling horizontally and vertically for databases

There is an additional architecture that wasn't mentioned - SQL-based database services that enable horizontal scaling without the complexity of manual sharding. These services do the sharding in the background, so they enable you to run a traditional SQL database and scale out like you would with NoSQL engines like MongoDB or CouchDB. Two services I am familiar with are EnterpriseDB for PostgreSQL and Xeround for MySQL. I saw an in-depth post by Xeround which explains why scale-out on SQL databases is difficult and how they do it differently - treat this with a grain of salt as it is a vendor post. Also check out Wikipedia's Cloud Database entry, there is a nice explanation of SQL vs. NoSQL and service vs. self-hosted, a list of vendors and scaling options for each combination. ;)

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

Best way to store chat messages in a database?

You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).

The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).

Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.

A beginner's guide to SQL database design

These are questions which, in my opionion, requires different knowledge from different domains.

  1. You just can't know in advance "which" tables to build, you have to know the problem you have to solve and design the schema accordingly;
  2. This is a mix of database design decision and your database vendor custom capabilities (ie. you should check the documentation of your (r)dbms and eventually learn some "tips & tricks" for scaling), also the configuration of your dbms is crucial for scaling (replication, data partitioning and so on);
  3. again, almost every rdbms comes with a particular "dialect" of the SQL language, so if you want efficient queries you have to learn that particular dialect --btw. much probably write elegant query which are also efficient is a big deal: elegance and efficiency are frequently conflicting goals--

That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).

Does Django scale?

What's the "largest" site that's built on Django today? (I measure size mostly by user traffic)

In the US, it was Mahalo. I'm told they handle roughly 10 million uniques a month. Now, in 2019, Mahalo is powered by Ruby on Rails.

Abroad, the Globo network (a network of news, sports, and entertainment sites in Brazil); Alexa ranks them in to top 100 globally (around 80th currently).

Other notable Django users include PBS, National Geographic, Discovery, NASA (actually a number of different divisions within NASA), and the Library of Congress.

Can Django deal with 100k users daily, each visiting the site for a couple of hours?

Yes -- but only if you've written your application right, and if you've got enough hardware. Django's not a magic bullet.

Could a site like StackOverflow run on Django?

Yes (but see above).

Technology-wise, easily: see soclone for one attempt. Traffic-wise, compete pegs StackOverflow at under 1 million uniques per month. I can name at least dozen Django sites with more traffic than SO.

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

Alert after page load

Why can't you use it in MVC?

Rather than using the body load method use jQuery and wait for the the document onready function to complete.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Transfer data between databases with PostgreSQL

You can not perform a cross-database query like SQL Server; PostgreSQL does not support this.

The DbLink extension of PostgreSQL is used to connect one database to another database. You have install and configure DbLink to execute a cross-database query.

I have already created a step-by-step script and example for executing cross database query in PostgreSQL. Please visit this post: PostgreSQL [Video]: Cross Database Queries using the DbLink Extension

Entity Framework - Generating Classes

I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2

There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!

After installation some context menu options would be added to your Visual Studio.

Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):

Visual Studio Context Menu

Then choose your database and click OK. That's all! It is very easy.

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Is String.Contains() faster than String.IndexOf()?

I am running a real case (in opposite to a synthetic benchmark)

 if("=,<=,=>,<>,<,>,!=,==,".IndexOf(tmps)>=0) {

versus

 if("=,<=,=>,<>,<,>,!=,==,".Contains(tmps)) {

It is a vital part of my system and it is executed 131,953 times (thanks DotTrace).

However shocking surprise, the result is the opposite that expected

  • IndexOf 533ms.
  • Contains 266ms.

:-/

net framework 4.0 (updated as for 13-02-2012)

fatal: 'origin' does not appear to be a git repository

$HOME/.gitconfig is your global config for git.
There are three levels of config files.

 cat $(git rev-parse --show-toplevel)/.git/config

(mentioned by bereal) is your local config, local to the repo you have cloned.

you can also type from within your repo:

git remote -v

And see if there is any remote named 'origin' listed in it.

If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:

git remote add origin url/to/your/fork

The OP mentions:

Doing git remote -v gives:

upstream git://git.moodle.org/moodle.git (fetch) 
upstream git://git.moodle.org/moodle.git (push)

So 'origin' is missing: the reference to your fork.
See "What is the difference between origin and upstream in github"

enter image description here

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

make sure your MANIFEST.MF contains the name of the referenced jar in my application was slf4j-api-*. jar.

How do you make a LinearLayout scrollable?

This can be done using the tag <ScrollView>. For ScrollView, one thing you have to remind that, ScrollView must have a single child.

If you want your full layout to be scrollable then add <ScrollView> at the top. Check the example given below.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
            <!-- Content here -->
    </LinearLayout>

</ScrollView>

But if you want some part of your layout to be scrollable then add <ScrollView> within that part. Check the example given below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <!-- Content here -->
        </LinearLayout>

    </ScrollView>

</LinearLayout>

Unable to access JSON property with "-" dash

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

jQuery "on create" event for dynamically-created elements

create a <select> with id , append it to document.. and call .combobox

  var dynamicScript='<select id="selectid"><option value="1">...</option>.....</select>'
  $('body').append(dynamicScript); //append this to the place your wanted.
  $('#selectid').combobox();  //get the id and add .combobox();

this should do the trick.. you can hide the select if you want and after .combobox show it..or else use find..

 $(document).find('select').combobox() //though this is not good performancewise

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

No REAL easy way to do this. Lots of ideas out there, though.

Best one I've found:

SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
    SELECT column_name + ','
    FROM information_schema.columns AS intern
    WHERE extern.table_name = intern.table_name
    FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;

Or a version that works correctly if the data might contain characters such as <

WITH extern
     AS (SELECT DISTINCT table_name
         FROM   INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
       LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM   extern
       CROSS APPLY (SELECT column_name + ','
                    FROM   INFORMATION_SCHEMA.COLUMNS AS intern
                    WHERE  extern.table_name = intern.table_name
                    FOR XML PATH(''), TYPE) x (column_names)
       CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names) 

How can I list all tags for a Docker image on a remote registry?

You can achieve by running on terminal this:

curl -L -s 'https://registry.hub.docker.com/v2/repositories/library/mysql/tags/' | jq . | grep name

Also, if you don't have jq you have to install it by

sudo apt-get install jq

How do you roll back (reset) a Git repository to a particular commit?

For those with a git gui bent, you can also use gitk.

Right click on the commit you want to return to and select "Reset master branch to here". Then choose hard from the next menu.

How to perform an SQLite query within an Android application?

Try this, this works for my code name is a String:

cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
    REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
    ROLEID, NATIONALID, URL, IMAGEURL },                    
    LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);

How do I print colored output to the terminal in Python?

A side note: Windows users should run os.system('color') first, otherwise you would see some ANSI escape sequences rather than a colored output.

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

How to gracefully handle the SIGKILL signal in Java

I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).

This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.

But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).

As other users commented, the usage of shutdown hooks seems mandatory.

So, how do I would handle it?

Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).

As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.

So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Interrupting threads");
        Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
        for (Thread th : runningThreads) {
            if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.getClass().getName().startsWith("org.brutusin")) {
                System.out.println("Interrupting '" + th.getClass() + "' termination");
                th.interrupt();
            }
        }
        for (Thread th : runningThreads) {
            try {
                if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.isInterrupted()) {
                    System.out.println("Waiting '" + th.getName() + "' termination");
                    th.join();
                }
            } catch (InterruptedException ex) {
                System.out.println("Shutdown interrupted");
            }
        }
        System.out.println("Shutdown finished");
    }
});

Complete test application at github: https://github.com/idelvall/kill-test

Can you pass parameters to an AngularJS controller on creation?

I didn't really like any of the solutions here for my particular use case, so I figured I'd post what I did because I didn't see it here.

I simply wanted to use a controller more like a directive, within a ng-repeat loop:

<div ng-repeat="objParameter in [{id:'a'},{id:'b'},{id:'c'}]">
  <div ng-controller="DirectiveLikeController as ctrl"></div>
</div>

Now, in order to access the objParameter on creation within each DirectiveLikeController (or to get the up-to-date objParameter at ANY time), all I need to do is inject $scope and call $scope.$eval('objParameter'):

var app = angular.module('myapp', []);
app.controller('DirectiveLikeController',['$scope'], function($scope) {
   //print 'a' for the 1st instance, 'b' for the 2nd instance, and 'c' for the 3rd.
   console.log($scope.$eval('objParameter').id); 
});

The only real downside that I see is that it requires the parent controller to know that the parameter is named objParameter.

How to implement drop down list in flutter?

When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:

dropdown_string_button.dart

import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage: 
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
  DropdownStringButton({
    Key key, @required List<String> items, value, hint, disabledHint,
    @required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
    isExpanded = false, }) : 
    assert(items == null || value == null || items.where((String item) => item == value).length == 1),
        super(
          key: key,
          items: items.map((String item) {
            return DropdownMenuItem<String>(child: Text(item), value: item);
          }).toList(),
        value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
        elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
        isExpanded: isExpanded,
        );
    }

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

Difference between const reference and normal parameter

With

 void DoWork(int n);

n is a copy of the value of the actual parameter, and it is legal to change the value of n within the function. With

void DoWork(const int &n);

n is a reference to the actual parameter, and it is not legal to change its value.

Installing Node.js (and npm) on Windows 10

Everything should be installed in %appdata% (C:\Users\\AppData\Roaming), not 'program files'.

Here's why...

The default MSI installer puts Node and the NPM that comes with it in 'program files' and adds this to the system path, but it sets the user path for NPM to %appdata% (c:\users[username]\appdata\roaming) since the user doesn't have sufficient priveleges to write to 'program files'.

This creates a mess as all modules go into %appdata%, and when you upgrade NPM itself - which NPM themselves recommend you do right away - you end up with two copies: the original still in 'program files' since NPM can't erase that, and the new one inn %appdata%.

Even worse, if you mistakenly perform NPM operations as admin (much easier on Windows then on *nix) then it will operate on the 'program files' copy of NPM node_modules. Potentially a real mess.

So, when you run the installer simply point it to %appdata% and avoid all this.

And note that this isn't anything wierd - it’s what would happen if you ran the installer with just user priveleges.

Constantly print Subprocess output while process is running

For anyone trying the answers to this question to get the stdout from a Python script note that Python buffers its stdout, and therefore it may take a while to see the stdout.

This can be rectified by adding the following after each stdout write in the target script:

sys.stdout.flush()

How do I calculate a trendline for a graph?

Given that the trendline is straight, find the slope by choosing any two points and calculating:

(A) slope = (y1-y2)/(x1-x2)

Then you need to find the offset for the line. The line is specified by the equation:

(B) y = offset + slope*x

So you need to solve for offset. Pick any point on the line, and solve for offset:

(C) offset = y - (slope*x)

Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort.

If your line isn't straight then you'll need to look into Curve fitting, or Least Squares Fitting - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like.

Also, if this is a one-off, use Excel.

Count number of matches of a regex in Javascript

how about like this

function isint(str){
    if(str.match(/\d/g).length==str.length){
        return true;
    }
    else {
         return false
    }
}

What is this Javascript "require"?

Necromancing.
IMHO, the existing answers leave much to be desired.

It's very simple:
Require is simply a (non-standard) function defined at global scope.
(window in browser, global in NodeJS).

Now, as such, to answer the question "what is require", we "simply" need to know what this function does.
This is perhaps best explained with code.

Here's a simple implementation by Michele Nasti, the code you can find on his github page.

Basically, let's call our minimalisc require function myRequire:

function myRequire(name) 
{
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequire.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = fs.readFileSync(name, 'utf8');
        let module = { exports: {} };
        myRequire.cache[name] = module;
        let wrapper = Function("require, exports, module", code);
        wrapper(myRequire, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequire.cache[name].exports;
}
myRequire.cache = Object.create(null);
window.require = myRequire;
const stuff = window.require('./main.js');
console.log(stuff);

Now you notice, the object "fs" is used here.
For simplicity's sake, Michele just imported the NodeJS fs module:

const fs = require('fs');

Which wouldn't be necessary.
So in the browser, you could make a simple implementation of require with a SYNCHRONOUS XmlHttpRequest:

const fs = {
    file: `
    // module.exports = \"Hello World\";
        
    module.exports = function(){ return 5*3;};
    
    `
    , getFile(fileName: string, encoding: string): string
    {
        // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
        let client = new XMLHttpRequest();
        // client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

        // open(method, url, async)
        client.open("GET", fileName, false);
        client.send();
        if (client.status === 200)
            return client.responseText;

        return null;
    }


    , readFileSync: function (fileName: string, encoding: string): string
    {
        // this.getFile(fileName, encoding);
        return this.file; // Example, getFile would fetch this file 
    }
};

Basically, what require thus does, is download a JavaScript-file, eval it in an anonymous namespace (aka Function), with the global parameters "require", "exports" and "module", and return the exports, meaning an object's public functions and properties.

Note that this evaluation is recursive: you require files, which themselfs can require files.

This way, all "global" variables used in your module are variables in the require-wrapper-function namespace, and don't pollute the global scope with unwanted variables.

Also, this way, you can reuse code without depending on namespaces, so you get "modularity" in JavaScript. "modularity" in quotes, because this is not exactly true, though, because you can still write window.bla, and hence still pollute the global scope... Also, this establishes a separation between private and public functions, the public functions being the exports.

Now instead of saying

module.exports = function(){ return 5*3;};

You can also say:

function privateSomething()
{
    return 42:
}


function privateSomething2()
{
    return 21:
}


module.exports = {
      getRandomNumber: privateSomething
     ,getHalfRandomNumber: privateSomething2
};

and return an object.

Also, because your modules get evaluated in a function with parameters "require", "exports" and "module", your modules can use the undeclared variables "require", "exports" and "module", which might be startling at first. The require parameter there is of course a ByVal pointer to the require function saved into a variable.
Cool, right ?
Seen this way, require looses its magic, and becomes simple.
Now, the real require-function will do a few more checks and quirks, of course, but this is the essence of what that boils down to.

Also, in 2020, you should use the ECMA implementations instead of require:

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";

And if you need a dynamic non-static import (e.g. load a polyfill based on browser-type), there is the ECMA-import function/keyword:

var promise = import("module-name");

note that import is not synchronous like require.
Instead, import is a promise, so

var something = require("something");

becomes

var something = await import("something");

because import returns a promise (asynchronous).

So basically, unlike require, import replaces fs.readFileSync with fs.readFileAsync.

async readFileAsync(fileName, encoding) 
{
    const textDecoder = new TextDecoder(encoding);
    // textDecoder.ignoreBOM = true;
    const response = await fetch(fileName);
    console.log(response.ok);
    console.log(response.status);
    console.log(response.statusText);
    // let json = await response.json();
    // let txt = await response.text();
    // let blo:Blob = response.blob();
    // let ab:ArrayBuffer = await response.arrayBuffer();
    // let fd = await response.formData()
    // Read file almost by line
    // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read#Example_2_-_handling_text_line_by_line
    let buffer = await response.arrayBuffer();
    let file = textDecoder.decode(buffer);
    return file;
} // End Function readFileAsync

This of course requires the import-function to be async as well.

"use strict";
async function myRequireAsync(name) {
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequireAsync.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = await fs.readFileAsync(name, 'utf8');
        let module = { exports: {} };
        myRequireAsync.cache[name] = module;
        let wrapper = Function("asyncRequire, exports, module", code);
        await wrapper(myRequireAsync, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequireAsync.cache[name].exports;
}
myRequireAsync.cache = Object.create(null);
window.asyncRequire = myRequireAsync;
async () => {
    const asyncStuff = await window.asyncRequire('./main.js');
    console.log(asyncStuff);
};

Even better, right ?
Well yea, except that there is no ECMA-way to dynamically import synchronously (without promise).

Now, to understand the repercussions, you absolutely might want to read up on promises/async-await here, if you don't know what that is.

But very simply put, if a function returns a promise, it can be "awaited":

function sleep (fn, par) 
{
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}


var fileList = await sleep(listFiles, nextPageToken)

Which is nice way to make asynchronous code look synchronous.
Note that if you want to use async await in a function, that function must be declared async.

async function doSomethingAsync()
{
    var fileList = await sleep(listFiles, nextPageToken)
}

And also please note that in JavaScript, there is no way to call an async function (blockingly) from a synchronous one (the ones you know). So if you want to use await (aka ECMA-import), all your code needs to be async, which most likely is a problem, if everything isn't already async...

An example of where this simplified implementation of require fails, is when you require a file that is not valid JavaScript, e.g. when you require css, html, txt, svg and images or other binary files.
And it's easy to see why:
If you e.g. put HTML into a JavaScript function body, you of course rightfully get

SyntaxError: Unexpected token '<'

because of Function("bla", "<doctype...")

Now, if you wanted to extend this to for example include non-modules, you could just check the downloaded file-contents with for code.indexOf("module.exports") == -1, and then e.g. eval("jquery content") instead of Func (which works fine as long as you're in the browser). Since downloads with Fetch/XmlHttpRequests are subject to the same-origin-policy, and integrity is ensured by SSL/TLS, the use of eval here is rather harmless, provided you checked the JS files before you added them to your site, but that much should be standard-operating-procedure.

Note that there are several implementations of require-like functionality:

How do function pointers in C work?

Function pointers in C

Let's start with a basic function which we will be pointing to:

int addInt(int n, int m) {
    return n+m;
}

First thing, let's define a pointer to a function which receives 2 ints and returns an int:

int (*functionPtr)(int,int);

Now we can safely point to our function:

functionPtr = &addInt;

Now that we have a pointer to the function, let's use it:

int sum = (*functionPtr)(2, 3); // sum == 5

Passing the pointer to another function is basically the same:

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

We can use function pointers in return values as well (try to keep up, it gets messy):

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

But it's much nicer to use a typedef:

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

check if variable empty

here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

<?php
    $val = 0;
    //evaluates to true because $var is empty
    if (empty($val)) {
        echo '$val is either 0, empty, or not set at all';
    }
    //evaluates to true because $VAR IS SET
    if (isset($val)) {
        echo '$val is set even though it is empty';
    }
    ?>

Checking if a string array contains a value, and if so, getting its position

string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};          
string[] fooArray = y.Split(whitespace);  // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };

for (int i = 0; i < target.Length; i++)
{
    string v = target[i];
    string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
    //
    if (results != null)
    { MessageBox.Show(results); }

}

Angular2 disable button

If you have a form then the following is also possible:

<form #f="ngForm">
    <input name="myfield" type="text" minlenght="3" required ngModel>
    <button type="submit" [disabled]="!f.valid">Submit</button>
</form>

Demo here: http://plnkr.co/edit/Xm2dCwqB9p6WygrquUGh?p=preview&open=app%2Fapp.component.ts

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

Generating a WSDL from an XSD file

You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.

These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types> tag.

(thanks to Cheeso for pointing out my inaccurate usage of terms)

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

Can Android Studio be used to run standard Java projects?

on Android Studio 4.0 and above, you will get an option readily on the IDE,a green run icon to run the related main() class.

enter image description here

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

Truststore and Keystore Definitions

You may also be interested in the write-up from Sun, as part of the standard JSSE documentation:

http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#Stores

Typically, the trust store is used to store only public keys, for verification purposes, such as with X.509 authentication. For manageability purposes, it's quite common for admins or developers to simply conflate the two into a single store.

cartesian product in pandas

You could start by taking the Cartesian product of df1.col1 and df2.col3, then merge back to df1 to get col2.

Here's a general Cartesian product function which takes a dictionary of lists:

def cartesian_product(d):
    index = pd.MultiIndex.from_product(d.values(), names=d.keys())
    return pd.DataFrame(index=index).reset_index()

Apply as:

res = cartesian_product({'col1': df1.col1, 'col3': df2.col3})
pd.merge(res, df1, on='col1')
#  col1 col3 col2
# 0   1    5    3
# 1   1    6    3
# 2   2    5    4
# 3   2    6    4

Eclipse - debugger doesn't stop at breakpoint

Remove all breakpoints and re-add them.

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

What are the differences between a pointer variable and a reference variable in C++?

This program might help in comprehending the answer of the question. This is a simple program of a reference "j" and a pointer "ptr" pointing to variable "x".

#include<iostream>

using namespace std;

int main()
{
int *ptr=0, x=9; // pointer and variable declaration
ptr=&x; // pointer to variable "x"
int & j=x; // reference declaration; reference to variable "x"

cout << "x=" << x << endl;

cout << "&x=" << &x << endl;

cout << "j=" << j << endl;

cout << "&j=" << &j << endl;

cout << "*ptr=" << *ptr << endl;

cout << "ptr=" << ptr << endl;

cout << "&ptr=" << &ptr << endl;
    getch();
}

Run the program and have a look at the output and you'll understand.

Also, spare 10 minutes and watch this video: https://www.youtube.com/watch?v=rlJrrGV0iOg

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

Examples:

class Dog 
{ 
public:
    barkAt( const std::string& pOtherDog ); // const reference
    barkAt( std::string pOtherDog ); // value
};

const & is generally best. You don't incur the construction and destruction penalty. If the reference isn't const your interface is suggesting that it will change the passed in data.

Remove padding from columns in Bootstrap 3

Building up on Vitaliy Silin's answer. Covering not only cases where we do not want padding at all, but also cases where we have standard size paddings.

See the live conversion of this code to CSS on sassmeister.com

@mixin padding($side, $size) {
    $padding-size : 0;
    @if $size == 'xs' { $padding-size : 5px; }
    @else if $size == 's' { $padding-size : 10px; }
    @else if $size == 'm' { $padding-size : 15px; }
    @else if $size == 'l' { $padding-size : 20px; }

    @if $side == 'all' {
        .padding--#{$size} {
            padding: $padding-size !important;
        }
    } @else {
        .padding-#{$side}--#{$size} {
            padding-#{$side}: $padding-size !important;
        }
    }
}

$sides-list: all top right bottom left;
$sizes-list: none xs s m l;
@each $current-side in $sides-list {
  @each $current-size in $sizes-list {
    @include padding($current-side,$current-size);
  }
}

This then outputs:

.padding--none {
  padding: 0 !important;
}

.padding--xs {
  padding: 5px !important;
}

.padding--s {
  padding: 10px !important;
}

.padding--m {
  padding: 15px !important;
}

.padding--l {
  padding: 20px !important;
}

.padding-top--none {
  padding-top: 0 !important;
}

.padding-top--xs {
  padding-top: 5px !important;
}

.padding-top--s {
  padding-top: 10px !important;
}

.padding-top--m {
  padding-top: 15px !important;
}

.padding-top--l {
  padding-top: 20px !important;
}

.padding-right--none {
  padding-right: 0 !important;
}

.padding-right--xs {
  padding-right: 5px !important;
}

.padding-right--s {
  padding-right: 10px !important;
}

.padding-right--m {
  padding-right: 15px !important;
}

.padding-right--l {
  padding-right: 20px !important;
}

.padding-bottom--none {
  padding-bottom: 0 !important;
}

.padding-bottom--xs {
  padding-bottom: 5px !important;
}

.padding-bottom--s {
  padding-bottom: 10px !important;
}

.padding-bottom--m {
  padding-bottom: 15px !important;
}

.padding-bottom--l {
  padding-bottom: 20px !important;
}

.padding-left--none {
  padding-left: 0 !important;
}

.padding-left--xs {
  padding-left: 5px !important;
}

.padding-left--s {
  padding-left: 10px !important;
}

.padding-left--m {
  padding-left: 15px !important;
}

.padding-left--l {
  padding-left: 20px !important;
}

jQuery ajax request with json response, how to?

You need to call the

$.parseJSON();

For example:

...
success: function(data){
       var json = $.parseJSON(data); // create an object with the key of the array
       alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
    },
    error: function(data){
       var json = $.parseJSON(data);
       alert(json.error);
    } ...

see this in http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

What are the applications of binary trees?

A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. In a binary tree a degree of every node is maximum two.

Binary Tree

Binary trees are useful, because as you can see in the picture, if you want to find any node in the tree, you only have to look a maximum of 6 times. If you wanted to search for node 24, for example, you would start at the root.

  • The root has a value of 31, which is greater than 24, so you go to the left node.
  • The left node has a value of 15, which is less than 24, so you go to the right node.
  • The right node has a value of 23, which is less than 24, so you go to the right node.
  • The right node has a value of 27, which is greater than 24, so you go to the left node.
  • The left node has a value of 25, which is greater than 24, so you go to the left node.
  • The node has a value of 24, which is the key we are looking for.

This search is illustrated below: Tree search

You can see that you can exclude half of the nodes of the entire tree on the first pass. and half of the left subtree on the second. This makes for very effective searches. If this was done on 4 billion elements, you would only have to search a maximum of 32 times. Therefore, the more elements contained in the tree, the more efficient your search can be.

Deletions can become complex. If the node has 0 or 1 child, then it's simply a matter of moving some pointers to exclude the one to be deleted. However, you can not easily delete a node with 2 children. So we take a short cut. Let's say we wanted to delete node 19.

Delete 1

Since trying to determine where to move the left and right pointers to is not easy, we find one to substitute it with. We go to the left sub-tree, and go as far right as we can go. This gives us the next greatest value of the node we want to delete.

Delete 3

Now we copy all of 18's contents, except for the left and right pointers, and delete the original 18 node.

Delete 4


To create these images, I implemented an AVL tree, a self balancing tree, so that at any point in time, the tree has at most one level of difference between the leaf nodes (nodes with no children). This keeps the tree from becoming skewed and maintains the maximum O(log n) search time, with the cost of a little more time required for insertions and deletions.

Here is a sample showing how my AVL tree has kept itself as compact and balanced as possible.

enter image description here

In a sorted array, lookups would still take O(log(n)), just like a tree, but random insertion and removal would take O(n) instead of the tree's O(log(n)). Some STL containers use these performance characteristics to their advantage so insertion and removal times take a maximum of O(log n), which is very fast. Some of these containers are map, multimap, set, and multiset.

Example code for an AVL tree can be found at http://ideone.com/MheW8

How to connect to SQL Server database from JavaScript in the browser?

A perfect working code..

    <script>
    var objConnection = new ActiveXObject("adodb.connection");
    var strConn = "driver={sql server};server=QITBLRQIPL030;database=adventureworks;uid=sa;password=12345";
    objConnection.Open(strConn);
    var rs = new ActiveXObject("ADODB.Recordset");
    var strQuery = "SELECT * FROM  Person.Address";
    rs.Open(strQuery, objConnection);
    rs.MoveFirst();
    while (!rs.EOF) {
        document.write(rs.fields(0) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        document.write(rs.fields(1) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        document.write(rs.fields(2) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    ");
        document.write(rs.fields(3) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    ");
        document.write(rs.fields(4) + "<br/>");
        rs.movenext();
    }
</script>

Service vs IntentService in the Android platform

I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'

One of the more important differences per example is that IntentService ends itself once it's done.

Some examples (quickly made up) could be;

IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.

Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.

How to align linearlayout to vertical center?

Use layout_gravity instead of gravity. layout_gravity tells the parent where it should be positioned, and gravity tells its child where they should be positioned.

<LinearLayout
    android:id="@+id/groupNumbers"
    android:orientation="horizontal"
    android:layout_gravity="center_vertical"
    android:layout_weight="0.7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

Hive ParseException - cannot recognize input near 'end' 'string'

I solved this issue by doing like that:

insert into my_table(my_field_0, ..., my_field_n) values(my_value_0, ..., my_value_n)

What is the difference between new/delete and malloc/free?

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

Automatically accept all SDK licences

After trying many the possible solutions mentioned by members from the community I just found there might have been different problems overtime so most of the solutions are outdated.

Currently, and as I posted in the Travis community, Travis should be accepting all the licenses by default, but it kept complaining about not accepting the licenses 27.0.3 which shouldn't happen.

Adding:

before_install:
  - yes | sdkmanager "build-tools;27.0.3"

should fix the problem, we we would be able to even use an a 3.+ version of Android Gradle Tools without needing to even declare what version of build-tools we are using:

android:
  components:
    # Use the latest revision of Android SDK Tools
    - tools
    - platform-tools
    - tools

    # The SDK version used to compile your project
    - android-${ANDROID_API}
    # - build-tools-28.0.3    # WE DONT NEED THIS ANYMORE FROM AGP 3.+

    # Additional components
    - extra-google-google_play_services
    - extra-google-m2repository
    - addon-google_apis-google-${ANDROID_API}

This works as October 29th, 2018. Travis might make changes in the future so good luck with that!

jQuery/JavaScript: accessing contents of an iframe

You can use window.postMessage to call a function between page and his iframe (cross domain or not).

Documentation

page.html

<!DOCTYPE html>
<html>
<head>
    <title>Page with an iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'page',
        variable:'This is the page.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    function iframeReady(iframe) {
        if(iframe.contentWindow.postMessage) {
            iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
        }
    }
    </script>
</head>
<body>
    <h1>Page with an iframe</h1>
    <iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

How to get the indexpath.row when an element is activated?

For Swift2.1

I found a way to do it, hopefully, it'll help.

let point = tableView.convertPoint(CGPoint.zero, fromView: sender)

    guard let indexPath = tableView.indexPathForRowAtPoint(point) else {
        fatalError("can't find point in tableView")
    }

Adding script tag to React/JSX

A bit late to the party but I decided to create my own one after looking at @Alex Macmillan answers and that was by passing two extra parameters; the position in which to place the scripts such as or and setting up the async to true/false, here it is:

import { useEffect } from 'react';

const useScript = (url, position, async) => {
  useEffect(() => {
    const placement = document.querySelector(position);
    const script = document.createElement('script');

    script.src = url;
    script.async = typeof async === 'undefined' ? true : async;

    placement.appendChild(script);

    return () => {
      placement.removeChild(script);
    };
  }, [url]);
};

export default useScript;

The way to call it is exactly the same as shown in the accepted answer of this post but with two extra(again) parameters:

// First string is your URL
// Second string can be head or body
// Third parameter is true or false.
useScript("string", "string", bool);

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

ADB No Devices Found

i had the same problem now it's fixed and he is the how: go to device manager update android driver by using windows updates then go to move app to sd manually from phone

Check to see if python script is running

Rather than developing your own PID file solution (which has more subtleties and corner cases than you might think), have a look at supervisord -- this is a process control system that makes it easy to wrap job control and daemon behaviors around an existing Python script.

Detecting when the 'back' button is pressed on a navbar

As purrrminator says, the answer by elitalon is not completely right, since your stuff would be executed even when popping the controller programmatically.

The solution I have found so far is not very nice, but it works for me. Besides what elitalon said, I also check whether I'm popping programmatically or not:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if ((self.isMovingFromParentViewController || self.isBeingDismissed)
      && !self.isPoppingProgrammatically) {
    // Do your stuff here
  }
}

You have to add that property to your controller and set it to YES before popping programmatically:

self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];

Thanks for your help!

in python how do I convert a single digit number into a double digits string?

>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>> 

It is that simple

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Do you have the line

apply plugin: 'com.google.gms.google-services' 

line at the bottom of your app's build.gradle file?

I saw some errors when it was on the top and as it's written here, it should be at the bottom.

How do I clone a subdirectory only of a Git repository?

If you never plan to interact with the repository from which you cloned, you can do a full git clone and rewrite your repository using git filter-branch --subdirectory-filter. This way, at least the history will be preserved.

Get difference between two lists

Here is an simple way to distinguish two lists (whatever the contents are), you can get the result as shown below :

>>> from sets import Set
>>>
>>> l1 = ['xvda', False, 'xvdbb', 12, 'xvdbc']
>>> l2 = ['xvda', 'xvdbb', 'xvdbc', 'xvdbd', None]
>>>
>>> Set(l1).symmetric_difference(Set(l2))
Set([False, 'xvdbd', None, 12])

Hope this will helpful.

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

How do I push a new local branch to a remote Git repository and track it too?

Simply put, to create a new local branch, do:

git branch <branch-name>

To push it to the remote repository, do:

git push -u origin <branch-name>

How to select all elements with a particular ID in jQuery?

I would use Different IDs but assign each DIV the same class.

<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>

This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length


Ok what about adding multiple classes to each countdown timer. IE:

<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>

That way you get the best of both worlds. It even allows repeat 'IDS'

how to pass parameter from @Url.Action to controller function

Try this:

public ActionResult CreatePerson(int id) //controller 

window.location.href = "@Url.Action("CreatePerson", "Person")?Id='+Id+'";

it's working fine passing parameter.

How to fill in proxy information in cntlm config file?

Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"

e.g pip install --proxy=localhost:3128 matplotlib

Visit this link to see full details.

Named capturing groups in JavaScript regex?

Another possible solution: create an object containing the group names and indexes.

var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };

Then, use the object keys to reference the groups:

var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];

This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.

Environment variables in Eclipse

You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.

Select the JRE you use for running programs in Eclipse

Sending the value for hadoop.home.dir property as a VM argument

How to get VM arguments from inside of Java application?

With this code you can get the JVM arguments:

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();

Add x and y labels to a pandas plot

You can use do it like this:

import matplotlib.pyplot as plt 
import pandas as pd

plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
         title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()

Obviously you have to replace the strings 'xlabel' and 'ylabel' with what you want them to be.

Convert String[] to comma separated string in java

i use this

public static String convertToCommaSeparated(String[] strings) {
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; strings != null && i < strings.length; i++) {
        sb.append(strings[i]);
        if (i < strings.length - 1) {
            sb.append(',');
        }
    }
    return sb.toString();
}

Could not load file or assembly '' or one of its dependencies

Clean the solution and then right click on the project and select Package

Here increment the Assembly and Assembly file version and rebuild.

enter image description here

If that does not work,

1 - Open the solution in file Explorer.

2 - Close Visual Studio.

3 - Remove all bin and obj folders.

4 - Reopen the project and build it.

Convert object string to JSON

There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:

var jsonify = (function(div){
  return function(json){
    div.setAttribute('onclick', 'this.__json__ = ' + json);
    div.click();
    return div.__json__;
  }
})(document.createElement('div'));

// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)

Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)

Terminal Commands: For loop with echo

for ((i=0; i<=1000; i++)); do
    echo "http://example.com/$i.jpg"
done

Passing a string array as a parameter to a function java

I think you forget to register the parameter as String[]

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

Calling Objective-C method from C++ member function?

You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include EAGLView.h (you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like.

How to scroll to specific item using jQuery?

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');

Determining if a number is prime

Someone above had the following.

bool check_prime(int num) {
for (int i = num - 1; i > 1; i--) {
    if ((num % i) == 0)
        return false;
}
return true;
}

This mostly worked. I just tested it in Visual Studio 2017. It would say that anything less than 2 was also prime (so 1, 0, -1, etc.)

Here is a slight modification to correct this.

bool check_prime(int number)
{
    if (number > 1)
    {
        for (int i = number - 1; i > 1; i--)
        {
            if ((number % i) == 0)
                return false;
        }
        return true;
    }
    return false;
}

Eclipse - java.lang.ClassNotFoundException

That means your pom.xml has unresolved issues. Open the problems view solve accordingly. Then you will be able to run the test cases successfully without encountering the classnotfoundexception.

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

How to prevent SIGPIPEs (or handle them properly)

Another method is to change the socket so it never generates SIGPIPE on write(). This is more convenient in libraries, where you might not want a global signal handler for SIGPIPE.

On most BSD-based (MacOS, FreeBSD...) systems, (assuming you are using C/C++), you can do this with:

int set = 1;
setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));

With this in effect, instead of the SIGPIPE signal being generated, EPIPE will be returned.

How to shift a column in Pandas DataFrame

In [18]: a
Out[18]: 
   x1  x2
0   0   5
1   1   6
2   2   7
3   3   8
4   4   9

In [19]: a['x2'] = a.x2.shift(1)

In [20]: a
Out[20]: 
   x1  x2
0   0 NaN
1   1   5
2   2   6
3   3   7
4   4   8

rotate image with css

Give the parent a style of overflow: hidden. If it is overlapping sibling elements, you will have to put it inside of a container with a fixed height/width and give that a style of overflow: hidden.

How to iterate over a string in C?

You want:

for (i = 0; i < strlen(source); i++){

sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

char source[] = "This is an example.";

but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

int len = strlen( source );
for (i = 0; i < len; i++){

or rewrite the loop:

for (i = 0; source[i] != 0; i++){

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

Use :hover to modify the css of another class?

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:

How to make promises work in IE11

You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.

used like: window.Promise https://www.npmjs.com/package/promise-polyfill

If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill

Tick symbol in HTML/XHTML

Coming very late to the party, I found that &check; (✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.

Disable all dialog boxes in Excel while running VB script?

From Excel Macro Security - www.excelfunctions.net:

Macro Security in Excel 2007, 2010 & 2013:

.....

The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :

'Disable all macros without notification'

  • This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Disable all macros with notification'

  • This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.

'Disable all macros except digitally signed macros'

  • This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Enable all macros'

  • This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.

If you trust the macros and are ok with enabling them, select this option:

'Enable all macros'

and this dialog box should not show up for macros.

As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.

Eclipse error "Could not find or load main class"

Had the same problem, struggling with it for a while: couldn't find main class.

I did Project -> Clean -> Clean all Projects

Cleaned everything, and tada, it compiled!

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

GCC -fPIC option

Adding further...

Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)

So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.

But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.

So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.

So they always have to use the relative addressing mode and hence fpic option.

"No such file or directory" but it exists

Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.

In my case, this happened due to working on Windows and uploading to Unix server for execution.

Simulate delayed and dropped packets on Linux

This tutorial on networking physics simulations contains a C++ class in the sample code for simulating latency and packet loss in a UDP connection and may be of guidance. See the public latency and packetLoss variables of the Connection class found in the Connection.h file of the downloadable source code.

How can I run another application within a panel of my C# program?

If you want to run notepad inside your app you would probably be better of with a text editor component. There's obviously a basic text box that comes with WinForms, but I suspect more advanced components that offer Notepad functionality (or better) can be found on the interweb.

Find a class somewhere inside dozens of JAR files?

To locate jars that match a given string:

find . -name \*.jar -exec grep -l YOUR_CLASSNAME {} \;

Java Scanner class reading strings

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.

Here a small change that you can do:

int nnames;
    String names[];

    System.out.print("How many names are you going to save: ");
    Scanner in = new Scanner(System.in);
    nnames = Integer.parseInt(in.nextLine());
    names = new String[nnames];

    for (int i = 0; i < names.length; i++){
            System.out.print("Type a name: ");
            names[i] = in.nextLine();
    }

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

Java error: Only a type can be imported. XYZ resolves to a package

I was getting the same error and nothing was wrong with my java files and packages. Later I noticed that the folder name WEB-INF was written like this "WEB_INF". So correcting just the folder name solved the issue

MySQL trigger if condition exists

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

How to print a list in Python "nicely"

import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))

Output:

[
    "one",
    "two",
    "three",
    "four"
]

Top 5 time-consuming SQL queries in Oracle

I found this SQL statement to be a useful place to start (sorry I can't attribute this to the original author; I found it somewhere on the internet):

SELECT * FROM
(SELECT
    sql_fulltext,
    sql_id,
    elapsed_time,
    child_number,
    disk_reads,
    executions,
    first_load_time,
    last_load_time
FROM    v$sql
ORDER BY elapsed_time DESC)
WHERE ROWNUM < 10
/

This finds the top SQL statements that are currently stored in the SQL cache ordered by elapsed time. Statements will disappear from the cache over time, so it might be no good trying to diagnose last night's batch job when you roll into work at midday.

You can also try ordering by disk_reads and executions. Executions is useful because some poor applications send the same SQL statement way too many times. This SQL assumes you use bind variables correctly.

Then, you can take the sql_id and child_number of a statement and feed them into this baby:-

SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id', &child));

This shows the actual plan from the SQL cache and the full text of the SQL.

How do I declare a two dimensional array?

And for me the argument about whether an array should be sparse or not depends on the context.

For example, if $a[6][9] is not populated is the equivalent to $a[6][9] being populated with for example with "" or 0.

yii2 redirect in controller action does not work?

If you are trying to do redirect in beforeAction() you should use send() method

 return $this->redirect('/some/url',302)->send();

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

How do I Search/Find and Replace in a standard string?

Why not return a modified string?

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

Is it possible to have different Git configuration for different projects?

You can customize a project's Git config by changing the repository specific configuration file (i.e. /path/to/repo/.git/config). BTW, git config writes to this file by default:

cd /path/to/repo
git config user.name 'John Doe'  # sets user.name locally for the repo

I prefer to create separate profiles for different projects (e.g. in ~/.gitconfig.d/) and then include them in the repository's config file:

cd /path/to/repo
git config include.path '~/.gitconfig.d/myproject.conf'

This works well if you need to use the same set of options in multiple repos that belong to a single project. You can also set up shell aliases or a custom Git command to manipulate the profiles.

How to make a class JSON serializable

jaraco gave a pretty neat answer. I needed to fix some minor things, but this works:

Code

# Your custom class
class MyCustom(object):
    def __json__(self):
        return {
            'a': self.a,
            'b': self.b,
            '__python__': 'mymodule.submodule:MyCustom.from_json',
        }

    to_json = __json__  # supported by simplejson

    @classmethod
    def from_json(cls, json):
        obj = cls()
        obj.a = json['a']
        obj.b = json['b']
        return obj

# Dumping and loading
import simplejson

obj = MyCustom()
obj.a = 3
obj.b = 4

json = simplejson.dumps(obj, for_json=True)

# Two-step loading
obj2_dict = simplejson.loads(json)
obj2 = MyCustom.from_json(obj2_dict)

# Make sure we have the correct thing
assert isinstance(obj2, MyCustom)
assert obj2.__dict__ == obj.__dict__

Note that we need two steps for loading. For now, the __python__ property is not used.

How common is this?

Using the method of AlJohri, I check popularity of approaches:

Serialization (Python -> JSON):

Deserialization (JSON -> Python):

jQuery form input select by id

You can just target the id directly:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

var value = $('#a #b').val();

Where is `%p` useful with printf?

They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer.

Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.

Always use %p for pointers.

Stick button to right side of div

Use position property

style="position: absolute;right:0;top:0"

Using SQL LOADER in Oracle to import CSV file

Try this

load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)

In command prompt:

sqlldr system@databasename/password control='control file location'

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

How can two strings be concatenated?

help.search() is a handy function, e.g.

> help.search("concatenate")

will lead you to paste().

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

jQuery - Increase the value of a counter when a button is clicked

$(document).ready(function() {
var count = 0;

  $("#update").click(function() {
    count++;
    $("#counter").html("My current count is: "+count);
  }

});

<div id="counter"></div>

Open source PDF library for C/C++ application?

If you're brave and willing to roll your own, you could start with a PostScript library and augment it to deal with PDF, taking advantage of Adobe's free online PDF reference.

HTTP POST using JSON in Java

I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.

Solution for Google Endpoints.

  1. Request body must contains only JSON string, not name=value pair.
  2. Content type header must be set to "application/json".

    post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
                       "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
    
    
    
    public static void post(String url, String json ) throws Exception{
      String charset = "UTF-8"; 
      URLConnection connection = new URL(url).openConnection();
      connection.setDoOutput(true); // Triggers POST.
      connection.setRequestProperty("Accept-Charset", charset);
      connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    
      try (OutputStream output = connection.getOutputStream()) {
        output.write(json.getBytes(charset));
      }
    
      InputStream response = connection.getInputStream();
    }
    

    It sure can be done using HttpClient as well.

ImportError: No module named 'Queue'

import queue is lowercase q in Python 3.

Change Q to q and it will be fine.

(See code in https://stackoverflow.com/a/29688081/632951 for smart switching.)

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

How to Query Database Name in Oracle SQL Developer?

try this:

select * from global_name;

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

in my case, I had a line Class.forName("com.mysql.jdbc.Driver"); after removing this line code works fine if you have any line for loading "com.mysql.jdbc.Driver" remove it, it doesn't require any more

Understanding __getitem__ method

Cong Ma does a good job of explaining what __getitem__ is used for - but I want to give you an example which might be useful. Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :

Without using __getitem__ we would have a class like this :

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def occupy(self, floor_number, data):
          self._floors[floor_number] = data
     def get_floor_data(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )

We could however use __getitem__ (and its counterpart __setitem__) to make the usage of the Building class 'nicer'.

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def __setitem__(self, floor_number, data):
          self._floors[floor_number] = data
     def __getitem__(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )

Whether you use __setitem__ like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

How to check if a specified key exists in a given S3 bucket using Java

Alternatively you can use Minio-Java client library, its Open Source and compatible with AWS S3 API.

You can use Minio-Java StatObject.java examples for the same.

import io.minio.MinioClient;
import io.minio.errors.MinioException;

import java.io.InputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;

import org.xmlpull.v1.XmlPullParserException;


public class GetObject {
  public static void main(String[] args)
    throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException, MinioException {
    // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are
    // dummy values, please replace them with original values.
    // Set s3 endpoint, region is calculated automatically
    MinioClient s3Client = new MinioClient("https://s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY");
    InputStream stream = s3Client.getObject("my-bucketname", "my-objectname");

    byte[] buf = new byte[16384];
    int bytesRead;
    while ((bytesRead = stream.read(buf, 0, buf.length)) >= 0) {
      System.out.println(new String(buf, 0, bytesRead));
    }

    stream.close();
  }
}

I hope it helps.

Disclaimer : I work for Minio

Is the sizeof(some pointer) always equal to four?

The reason the size of your pointer is 4 bytes is because you are compiling for a 32-bit architecture. As FryGuy pointed out, on a 64-bit architecture you would see 8.

"VT-x is not available" when I start my Virtual machine

Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?

Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.

Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.

C#: easiest way to populate a ListBox from a List

Is this what you are looking for:

myListBox.DataSource = MyList;

How to add a href link in PHP?

There is no need to invoke PHP for this. Just put it directly into the HTML:

<a href="http://www.example.com/">...

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

Zooming MKMapView to fit annotation pins?

Apple has added a new method for IOS 7 to simplify life a bit.

[mapView showAnnotations:yourAnnotationArray animated:YES];

You can easily pull from an array stored in the map view:

yourAnnotationArray = mapView.annotations;

and quickly adjust the camera too!

mapView.camera.altitude *= 1.4;

this won't work unless the user has iOS 7+ or OS X 10.9+ installed. check out custom animation here

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

How to make an HTTP request + basic auth in Swift

I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.

I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "[email protected]"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How to install SQL Server 2005 Express in Windows 8

I had a different experience loading SQL Server 2005 Express on Windows 8. I was using the installer that already had SP4 applied so maybe that explains the difference. The first error I received was when Setup tried to start the SQL VSS Writer. I just told it to Ignore and it continued. I then ran into the same error Sohail had where the SQL Server service failed to start. There was no point in following the rest of Sohail's method since I already was using a SP4 version of SQLServr.exe and SQLOS.dll. Instead, I just canceled the install rebooted the machine and ran the install again. Everything ran fine the second time around.

The place I found Sohail's technique invaluable was when I needed to install SQL Server 2005 Standard on Windows Server 2012. We have a few new servers we're looking to roll out with Windows 2012 but we didn't feel the need to upgrade SQL Server since the 2005 version has all the functionality we need and the cost to license SQL 2012 on these boxes would have been a 5-figure sum.

I wound up tweaking Sohail's technique a bit by adding steps to revert the SQLServr.exe and SQLOS.dll files so that I could then apply SP4 fully. Below are all the steps I took starting from a scratch install of Windows Server 2012 Standard. I hope this helps anyone else looking to get a fully updated install of SQL Server 2005 x64 on this OS.

  1. Use Server Manger Add roles and features wizard to satisfy all of SQL's prerequisites:
    • Select the Web Server (IIS) Role
    • Add the following additional Web Server Role Services (note that some of these will automatically pull in others, just accept and move on):
      • HTTP Redirection
      • Windows Authentication
      • ASP.NET 3.5 (note that you'll need to tell the wizard to look in the \Sources\SxS folder of the Windows 2012 installation media for this to install properly; just click the link to "Specify an alternate source path" before clicking Install)
      • IIS 6 Metabase Compatibility
      • IIS 6 WMI Compatibility
  2. Start SQL Server 2005 Install, ignoring any compatibility warnings
    • If SQL Server service fails to start during setup, leave dialog up and do the following:
      • Backup SQLServr.exe and SQLOS.dll from C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn
      • Replace those two files from a working copy of SQL Server 2005 that already has had SP4 applied
      • Return to setup, hit Retry and setup will now run to completion.
      • Stop SQL Service and restore orignal versions of SQLServr.exe and SQLOS.dll (or else SP4 doesn't think it is needed in the next step)
  3. Install SQL Server 2005 SP4
  4. Install SQL Server 2005 SP4 Cumulative Hotfix 5069 (Windows Update wasn't offering this for some reason so I had to download and install manually)
  5. If you want the latest documentation, install the latest version of SQL Server 2005 Books Online.

ffprobe or avprobe not found. Please install one

  1. update your version of youtube-dl to the lastest as older version might not support palylists.

    sudo youtube-dl -U if u installed via .deb

    sudo pip install --upgrade youtube_dl via pip

  2. use this to download the playlist as an MP3 file

    youtube-dl --extract-audio --audio-format mp3 #url_to_playlist

Show a PDF files in users browser via PHP/Perl

    $url ="https://yourFile.pdf";
    $content = file_get_contents($url);

    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: inline; filename="YourFileName.pdf"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    ini_set('zlib.output_compression','0');

    die($content);

Tested and works fine. If you want the file to download instead, replace

    Content-Disposition: inline

with

    Content-Disposition: attachment

How to see the actual Oracle SQL statement that is being executed

On the data dictionary side there are a lot of tools you can use to such as Schema Spy

To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users

One thing to note that queries that use parameters will show up once with entries like

and TABLETYPE=’:b16’

while others that dont will show up multiple times such as:

and TABLETYPE=’MT’

An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)

SELECT 
 module, 
 sql_text, 
 username, 
 disk_reads_per_exec, 
 buffer_gets, 
 disk_reads, 
 parse_calls, 
 sorts, 
 executions, 
 rows_processed, 
 hit_ratio, 
 first_load_time, 
 sharable_mem, 
 persistent_mem, 
 runtime_mem, 
 cpu_time, 
 elapsed_time, 
 address, 
 hash_value 
FROM 
  (SELECT
   module, 
   sql_text , 
   u.username , 
   round((s.disk_reads/decode(s.executions,0,1, s.executions)),2)  disk_reads_per_exec, 
   s.disk_reads , 
   s.buffer_gets , 
   s.parse_calls , 
   s.sorts , 
   s.executions , 
   s.rows_processed , 
   100 - round(100 *  s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, 
   s.first_load_time , 
   sharable_mem , 
   persistent_mem , 
   runtime_mem, 
   cpu_time, 
   elapsed_time, 
   address, 
   hash_value 
  FROM
   sys.v_$sql s, 
   sys.all_users u 
  WHERE
   s.parsing_user_id=u.user_id 
   and UPPER(u.username) not in ('SYS','SYSTEM') 
  ORDER BY
   4 desc) 
WHERE
 rownum <= 20;

Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:

SELECT
 *
FROM
 sys.v_$sqltext
WHERE
 address = 'C0000000372B3C28'
 and hash_value = '1272580459'
ORDER BY 
 address, hash_value, command_type, piece
;

Execute a command line binary with Node.js

Now you can use shelljs ( from node v4 ) as follows :

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version')

How to ignore user's time zone and force Date() use specific time zone

You could use setUTCMilliseconds()

var _date = new Date();
_date.setUTCMilliseconds(1270544790922);

Dynamic Height Issue for UITableView Cells (Swift)

You should just set all constraints for TOP, BOTTOM and HEIGHT for each object on cell view/views and remove exists middle Y position if have. Because where you didn't this, puts artifacts on another views.

Convert string to Color in C#

(It would really have been nice if you'd mentioned which Color type you were interested in to start with...)

One simple way of doing this is to just build up a dictionary via reflection:

public static class Colors
{
    private static readonly Dictionary<string, Color> dictionary =
        typeof(Color).GetProperties(BindingFlags.Public | 
                                    BindingFlags.Static)
                     .Where(prop => prop.PropertyType == typeof(Color))
                     .ToDictionary(prop => prop.Name,
                                   prop => (Color) prop.GetValue(null, null)));

    public static Color FromName(string name)
    {
        // Adjust behaviour for lookup failure etc
        return dictionary[name];
    }
}

That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.

If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase as an extra argument in the ToDictionary call. You can easily add TryParse etc methods should you wish.

Of course, if you only need this in one place, don't bother with a separate class etc :)

Highlight a word with jQuery

You need to get the content of the p tag and replace all the dolors in it with the highlighted version.

You don't even need to have jQuery for this. :-)

Get device token for push notification

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
        }
    let token = tokenParts.joined()

    print("Token\(token)")
}

Cmake is not able to find Python-libraries

Even after adding -DPYTHON_INCLUDE_DIR and -DPYTHON_LIBRARY as suggested above, I was still facing the error Could NOT find PythonInterp. What solved it was adding -DPYTHON_EXECUTABLE:FILEPATH= to cmake as suggested in https://github.com/pybind/pybind11/issues/99#issuecomment-182071479:

cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))") \
-DPYTHON_EXECUTABLE:FILEPATH=`which python`

How do I hide a menu item in the actionbar?

You are trying to access a menu item from an activity, which dont have the access to scope. The call to find the menu item will return null, because the view is not binded with neither the activity nor the layout you are calling from.

The menu items are binded with items such as "Navigation Bar" which in turn are binded with the corresponding activity.

So initialize those views in activity (), and then access the menu items withing that views.

Navigation navView;
navView = findViewById(R.id.navigationView);

MenuItem item = navView.getMenu().findItem(R.id.item_hosting);
item.setVisible(false);

When and Why to use abstract classes/methods?

Typically one uses an abstract class to provide some incomplete functionality that will be fleshed out by concrete subclasses. It may provide methods that are used by its subclasses; it may also represent an intermediate node in the class hierarchy, to represent a common grouping of concrete subclasses, distinguishing them in some way from other subclasses of its superclass. Since an interface can't derive from a class, this is another situation where a class (abstract or otherwise) would be necessary, versus an interface.

A good rule of thumb is that only leaf nodes of a class hierarchy should ever be instantiated. Making non-leaf nodes abstract is an easy way of ensuring that.

When do we need curly braces around shell variables?

Curly braces are always needed for accessing array elements and carrying out brace expansion.

It's good to be not over-cautious and use {} for shell variable expansion even when there is no scope for ambiguity.

For example:

dir=log
prog=foo
path=/var/${dir}/${prog}      # excessive use of {}, not needed since / can't be a part of a shell variable name
logfile=${path}/${prog}.log   # same as above, . can't be a part of a shell variable name
path_copy=${path}             # {} is totally unnecessary
archive=${logfile}_arch       # {} is needed since _ can be a part of shell variable name

So, it is better to write the three lines as:

path=/var/$dir/$prog
logfile=$path/$prog.log
path_copy=$path

which is definitely more readable.

Since a variable name can't start with a digit, shell doesn't need {} around numbered variables (like $1, $2 etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {} in such contexts:

set app      # set $1 to app
fruit=$1le   # sets fruit to apple, but confusing
fruit=${1}le # sets fruit to apple, makes the intention clear

See:

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Media Queries: How to target desktop, tablet, and mobile?

Don't target specific devices or sizes!

The general wisdom is not to target specific devices or sizes, but to reframe the term 'breakpoint':

  • develop the site for mobile first using percentages or ems, not pixels,
  • then try it in a larger viewport and note where it begins to fail,
  • redesign the layout and add a CSS media query just to handle the broken parts,
  • repeat the process until you reach the next breakpoint.

You can use responsivepx.com to find the 'natural' breakpoints, as in 'breakpoints are dead' by Marc Drummond.

Use natural breakpoints

The 'breakpoints' then become the actual point at which your mobile design begins to 'break' i.e. cease to be usable or visually pleasing. Once you have a good working mobile site, without media queries, you can stop being concerned about specific sizes and simply add media queries that handle successively larger viewports.

If you're not trying to pin design to exact screen size, this approach works by removing the need to target specific devices. The integrity of the design itself at each breakpoint ensures that it will hold up at any size. In other words, if a menu/content section/whatever stops being usable at a certain size, design a breakpoint for that size, not for a specific device size.

See Lyza Gardner's post on behavioral breakpoints, and also Zeldman's post about Ethan Marcotte and how responsive web design evolved from the initial idea.

Use semantic markup

Further, the simpler and more semantic the DOM structure with nav, header, main, section, footer etc. (avoiding abominations like div class="header" with nested inner div tags) the easier it will be to engineer responsiveness, especially avoiding floats by using CSS Grid Layout (Sarah Drasner's grid generator is a great tool for this) and flexbox for arranging and re-ordering according to your RWD design plan.

Quick unix command to display specific lines in the middle of a file?

If your line number is 100 to read

head -100 filename | tail -1

Find all zero-byte files in directory and subdirectories

No, you don't have to bother grep.

find $dir -size 0 ! -name "*.xml"

How do I use raw_input in Python 3

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.

From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.

Use a command-prompt

When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Weeble\My Python Program>_

To run your program, type the following (substituting your script name):

    python myscript.py

...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.

Use IDLE

IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

How to get row from R data.frame

If you don't know the row number, but do know some values then you can use subset

x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
               ),
               .Names    = c("A", "B", "C"),
               class     = "data.frame",
               row.names = c(NA, -5L)
     )

subset(x, A ==5 & B==4.25 & C==4.5)

Set min-width in HTML table's <td>

<table style="border:2px solid #ddedde">
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
</table>

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

Predicate in Java

Adding up to what Micheal has said:

You can use Predicate as follows in filtering collections in java:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

Check if list is empty in C#

You should use a simple IF statement

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();

Angular 5, HTML, boolean on checkbox is checked

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

Here, record is the model for current row and status is boolean value.

Icons missing in jQuery UI

I found icons were not displaying due to a difference in the casing (ie upper case vs lower case). The CSS file was using "FFFFFF" while the actual file was using "ffffff". Icons displayed for me once I changed the case to match.

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

if you wanna remove attributes for all files in all folders on whole flash drive do this:

attrib -r -s -h /S /D

this command will remove attrubutes for all files folders and subfolders:

-read only -system file -is hidden -Processes matching files and all subfolders. -Processes folders as well

How to check null objects in jQuery

What about using "undefined"?

if (value != undefined){ // do stuff } 

How to create a RelativeLayout programmatically with two buttons one on top of the other?

I have written a quick example to demonstrate how to create a layout programmatically.

public class CodeLayout extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Creating a new RelativeLayout
        RelativeLayout relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

        // Creating a new TextView
        TextView tv = new TextView(this);
        tv.setText("Test");

        // Defining the layout parameters of the TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);

        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(tv);

        // Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
    }
}

In theory everything should be clear as it is commented. If you don't understand something just tell me.

How to get the list of all installed color schemes in Vim?

Try

set wildmenu
set wildmode=list:full
set wildcharm=<C-z>
let mapleader=','
nnoremap <leader>c :colorscheme <C-z><S-Tab>

in your ~/.vimrc.

The first two lines make possible matches appear as lists. You can use either or both.

The fourth line makes leader , instead of the default \.

The last line allows you to simply type ,c to get a list and a prompt to change your colorscheme.

The third line effectively allows for Tabs to appear in key maps.

(Of course, all of these strategies I've learned from the internet, and mostly SO, very recently.)

Which concurrent Queue implementation should I use in Java?

  1. SynchronousQueue ( Taken from another question )

SynchronousQueue is more of a handoff, whereas the LinkedBlockingQueue just allows a single element. The difference being that the put() call to a SynchronousQueue will not return until there is a corresponding take() call, but with a LinkedBlockingQueue of size 1, the put() call (to an empty queue) will return immediately. It's essentially the BlockingQueue implementation for when you don't really want a queue (you don't want to maintain any pending data).

  1. LinkedBlockingQueue (LinkedList Implementation but Not Exactly JDK Implementation of LinkedList It uses static inner class Node to maintain Links between elements )

Constructor for LinkedBlockingQueue

public LinkedBlockingQueue(int capacity) 
{
        if (capacity < = 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node< E >(null);   // Maintains a underlying linkedlist. ( Use when size is not known )
}

Node class Used to Maintain Links

static class Node<E> {
    E item;
    Node<E> next;
    Node(E x) { item = x; }
}

3 . ArrayBlockingQueue ( Array Implementation )

Constructor for ArrayBlockingQueue

public ArrayBlockingQueue(int capacity, boolean fair) 
{
            if (capacity < = 0)
                throw new IllegalArgumentException();
            this.items = new Object[capacity]; // Maintains a underlying array
            lock = new ReentrantLock(fair);
            notEmpty = lock.newCondition();
            notFull =  lock.newCondition();
}

IMHO Biggest Difference between ArrayBlockingQueue and LinkedBlockingQueue is clear from constructor one has underlying data structure Array and other linkedList.

ArrayBlockingQueue uses single-lock double condition algorithm and LinkedBlockingQueue is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock)

Php - testing if a radio button is selected and get the value

<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
    if (isset($_POST['radio'])) {
        $radio_input = $_POST['radio'];
        echo $radio_input;
    }
} else {

}
?>
<form action="radio.php" method="post">
   <input type="radio" name="radio" value="v1"/>
   <input type="radio" name="radio" value="v2"/>
   <input type="radio" name="radio" value="v3"/>
   <input type="radio" name="radio" value="v4"/>
   <input type="radio" name="radio" value="v5"/>
   <input type= "submit" name="submit"value="submit"/>
</form>

javascript: using a condition in switch case

See dmp's answer below. I'd delete this answer if I could, but it was accepted so this is the next best thing :)

You can't. JS Interpreters require you to compare against the switch statement (e.g. there is no "case when" statement). If you really want to do this, you can just make if(){ .. } else if(){ .. } blocks.

How can I select random files from a directory in bash?

Here's a script that uses GNU sort's random option:

ls |sort -R |tail -$N |while read file; do
    # Something involving $file, or you can leave
    # off the while to just get the filenames
done

How do you return a JSON object from a Java Servlet

Close to BalusC answer in 4 simple lines using Google Gson lib. Add this lines to the servlet method:

User objToSerialize = new User("Bill", "Gates");    
ServletOutputStream outputStream = response.getOutputStream();

response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));

Good luck!

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

var shiftDown = false;
this.onkeydown = function(evt){
    var evt2 = evt || window.event;
    var keyCode = evt2.keyCode || evt2.which;       
    if(keyCode==16)shiftDown = true;
}
this.onkeyup = function(){
    shiftDown = false;
}

demo

Try-catch speeding up my code?

I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

What do &lt; and &gt; stand for?

Others have noted the correct answer, but have not clearly explained the all-important reason:

  • why do we need this?

What do < and > stand for?

  • &lt; stands for the < sign. Just remember: lt == less than
  • &gt; stands for the > Just remember: gt == greater than

Why can’t we simply use the < and > characters in HTML?

  • This is because the > and < characters are ‘reserved’ characters in HTML.
  • HTML is a mark up language: The < and > are used to denote the starting and ending of different elements: e.g. <h1> and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use &lt; and &gt; and the browser will know exactly how to display it.