Programs & Examples On #Libpqxx

Libpqxx is the official C++ client API for PostgreSQL, the enterprise-strength open-source database software.

How to change identity column values programmatically?

I saw a good article which helped me out at the last moment .. I was trying to insert few rows in a table which had identity column but did it wrongly and have to delete back. Once I deleted the rows then my identity column got changed . I was trying to find an way to update the column which was inserted but - no luck. So, while searching on google found a link ..

  1. Deleted the columns which was wrongly inserted
  2. Use force insert using identity on/off (explained below)

http://beyondrelational.com/modules/2/blogs/28/posts/10337/sql-server-how-do-i-insert-an-explicit-value-into-an-identity-column-how-do-i-update-the-value-of-an.aspx

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

I started mongod in cmd,It threw error like C:\data\db\ not found. Created folder then typed mongod opened another cmd typed mongo it worked.

How do I list all cron jobs for all users?

If you check a cluster using NIS, the only way to see if a user has a crontab entry ist according to Matt's answer /var/spool/cron/tabs.

grep -v "#" -R  /var/spool/cron/tabs

Getting around the Max String size in a vba function?

I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:

Dim AString As String * 1024

which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.

This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.

Error: Local workspace file ('angular.json') could not be found

Well, I faced the same issue as soon as I updated my angular cli version.

Earlier I was using 1.7.4 and just now I upgraded it to angular cli 6.0.8.

To update Angular Cli global:

npm uninstall -g angular-cli
npm cache clean 
npm install -g @angular/cli@latest

To update Angular Cli dev:

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix audit issues after npm install:

npm audit fix

To fix the issue related to "angular.json":

ng update @angular/cli --migrate-only --from=1.7.4

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT distinct new com.model.referential.Asset(firefCode,firefDescription) FROM AssetClass ")
List<AssetClass> findDistinctAsset();

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Configuring Git over SSH to login once

Try ssh-add, you need ssh-agent to be running and holding your private key

(Ok, responding to the updated question, you first run ssh-keygen to generate a public and private key as Jefromi explained. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter ssh-agent as explained below.)

You want to be running ssh-agent in the background as you log in. Once you log in, the idea is to run ssh-add once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere.

All ssh-family commands1 will then consult the agent and automatically be able to use your private key.

On OSX (err, macOS), GNOME and KDE systems, ssh-agent is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.

Start here: man ssh-agent.

There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke ssh-add or ssh both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.

Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.

My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run ssh-add once. Try running ssh-add and see if it works, if so, then you just need to do that once per reboot.

My Cygwin system needed it done manually, so I did this in my .profile and I have .bashrc source .profile:

. .agent > /dev/null
ps -p $SSH_AGENT_PID | grep ssh-agent > /dev/null || {
        ssh-agent > .agent
        . .agent > /dev/null
}

The .agent file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to ps(1) the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run ssh-add and if it fails start an agent.


1. And even local and remote sudo with the right pam extension.

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

How to set image for bar button with swift?

I am using latest swift (2.1) and the answer (Dharmesh Kheni and jungledev) does not work for me. The image color was off (when setting in IB, it was blue and when setting directly in UIButton, it was black). It turns out I could create the same bar item with the following code:

let barButton = UIBarButtonItem(image: UIImage(named: "menu"), landscapeImagePhone: nil, style: .Done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton

Get a list of all threads currently running in Java

In the java console, hit Ctrl-Break. It will list all threads plus some information about the heap. This won't give you access to the objects of course. But it can be very helpful for debugging anyway.

Creating default object from empty value in PHP?

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

Using python's mock patch.object to change the return value of a method called within another method

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

How to extract img src, title and alt from html using php?

Here's A PHP Function I hobbled together from all of the above info for a similar purpose, namely adjusting image tag width and length properties on the fly ... a bit clunky, perhaps, but seems to work dependably:

function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {

// find image tags
preg_match_all('/<img[^>]+>/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER); 

// put image tags in a simpler array
$imagearray = array();
for ($i = 0; $i < count($rawimagearray); $i++) {
    array_push($imagearray, $rawimagearray[$i][0]);
}

// put image attributes in another array
$imageinfo = array();
foreach($imagearray as $img_tag) {

    preg_match_all('/(src|width|height)=("[^"]*")/i',$img_tag, $imageinfo[$img_tag]);
}

// combine everything into one array
$AllImageInfo = array();
foreach($imagearray as $img_tag) {

    $ImageSource = str_replace('"', '', $imageinfo[$img_tag][2][0]);
    $OrignialWidth = str_replace('"', '', $imageinfo[$img_tag][2][1]);
    $OrignialHeight = str_replace('"', '', $imageinfo[$img_tag][2][2]);

    $NewWidth = $OrignialWidth; 
    $NewHeight = $OrignialHeight;
    $AdjustDimensions = "F";

    if($OrignialWidth > $MaximumWidth) { 
        $diff = $OrignialWidth-$MaximumHeight; 
        $percnt_reduced = (($diff/$OrignialWidth)*100); 
        $NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100)); 
        $NewWidth = floor($OrignialWidth-$diff); 
        $AdjustDimensions = "T";
    }

    if($OrignialHeight > $MaximumHeight) { 
        $diff = $OrignialHeight-$MaximumWidth; 
        $percnt_reduced = (($diff/$OrignialHeight)*100); 
        $NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100)); 
        $NewHeight= floor($OrignialHeight-$diff); 
        $AdjustDimensions = "T";
    } 

    $thisImageInfo = array('OriginalImageTag' => $img_tag , 'ImageSource' => $ImageSource , 'OrignialWidth' => $OrignialWidth , 'OrignialHeight' => $OrignialHeight , 'NewWidth' => $NewWidth , 'NewHeight' => $NewHeight, 'AdjustDimensions' => $AdjustDimensions);
    array_push($AllImageInfo, $thisImageInfo);
}

// build array of before and after tags
$ImageBeforeAndAfter = array();
for ($i = 0; $i < count($AllImageInfo); $i++) {

    if($AllImageInfo[$i]['AdjustDimensions'] == "T") {
        $NewImageTag = str_ireplace('width="' . $AllImageInfo[$i]['OrignialWidth'] . '"', 'width="' . $AllImageInfo[$i]['NewWidth'] . '"', $AllImageInfo[$i]['OriginalImageTag']);
        $NewImageTag = str_ireplace('height="' . $AllImageInfo[$i]['OrignialHeight'] . '"', 'height="' . $AllImageInfo[$i]['NewHeight'] . '"', $NewImageTag);

        $thisImageBeforeAndAfter = array('OriginalImageTag' => $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' => $NewImageTag);
        array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);
    }
}

// execute search and replace
for ($i = 0; $i < count($ImageBeforeAndAfter); $i++) {
    $HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);
}

return $HTMLContent;

}

Installation error: INSTALL_FAILED_OLDER_SDK

This error occurs when the sdk-version installed on your device (real or virtual device) is smaller than android:minSdkVersion in your android manifest.

You either have to decrease your android:minSdkVersion or you have to specify a higher api-version for your AVD.

Keep in mind, that it is not always trivial to decrease android:minSdkVersion as you have to make sure, your app cares about the actual installed API and uses the correct methods:

AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
    @Override
    protected Boolean doInBackground(String... params) {
        if (params == null) return "";
        StringBuilder b = new StringBuilder();
        for (String p : params) {
             b.append(p);
        }
        return b.toString();
    }
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"Hello", " ", "world!");
} else {
    task.execute("Hello", " ", "world!");
}

Using the android-support-library and/or libraries like actionbar-sherlock will help you dealing especially with widgets of older versions.

How to set python variables to true or false?

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

MSBUILD : error MSB1008: Only one project can be specified

If you are using Any CPU you may need to put it in single quotes.

Certainly when running in a Dockerfile, I had to use single quotes:

# Fails. Gives: MSBUILD : error MSB1008: Only one project can be specified.
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform="Any CPU" 

# Passes. Gives: Successfully built 40163c3e0121
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform='Any CPU' 

MVC Razor Radio Button

MVC5 Razor Views

Below example will also associate labels with radio buttons (radio button will be selected upon clicking on the relevant label)

// replace "Yes", "No" --> with, true, false if needed
@Html.RadioButtonFor(m => m.Compatible, "Yes", new { id = "compatible" })
@Html.Label("compatible", "Compatible")

@Html.RadioButtonFor(m => m.Compatible, "No", new { id = "notcompatible" })
@Html.Label("notcompatible", "Not Compatible")

Drawing a line/path on Google Maps

Simply get route form this url and do next ...

Origin ---> starting point latitude & longitude

Destination---> ending point latitude & longitude

here i have put origin as Delhi latitude and longitude & destination as chandigarh latitude longitude

https://maps.googleapis.com/maps/api/directions/json?origin=28.704060,77.102493&destination=30.733315,76.779419&sensor=false&key="PUT YOUR MAP API KEY"

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

You might also want to check for Heroku telling you there's a typo in your CSS file.

Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after. It means Heroku has found a typo and you need to fix it in the CSS file.

You can do a find for rake aborted! and directly after that it should say why the push failed.

Copying a HashMap in Java

In Java, when you write:

Object objectA = new Object();
Object objectB = objectA;

objectA and objectB are the same and point to the same reference. Changing one will change the other. So if you change the state of objectA (not its reference) objectB will reflect that change too.

However, if you write:

objectA = new Object()

Then objectB is still pointing to the first object you created (original objectA) while objectA is now pointing to a new Object.

Get the value of bootstrap Datetimepicker in JavaScript

Or try:

$("#datetimepicker").data().date;

How can I use a carriage return in a HTML tooltip?

hack but works - (tested on chrome and mobile)

just add no break spaces   till it breaks - you might have to limit the tooltip size depending on the amount of content but for small text messages this works:

&nbsp;&nbsp; etc

Tried everything above and this is the only thing that worked for me -

How can I check for "undefined" in JavaScript?

    var x;
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("I am not even declared.")
    };

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 

Simplest way to wait some asynchronous tasks complete, in Javascript?

Use Promises.

var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return new Promise(function(resolve, reject) {
    var collection = conn.collection(name);
    collection.drop(function(err) {
      if (err) { return reject(err); }
      console.log('dropped ' + name);
      resolve();
    });
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped)'); })
.catch(console.error);

This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr.


Previous answer (this pre-dates Node’s native support for Promises):

Use Q promises or Bluebird promises.

With Q:

var Q = require('q');
var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa','bbb','ccc'].map(function(name){
    var collection = conn.collection(name);
    return Q.ninvoke(collection, 'drop')
      .then(function() { console.log('dropped ' + name); });
});

Q.all(promises)
.then(function() { console.log('all dropped'); })
.fail(console.error);

With Bluebird:

var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose'));

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return conn.collection(name).dropAsync().then(function() {
    console.log('dropped ' + name);
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped'); })
.error(console.error);

Why is setState in reactjs Async instead of Sync?

Imagine incrementing a counter in some component:

  class SomeComponent extends Component{

    state = {
      updatedByDiv: '',
      updatedByBtn: '',
      counter: 0
    }

    divCountHandler = () => {
      this.setState({
        updatedByDiv: 'Div',
        counter: this.state.counter + 1
      });
      console.log('divCountHandler executed');
    }

    btnCountHandler = () => {
      this.setState({
        updatedByBtn: 'Button',
        counter: this.state.counter + 1
      });
      console.log('btnCountHandler executed');
    }
    ...
    ...
    render(){
      return (
        ...
        // a parent div
        <div onClick={this.divCountHandler}>
          // a child button
          <button onClick={this.btnCountHandler}>Increment Count</button>
        </div>
        ...
      )
    }
  }

There is a count handler attached to both the parent and the child components. This is done purposely so we can execute the setState() twice within the same click event bubbling context, but from within 2 different handlers.

As we would imagine, a single click event on the button would now trigger both these handlers since the event bubbles from target to the outermost container during the bubbling phase.

Therefore the btnCountHandler() executes first, expected to increment the count to 1 and then the divCountHandler() executes, expected to increment the count to 2.

However the count only increments to 1 as you can inspect in React Developer tools.

This proves that react

  • queues all the setState calls

  • comes back to this queue after executing the last method in the context(the divCountHandler in this case)

  • merges all the object mutations happening within multiple setState calls in the same context(all method calls within a single event phase is same context for e.g.) into one single object mutation syntax (merging makes sense because this is why we can update the state properties independently in setState() in the first place)

  • and passes it into one single setState() to prevent re-rendering due to multiple setState() calls (this is a very primitive description of batching).

Resultant code run by react:

this.setState({
  updatedByDiv: 'Div',
  updatedByBtn: 'Button',
  counter: this.state.counter + 1
})

To stop this behaviour, instead of passing objects as arguments to the setState method, callbacks are passed.

    divCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByDiv: 'Div',
              counter: prevState.counter + 1
            };
          });
          console.log('divCountHandler executed');
        }

    btnCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByBtn: 'Button',
              counter: prevState.counter + 1
            };
          });
      console.log('btnCountHandler executed');
    }

After the last method finishes execution and when react returns to process the setState queue, it simply calls the callback for each setState queued, passing in the previous component state.

This way react ensures that the last callback in the queue gets to update the state that all of its previous counterparts have laid hands on.

Explaining Apache ZooKeeper

In a nutshell, ZooKeeper helps you build distributed applications.

How it works

You may describe ZooKeeper as a replicated synchronization service with eventual consistency. It is robust, since the persisted data is distributed between multiple nodes (this set of nodes is called an "ensemble") and one client connects to any of them (i.e., a specific "server"), migrating if one node fails; as long as a strict majority of nodes are working, the ensemble of ZooKeeper nodes is alive. In particular, a master node is dynamically chosen by consensus within the ensemble; if the master node fails, the role of master migrates to another node.

How writes are handled

The master is the authority for writes: in this way writes can be guaranteed to be persisted in-order, i.e., writes are linear. Each time a client writes to the ensemble, a majority of nodes persist the information: these nodes include the server for the client, and obviously the master. This means that each write makes the server up-to-date with the master. It also means, however, that you cannot have concurrent writes.

The guarantee of linear writes is the reason for the fact that ZooKeeper does not perform well for write-dominant workloads. In particular, it should not be used for interchange of large data, such as media. As long as your communication involves shared data, ZooKeeper helps you. When data could be written concurrently, ZooKeeper actually gets in the way, because it imposes a strict ordering of operations even if not strictly necessary from the perspective of the writers. Its ideal use is for coordination, where messages are exchanged between the clients.

How reads are handled

This is where ZooKeeper excels: reads are concurrent since they are served by the specific server that the client connects to. However, this is also the reason for the eventual consistency: the "view" of a client may be outdated, since the master updates the corresponding server with a bounded but undefined delay.

In detail

The replicated database of ZooKeeper comprises a tree of znodes, which are entities roughly representing file system nodes (think of them as directories). Each znode may be enriched by a byte array, which stores data. Also, each znode may have other znodes under it, practically forming an internal directory system.

Sequential znodes

Interestingly, the name of a znode can be sequential, meaning that the name the client provides when creating the znode is only a prefix: the full name is also given by a sequential number chosen by the ensemble. This is useful, for example, for synchronization purposes: if multiple clients want to get a lock on a resource, they can each concurrently create a sequential znode on a location: whoever gets the lowest number is entitled to the lock.

Ephemeral znodes

Also, a znode may be ephemeral: this means that it is destroyed as soon as the client that created it disconnects. This is mainly useful in order to know when a client fails, which may be relevant when the client itself has responsibilities that should be taken by a new client. Taking the example of the lock, as soon as the client having the lock disconnects, the other clients can check whether they are entitled to the lock.

Watches

The example related to client disconnection may be problematic if we needed to periodically poll the state of znodes. Fortunately, ZooKeeper offers an event system where a watch can be set on a znode. These watches may be set to trigger an event if the znode is specifically changed or removed or new children are created under it. This is clearly useful in combination with the sequential and ephemeral options for znodes.

Where and how to use it

A canonical example of Zookeeper usage is distributed-memory computation, where some data is shared between client nodes and must be accessed/updated in a very careful way to account for synchronization.

ZooKeeper offers the library to construct your synchronization primitives, while the ability to run a distributed server avoids the single-point-of-failure issue you have when using a centralized (broker-like) message repository.

ZooKeeper is feature-light, meaning that mechanisms such as leader election, locks, barriers, etc. are not already present, but can be written above the ZooKeeper primitives. If the C/Java API is too unwieldy for your purposes, you should rely on libraries built on ZooKeeper such as cages and especially curator.

Where to read more

Official documentation apart, which is pretty good, I suggest to read Chapter 14 of Hadoop: The Definitive Guide which has ~35 pages explaining essentially what ZooKeeper does, followed by an example of a configuration service.

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

How do I use .woff fonts for my website?

You need to declare @font-face like this in your stylesheet

@font-face {
  font-family: 'Awesome-Font';
  font-style: normal;
  font-weight: 400;
  src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}

Now if you want to apply this font to a paragraph simply use it like this..

p {
font-family: 'Awesome-Font', Arial;
}

More Reference

Python Progress Bar

If it is a big loop with a fixed amount of iterations that is taking a lot of time you can use this function I made. Each iteration of loop adds progress. Where count is the current iteration of the loop, total is the value you are looping to and size(int) is how big you want the bar in increments of 10 i.e. (size 1 =10 chars, size 2 =20 chars)

import sys
def loadingBar(count,total,size):
    percent = float(count)/float(total)*100
    sys.stdout.write("\r" + str(int(count)).rjust(3,'0')+"/"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']')

example:

for i in range(0,100):
     loadingBar(i,100,2)
     #do some code 

output:

i = 50
>> 050/100 [==========          ]

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

Show a popup/message box from a Windows batch file

Here is my batch script that I put together based on the good answers here & in other posts

You can set title timeout & even sleep to schedule it for latter & \n for new line

Name it popup.bat & put it in your windows path folder to work globally on your pc

For example popup Line 1\nLine 2 will produce a 2 line popup box (type popup /? for usage)

Here is the code

<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1]  set pop.key=Ok
if %pop.key% == [2]  set pop.key=Cancel
if %pop.key% == [3]  set pop.key=Abort
if %pop.key% == [4]  set pop.key=Retry
if %pop.key% == [5]  set pop.key=Ignore
if %pop.key% == [6]  set pop.key=Yes
if %pop.key% == [7]  set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b 
-- End CMD -->

<job><script language="VBScript">
'on error resume next
q   =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup       =   0
Title       =   "Popup"
Timeout     =   0
Mode        =   0
Message     =   ""
Sleep       =   0
button      =   0
If objArgs.Count = 0 Then 
    Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then 
    Usage()
End If
noWait = Not wait() 
For Each arg in objArgs
    If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch   =   True
Next
If not haveSwitch Then 
    Message=joinParam("woq")
Else
    For i = 0 To objArgs.Count-1 
        If IsSwitch(objArgs(i)) Then 
            S=split(objArgs(i) , ":" , 2)
                select case Lcase(S(0))
                    case "/m","/message"
                        Message=S(1)
                    case "/tt","/title"
                        Title=S(1)
                    case "/s","/sleep"
                        If IsNumeric(S(1)) Then Sleep=S(1)*1000
                    case "/t","/time"
                        If IsNumeric(S(1)) Then Timeout=S(1)
                    case "/b","/button"
                        select case S(1)
                            case "oc", "1"
                                button=1
                            case "ari","2"
                                button=2
                            case "ync","3"
                                button=3
                            case "yn", "4"
                                button=4
                            case "rc", "5"
                                button=5
                            case "ctc","6"
                                button=6
                            case Else
                                button=0
                        end select
                    case "/i","/icon"
                        select case S(1)
                            case "s","x","stop","16"
                                Mode=16
                            case "?","q","question","32"
                                Mode=32
                            case "!","w","warning","exclamation","48"
                                Mode=48
                            case "i","information","info","64"
                                Mode=64
                            case Else 
                                Mode=0
                        end select
                end select
        End If
    Next
End If
Message = Replace(Message,"/\n", "°"  )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0

Wscript.Sleep(sleep)
Popup   = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup

Function IsSwitch(Val)
    IsSwitch        = False
    If Mid(Val,1,1) = "/" Then
        For ii = 3 To 9 
            If Mid(Val,ii,1)    = ":" Then IsSwitch = True
        Next
    End If
End Function

Function joinParam(quotes)
    ReDim ArgArr(objArgs.Count-1)
    For i = 0 To objArgs.Count-1 
        If quotes = "wq" Then 
            ArgArr(i) = q & objArgs(i) & q 
        Else
            ArgArr(i) =     objArgs(i)
        End If
    Next
    joinParam = Join(ArgArr)
End Function

Function wait()
    wait=True
    If objArgs.Named.Exists("NewProcess") Then
        wait=False
        Exit Function
    ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
        objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq") 
        WScript.Quit 99
    End If
End Function

Function Usage()
    Wscript.Echo _
                     vbCrLf&"Usage:" _
                    &vbCrLf&"      popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
                    &vbCrLf&"      To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
                    &vbCrLf&"" _
                    &vbCrLf&"Advanced user" _
                    &vbCrLf&"      If any Switch is used then you must use the /m: switch for the message " _
                    &vbCrLf&"      No space allowed between the switch & the value " _
                    &vbCrLf&"      The switches are NOT case sensitive " _
                    &vbCrLf&"" _
                    &vbCrLf&"      popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
                    &vbCrLf&"" _
                    &vbCrLf&"      Switch       | value |Description" _
                    &vbCrLf&"      -----------------------------------------------------------------------" _
                    &vbCrLf&"      /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /t: /time:   | nn    |Duration of the popup for n seconds " _
                    &vbCrLf&"                   |       |<Default> untill key pressed" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
                    &vbCrLf&"                   |       | <Default> Popup" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /s: /sleep:  | nn    |schedule the popup after n seconds " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /nw /NoWait  |       |Continue script without the user pressing ok - " _
                    &vbCrLf&"                   |       | botton option will be defaulted to OK button " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /i: /icon:   | ?/q   |[question mark]"  _
                    &vbCrLf&"                   | !/w   |[exclamation (warning) mark]"  _
                    &vbCrLf&"                   | i/info|[information mark]"  _
                    &vbCrLf&"                   | x/stop|[stop\error mark]" _
                    &vbCrLf&"                   | n/none|<Default>" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /b: /button: | o     |[OK button] <Default>"  _
                    &vbCrLf&"                   | oc    |[OK and Cancel buttons]"  _
                    &vbCrLf&"                   | ari   |[Abort, Retry, and Ignore buttons]"  _
                    &vbCrLf&"                   | ync   |[Yes, No, and Cancel buttons]" _
                    &vbCrLf&"                   | yn    |[Yes and No buttons]" _
                    &vbCrLf&"                   | rc    |[Retry and Cancel buttons]" _
                    &vbCrLf&"                   | ctc   |[Cancel and Try Again and Continue buttons]" _
                    &vbCrLf&"      --->         | --->  |The output will be saved in variable ""pop.key""" _
                    &vbCrLf&"" _
                    &vbCrLf&"Example:" _
                    &vbCrLf&"        popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
                    &vbCrLf&"" _
                    &vbCrLf&"                     v1.9 By RDR @ 2020"
    Wscript.Quit
End Function

</script></job>

Vue 2 - Mutating props vue-warn

one-way Data Flow, according to https://vuejs.org/v2/guide/components.html, the component follow one-Way Data Flow, All props form a one-way-down binding between the child property and the parent one, when the parent property updates, it will flow down to the child but not the other way around, this prevents child components from accidentally mutating the parent's, which can make your app's data flow harder to understand.

In addition, every time the parent component is updates all props in the child components will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do .vue will warn you in the console.

There are usually two cases where it’s tempting to mutate a prop: The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. The prop is passed in as a raw value that needs to be transformed. The proper answer to these use cases are: Define a local data property that uses the prop’s initial value as its initial value:

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

Define a computed property that is computed from the prop’s value:

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
    
  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.

Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.

File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run

fciv -sha1 DXSDK_Jun10.exe

and verify you get

8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Oracle SQL Developer: Unable to find a JVM

Probably this is you are looking for (from this post):

Oracle SQL developer is NOT support on 64 bits JDK. To solve it, install a 32 bits / x86 JDK and update your SQL developer config file, so that it points to the 32 bits JDK.

Fix it! Edit the “sqldeveloper.conf“, which can be found under “{ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf“, make sure “SetJavaHome” is point to your 32 bits JDK.

Update: Based on @FGreg answer below, in the Sql Developer version 4.XXX you can do it in user-specific config file:

  • Go to Properties -> Help -> About
  • Add / Change SetJavaHome to your path (for example - C:\Program Files (x86)\Java\jdk1.7.0_03) - this will override the setting in sqldeveloper.conf

Update 2: Based on @krm answer below, if your SQL Developer and JDK "bits" versions are not same, you can try to set the value of SetJavaHome property in product.conf

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

updating Google play services in Emulator

My answer is not to update the Google play service but work around. Get the play service version of the emulator by using the following code

getPackageManager().getPackageInfo("com.google.android.gms", 0 ).versionName);

For example if the value is "9.8.79" then use the nearest lesser version available com.google.android.gms:play-services:9.8.0'

This will resolve your problem. Get the release history from https://developers.google.com/android/guides/releases#november_2016_-_v100

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

C# : Passing a Generic Object

You cannot access var with the generic.

Try something like

Console.WriteLine("Generic : {0}", test);

And override ToString method [1]

[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

How do I use properly CASE..WHEN in MySQL

Remove the course_enrollment_settings.base_price immediately after CASE:

SELECT
   CASE
    WHEN course_enrollment_settings.base_price = 0      THEN 1
    ...
    END

CASE has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.

How to search for a part of a word with ElasticSearch

without changing your index mappings you could do a simple prefix query that will do partial searches like you are hoping for

ie.

{
  "query": { 
    "prefix" : { "name" : "Doe" }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html

How can I get the client's IP address in ASP.NET MVC?

The simple answer is to use the HttpRequest.UserHostAddress property.

Example: From within a Controller:

using System;
using System.Web.Mvc;

namespace Mvc.Controllers
{
    public class HomeController : ClientController
    {
        public ActionResult Index()
        {
            string ip = Request.UserHostAddress;

            ...
        }
    }
}

Example: From within a helper class:

using System.Web;

namespace Mvc.Helpers
{
    public static class HelperClass
    {
        public static string GetIPHelper()
        {
            string ip = HttpContext.Current.Request.UserHostAddress;
            ..
        }
    }
}

BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.

Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.


Original Answer

Request.UserHostAddress

The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:

public static string getIPAddress(HttpRequestBase request)
{
    string szRemoteAddr = request.UserHostAddress;
    string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
    string szIP = "";

    if (szXForwardedFor == null)
    {
        szIP = szRemoteAddr;
    }
    else
    {
        szIP = szXForwardedFor;
        if (szIP.IndexOf(",") > 0)
        {
            string [] arIPs = szIP.Split(',');

            foreach (string item in arIPs)
            {
                if (!isPrivateIP(item))
                {
                    return item;
                }
            }
        }
    }
    return szIP;
}

How do I import a specific version of a package using go get?

go get is the Go package manager. It works in a completely decentralized way and how package discovery still possible without a central package hosting repository.

Besides locating and downloading packages, the other big role of a package manager is handling multiple versions of the same package. Go takes the most minimal and pragmatic approach of any package manager. There is no such thing as multiple versions of a Go package.

go get always pulls from the HEAD of the default branch in the repository. Always. This has two important implications:

  1. As a package author, you must adhere to the stable HEAD philosophy. Your default branch must always be the stable, released version of your package. You must do work in feature branches and only merge when ready to release.

  2. New major versions of your package must have their own repository. Put simply, each major version of your package (following semantic versioning) would have its own repository and thus its own import path.

    e.g. github.com/jpoehls/gophermail-v1 and github.com/jpoehls/gophermail-v2.

As someone building an application in Go, the above philosophy really doesn't have a downside. Every import path is a stable API. There are no version numbers to worry about. Awesome!

For more details : http://zduck.com/2014/go-and-package-versioning/

Git merge reports "Already up-to-date" though there is a difference

Say you have a branch master with the following commit history:

A -- B -- C -- D

Now, you create a branch test, work on it, and do 4 commits:


                 E -- F -- G -- H
                /
A -- B -- C -- D

master's head points to D, and test's head points to H.

The "Already up-to-date" message shows up when the HEAD of the branch you are merging into is a parent of the chain of commits of the branch you want to merge. That's the case, here: D is a parent of E.

There is nothing to merge from test to master, since nothing has changed on master since then. What you want to do here is literally to tell Git to have master's head to point to H, so master's branch has the following commits history:

A -- B -- C -- D -- E -- F -- G -- H

This is a job for Git command reset. You also want the working directory to reflect this change, so you'll do a hard reset:

git reset --hard H

How to get a password from a shell script without echoing

Turn echo off using stty, then back on again after.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

Generating UNIQUE Random Numbers within a range

This is how I would do it.

$randnum1 = mt_rand(1,20);

$nomatch = 0;

while($nomatch == 0){

$randnum2 = mt_rand(1,20);

if($randnum2 != $randnum1){

$nomatch = 1;

}

}

$nomatch = 0;

while($nomatch == 0){

$randnum3 = mt_rand(1,20);

if(($randnum3 != $randnum1)and($randnum3 != $randnum2)){

$nomatch = 1;

}

}

Then you can echo the results to check

echo "Random numbers are " . $randnum1 . "," . $randnum2 . ", and " . $randnum3 . "\n";

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

Parse query string in JavaScript

Here is a fast and easy way of parsing query strings in JavaScript:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));

What's the default password of mariadb on fedora?

Had the same issue after installing mysql mariadb 10.3. The password was not NULL so simply pressing ENTER didn't worked for me. So finally had to change the password. I followed instruction from here. In nutshell; stop the server

sudo systemctl stop mariadb.service

gain access to the server through a backdoor by starting the database server and skipping networking and permission tables.

sudo mysqld_safe --skip-grant-tables --skip-networking &

login as root

sudo mysql -u root

then change server password

use mysql;
update user set password=PASSWORD("new_password_here") where User='root';

Note that after MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'. So use appropriate table name based on mysql version. finally save changes & restart the server

flush privileges;
sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

How to cast the size_t to double or int C++

Static cast:

static_cast<int>(data);

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

Angular 2.0 router not working on reloading the browser

Make sure this is placed in the head element of your index.html:

<base href="/">

The Example in the Angular2 Routing & Navigation documentation uses the following code in the head instead (they explain why in the live example note of the documentation):

<script>document.write('<base href="' + document.location + '" />');</script>

When you refresh a page this will dynamically set the base href to your current document.location. I could see this causing some confusion for people skimming the documentation and trying to replicate the plunker.

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

Extract code country from phone number [libphonenumber]

Here is a solution to get the country based on an international phone number without using the Google library.

Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:

1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada

Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.

For my code, I defined a class which holds information for ever digit:

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:

country code 1: byPhone[1].Country is US  
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada  
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since   
                   byPhone[1].Country is US, also 1235 is US, because no other   
                   country was found in the later digits

Here is the method which returns the country based on the phone number:

/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
  if (phoneNumber.Length==0) return null;

  var isFirstDigit = true;
  DigitInfo? digitInfo = null;
  Country? country = null;
  foreach (var digitChar in phoneNumber) {
    var digitIndex = digitChar - '0';
    if (isFirstDigit) {
      isFirstDigit = false;
      digitInfo = ByPhone[digitIndex];
    } else {
      if (digitInfo!.Digits is null) return country;

      digitInfo = digitInfo.Digits[digitIndex];
    }
    if (digitInfo is null) return country;

    country = digitInfo.Country??country;
  }
  return country;
}

The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github: https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsLib/CountryCode.cs

The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Can anyone explain IEnumerable and IEnumerator to me?

The IEnumerable and IEnumerator Interfaces

To begin examining the process of implementing existing .NET interfaces, let’s first look at the role of IEnumerable and IEnumerator. Recall that C# supports a keyword named foreach that allows you to iterate over the contents of any array type:

// Iterate over an array of items.
int[] myArrayOfInts = {10, 20, 30, 40};
foreach(int i in myArrayOfInts)
{
   Console.WriteLine(i);
}

While it might seem that only array types can make use of this construct, the truth of the matter is any type supporting a method named GetEnumerator() can be evaluated by the foreach construct.To illustrate, follow me!

Suppose we have a Garage class:

// Garage contains a set of Car objects.
public class Garage
{
   private Car[] carArray = new Car[4];
   // Fill with some Car objects upon startup.
   public Garage()
   {
      carArray[0] = new Car("Rusty", 30);
      carArray[1] = new Car("Clunker", 55);
      carArray[2] = new Car("Zippy", 30);
      carArray[3] = new Car("Fred", 30);
   }
}

Ideally, it would be convenient to iterate over the Garage object’s subitems using the foreach construct, just like an array of data values:

// This seems reasonable ...
public class Program
{
   static void Main(string[] args)
   {
      Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n");
      Garage carLot = new Garage();
      // Hand over each car in the collection?
      foreach (Car c in carLot)
      {
         Console.WriteLine("{0} is going {1} MPH",
         c.PetName, c.CurrentSpeed);
      }
      Console.ReadLine();
   }
}

Sadly, the compiler informs you that the Garage class does not implement a method named GetEnumerator(). This method is formalized by the IEnumerable interface, which is found lurking within the System.Collections namespace. Classes or structures that support this behavior advertise that they are able to expose contained subitems to the caller (in this example, the foreach keyword itself). Here is the definition of this standard .NET interface:

// This interface informs the caller
// that the object's subitems can be enumerated.
public interface IEnumerable
{
   IEnumerator GetEnumerator();
}

As you can see, the GetEnumerator() method returns a reference to yet another interface named System.Collections.IEnumerator. This interface provides the infrastructure to allow the caller to traverse the internal objects contained by the IEnumerable-compatible container:

// This interface allows the caller to
// obtain a container's subitems.
public interface IEnumerator
{
   bool MoveNext (); // Advance the internal position of the cursor.
   object Current { get;} // Get the current item (read-only property).
   void Reset (); // Reset the cursor before the first member.
}

If you want to update the Garage type to support these interfaces, you could take the long road and implement each method manually. While you are certainly free to provide customized versions of GetEnumerator(), MoveNext(), Current, and Reset(), there is a simpler way. As the System.Array type (as well as many other collection classes) already implements IEnumerable and IEnumerator, you can simply delegate the request to the System.Array as follows:

using System.Collections;
...
public class Garage : IEnumerable
{
   // System.Array already implements IEnumerator!
   private Car[] carArray = new Car[4];
   public Garage()
   {
      carArray[0] = new Car("FeeFee", 200);
      carArray[1] = new Car("Clunker", 90);
      carArray[2] = new Car("Zippy", 30);
      carArray[3] = new Car("Fred", 30);
   }
   public IEnumerator GetEnumerator()
   {
      // Return the array object's IEnumerator.
      return carArray.GetEnumerator();
   }
}

After you have updated your Garage type, you can safely use the type within the C# foreach construct. Furthermore, given that the GetEnumerator() method has been defined publicly, the object user could also interact with the IEnumerator type:

// Manually work with IEnumerator.
IEnumerator i = carLot.GetEnumerator();
i.MoveNext();
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.CurrentSpeed);

However, if you prefer to hide the functionality of IEnumerable from the object level, simply make use of explicit interface implementation:

IEnumerator IEnumerable.GetEnumerator()
{
  // Return the array object's IEnumerator.
  return carArray.GetEnumerator();
}

By doing so, the casual object user will not find the Garage’s GetEnumerator() method, while the foreach construct will obtain the interface in the background when necessary.

Adapted from the Pro C# 5.0 and the .NET 4.5 Framework

Change keystore password from no password to a non blank password

Add -storepass to keytool arguments.

keytool -storepasswd -storepass '' -keystore mykeystore.jks

But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists represent a sequential ordering of elements. Maps are used to represent a collection of key / value pairs.

While you could use a map as a list, there are some definite downsides of doing so.

Maintaining order: - A list by definition is ordered. You add items and then you are able to iterate back through the list in the order that you inserted the items. When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map.

Key/Value semantics: - The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.

Code readability Consider the following examples.

    // Adding to a List
    list.add(myObject);         // adds to the end of the list
    map.put(myKey, myObject);   // sure, you can do this, but what is myKey?
    map.put("1", myObject);     // you could use the position as a key but why?

    // Iterating through the items
    for (Object o : myList)           // nice and easy
    for (Object o : myMap.values())   // more code and the order is not guaranteed

Collection functionality Some great utility functions are available for lists via the Collections class. For example ...

    // Randomize the list
    Collections.shuffle(myList);

    // Sort the list
    Collections.sort(myList, myComparator);  

Hope this helps,

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

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

How to know elastic search installed version from kibana?

I would like to add which isn't mentioned in above answers.

From your kibana's dev console, hit following command:

GET /

This is similar to accessing localhost:9200 from browser.

Hope this will help someone.

Python circular importing?

I was able to import the module within the function (only) that would require the objects from this module:

def my_func():
    import Foo
    foo_instance = Foo()

How to use JavaScript with Selenium WebDriver Java

Following code worked for me:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

TLS 1.2 not working in cURL

TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1

Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0

You should consider an upgrade.

Set HTTP header for one request

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {


return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;
    }
  };
})

.config(function($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
})

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
            die();
        }

        if(!$this->input->get_request_header('Authorization')){
            $this->response(null, 400);    
        }

        $this->authorization = $this->input->get_request_header('Authorization');
    }

}

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

C++: what regex library should I use?

Boost has regex in it.

That should fill the bill

ASP.NET MVC get textbox input value

Try This.

View:

@using (Html.BeginForm("Login", "Accounts", FormMethod.Post)) 
{
   <input type="text" name="IP" id="IP" />
   <input type="text" name="Name" id="Name" />

   <input type="submit" value="Login" />
}

Controller:

[HttpPost]
public ActionResult Login(string IP, string Name)
{
    string s1=IP;//
    string s2=Name;//
}

If you can use model class

[HttpPost]
public ActionResult Login(ModelClassName obj)
{
    string s1=obj.IP;//
    string s2=obj.Name;//
}

.NET Global exception handler in console application

You also need to handle exceptions from threads:

static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}

private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
    Console.WriteLine(e.Exception.StackTrace);
}

Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Most the time If Activity name changed reflected all over the project except the AndroidManifest.xml file.

You just need to Add the name in manifest manually.

<activity
android:name="Activity_Class_Name"
android:label="@string/app_name">
</activity>

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

Getting only 1 decimal place

Are you trying to represent it with only one digit:

print("{:.1f}".format(number)) # Python3
print "%.1f" % number          # Python2

or actually round off the other decimal places?

round(number,1)

or even round strictly down?

math.floor(number*10)/10

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

What's the difference between a proxy server and a reverse proxy server?

Proxy: It is making the request on behalf of the client. So, the server will return the response to the proxy, and the proxy will forward the response to the client. In fact, the server will never "learn" who the client was (the client's IP address); it will only know the proxy. However, the client definitely knows the server, since it essentially formats the HTTP request destined for the server, but it just hands it to the proxy.

Enter image description here

Reverse Proxy: It is receiving the request on behalf of the server. It forwards the request to the server, receives the response and then returns the response to the client. In this case, the client will never "learn" who was the actual server (the server's IP address) (with some exceptions); it will only know the proxy. The server will or won't know the actual client, depending on the configurations of the reverse proxy.

Enter image description here

Delete all records in a table of MYSQL in phpMyAdmin

Use this query:

DELETE FROM tableName;

Note: To delete some specific record you can give the condition in where clause in the query also.

OR you can use this query also:

truncate tableName;

Also remember that you should not have any relationship with other table. If there will be any foreign key constraint in the table then those record will not be deleted and will give the error.

How do I make WRAP_CONTENT work on a RecyclerView

This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

Spring: @Component versus @Bean

You have two ways to generate beans. One is to create a class with an annotation @Component. The other is to create a method and annotate it with @Bean. For those classes containing method with @Bean should be annotated with @Configuration Once you run your spring project, the class with a @ComponentScan annotation would scan every class with @Component on it, and restore the instance of this class to the Ioc Container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean. So when you need to decide which kind of beans you want to create depending upon current states, you need to use @Bean. You can write the logic and return the object you want. Another thing worth to mention is the name of the method with @Bean is the default name of bean.

Using IQueryable with Linq

Although Reed Copsey and Marc Gravell already described about IQueryable (and also IEnumerable) enough,mI want to add little more here by providing a small example on IQueryable and IEnumerable as many users asked for it

Example: I have created two table in database

   CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Gender] [nchar](1) NOT NULL)
   CREATE TABLE [dbo].[Person]([PersonId] [int] NOT NULL PRIMARY KEY,[FirstName] [nvarchar](50) NOT NULL,[LastName] [nvarchar](50) NOT NULL)

The Primary key(PersonId) of table Employee is also a forgein key(personid) of table Person

Next i added ado.net entity model in my application and create below service class on that

public class SomeServiceClass
{   
    public IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }

    public IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable(IEnumerable<int> employeesToCollect)
    {
        DemoIQueryableEntities db = new DemoIQueryableEntities();
        var allDetails = from Employee e in db.Employees
                         join Person p in db.People on e.PersonId equals p.PersonId
                         where employeesToCollect.Contains(e.PersonId)
                         select e;
        return allDetails;
    }
}

they contains same linq. It called in program.cs as defined below

class Program
{
    static void Main(string[] args)
    {
        SomeServiceClass s= new SomeServiceClass(); 

        var employeesToCollect= new []{0,1,2,3};

        //IQueryable execution part
        var IQueryableList = s.GetEmployeeAndPersonDetailIQueryable(employeesToCollect).Where(i => i.Gender=="M");            
        foreach (var emp in IQueryableList)
        {
            System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IQueryable contain {0} row in result set", IQueryableList.Count());

        //IEnumerable execution part
        var IEnumerableList = s.GetEmployeeAndPersonDetailIEnumerable(employeesToCollect).Where(i => i.Gender == "M");
        foreach (var emp in IEnumerableList)
        {
           System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
        }
        System.Console.WriteLine("IEnumerable contain {0} row in result set", IEnumerableList.Count());

        Console.ReadKey();
    }
}

The output is same for both obviously

ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IQueryable contain 2 row in result set  
ID:1, EName:Ken,Gender:M  
ID:3, EName:Roberto,Gender:M  
IEnumerable contain 2 row in result set

So the question is what/where is the difference? It does not seem to have any difference right? Really!!

Let's have a look on sql queries generated and executed by entity framwork 5 during these period

IQueryable execution part

--IQueryableQuery1 
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])

--IQueryableQuery2
SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [dbo].[Employee] AS [Extent1]
    WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
)  AS [GroupBy1]

IEnumerable execution part

--IEnumerableQuery1
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

--IEnumerableQuery2
SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)

Common script for both execution part

/* these two query will execute for both IQueryable or IEnumerable to get details from Person table
   Ignore these two queries here because it has nothing to do with IQueryable vs IEnumerable
--ICommonQuery1 
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1

--ICommonQuery2
exec sp_executesql N'SELECT 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3
*/

So you have few questions now, let me guess those and try to answer them

Why are different scripts generated for same result?

Lets find out some points here,

all queries has one common part

WHERE [Extent1].[PersonId] IN (0,1,2,3)

why? Because both function IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable and IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable of SomeServiceClass contains one common line in linq queries

where employeesToCollect.Contains(e.PersonId)

Than why is the AND (N'M' = [Extent1].[Gender]) part is missing in IEnumerable execution part, while in both function calling we used Where(i => i.Gender == "M") inprogram.cs`

Now we are in the point where difference came between IQueryable and IEnumerable

What entity framwork does when an IQueryable method called, it tooks linq statement written inside the method and try to find out if more linq expressions are defined on the resultset, it then gathers all linq queries defined until the result need to fetch and constructs more appropriate sql query to execute.

It provide a lots of benefits like,

  • only those rows populated by sql server which could be valid by the whole linq query execution
  • helps sql server performance by not selecting unnecessary rows
  • network cost get reduce

like here in example sql server returned to application only two rows after IQueryable execution` but returned THREE rows for IEnumerable query why?

In case of IEnumerable method, entity framework took linq statement written inside the method and constructs sql query when result need to fetch. it does not include rest linq part to constructs the sql query. Like here no filtering is done in sql server on column gender.

But the outputs are same? Because 'IEnumerable filters the result further in application level after retrieving result from sql server

SO, what should someone choose? I personally prefer to define function result as IQueryable<T> because there are lots of benefit it has over IEnumerable like, you could join two or more IQueryable functions, which generate more specific script to sql server.

Here in example you can see an IQueryable Query(IQueryableQuery2) generates a more specific script than IEnumerable query(IEnumerableQuery2) which is much more acceptable in my point of view.

Rename column SQL Server 2008

Sql Server management studio has some system defined Stored Procedures(SP)
One of which is used to rename a column.The SP is sp_rename

Syntax: sp_rename '[table_name].old_column_name', 'new_column_name'
For further help refer this article: sp_rename by Microsoft Docs

Note: On execution of this SP the sql server will give you a caution message as 'Caution: Changing any part of an object name could break scripts and stored procedures'.This is critical only if you have written your own sp which involves the column in the table you are about to change.

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

How do I get my page title to have an icon?

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

add this to your HTML Head. Of course the file "favicon.ico" has to exist. I think 16x16 or 32x32 pixel files are best.

How to make a .jar out from an Android Studio project

If you set up the code as a plain Java module in Gradle, then it's really easy to have Gradle give you a jar file with the contents. That jar file will have only your code, not the other Apache libraries it depends on. I'd recommend distributing it this way; it's a little weird to bundle dependencies inside your library, and it's more normal for users of those libraries to have to include those dependencies on their own (because otherwise there are collisions of those projects are already linking copies of the library, perhaps of different versions). What's more, you avoid potential licensing problems around redistributing other people's code if you were to publish your library.

Take the code that also needs to be compiled to a jar, and move it to a separate plain Java module in Android Studio:

  1. File menu > New Module... > Java Library
  2. Set up the library, Java package name, and class names in the wizard. (If you don't want it to create a class for you, you can just delete it once the module is created)
  3. In your Android code, set up a dependency on the new module so it can use the code in your new library:
  4. File > Project Structure > Modules > (your Android Module) > Dependencies > + > Module dependency. See the screenshot below: enter image description here
  5. Choose your module from the list in the dialog that comes up: enter image description here

Hopefully your project should be building normally now. After you do a build, a jar file for your Java library will be placed in the build/libs directory in your module's directory. If you want to build the jar file by hand, you can run its jar build file task from the Gradle window: enter image description here

Android: remove left margin from actionbar's custom layout

try this:

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);
    View customView = getLayoutInflater().inflate(R.layout.main_action_bar, null);
    actionBar.setCustomView(customView);
    Toolbar parent =(Toolbar) customView.getParent();
    parent.setPadding(0,0,0,0);//for tab otherwise give space in tab
    parent.setContentInsetsAbsolute(0,0);

I used this code in my project,good luck;

@RequestParam vs @PathVariable

@RequestParam is use for query parameter(static values) like: http://localhost:8080/calculation/pow?base=2&ext=4

@PathVariable is use for dynamic values like : http://localhost:8080/calculation/sqrt/8

@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
    int pow = (int) Math.pow(base1, ext1);
    return pow;
}

@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
    double sqrtnum=Math.sqrt(num1);
    return sqrtnum;
}

Appending a list to a list of lists in R

Just a note on Brian's answer below, the first assignment to outlist can also be an append statement so you could also do something like this:

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list()
outlist <- append(outlist,list(resultsa))
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

This is sometimes helpful if you want to build a list from scratch in a loop.

Rotate axis text in python matplotlib

This works for me:

plt.xticks(rotation=90)

How to create full path with node's fs.mkdirSync?

Edit

NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create a directory recursively with recursive: true option as the following:

fs.mkdirSync(targetDir, { recursive: true });

And if you prefer fs Promises API, you can write

fs.promises.mkdir(targetDir, { recursive: true });

Original Answer

Create directories recursively if they do not exist! (Zero dependencies)

const fs = require('fs');
const path = require('path');

function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
  const sep = path.sep;
  const initDir = path.isAbsolute(targetDir) ? sep : '';
  const baseDir = isRelativeToScript ? __dirname : '.';

  return targetDir.split(sep).reduce((parentDir, childDir) => {
    const curDir = path.resolve(baseDir, parentDir, childDir);
    try {
      fs.mkdirSync(curDir);
    } catch (err) {
      if (err.code === 'EEXIST') { // curDir already exists!
        return curDir;
      }

      // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
      if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
        throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
      }

      const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
      if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
        throw err; // Throw if it's just the last created dir.
      }
    }

    return curDir;
  }, initDir);
}

Usage

// Default, make directories relative to current working directory.
mkDirByPathSync('path/to/dir');

// Make directories relative to the current script.
mkDirByPathSync('path/to/dir', {isRelativeToScript: true});

// Make directories with an absolute path.
mkDirByPathSync('/path/to/dir');

Demo

Try It!

Explanations

  • [UPDATE] This solution handles platform-specific errors like EISDIR for Mac and EPERM and EACCES for Windows. Thanks to all the reporting comments by @PediT., @JohnQ, @deed02392, @robyoder and @Almenon.
  • This solution handles both relative and absolute paths. Thanks to @john comment.
  • In the case of relative paths, target directories will be created (resolved) in the current working directory. To Resolve them relative to the current script dir, pass {isRelativeToScript: true}.
  • Using path.sep and path.resolve(), not just / concatenation, to avoid cross-platform issues.
  • Using fs.mkdirSync and handling the error with try/catch if thrown to handle race conditions: another process may add the file between the calls to fs.existsSync() and fs.mkdirSync() and causes an exception.
    • The other way to achieve that could be checking if a file exists then creating it, I.e, if (!fs.existsSync(curDir) fs.mkdirSync(curDir);. But this is an anti-pattern that leaves the code vulnerable to race conditions. Thanks to @GershomMaes comment about the directory existence check.
  • Requires Node v6 and newer to support destructuring. (If you have problems implementing this solution with old Node versions, just leave me a comment)

How to get a list of column names

Use a recursive query. Given

create table t (a int, b int, c int);

Run:

with recursive
  a (cid, name) as (select cid, name from pragma_table_info('t')),
  b (cid, name) as (
    select cid, '|' || name || '|' from a where cid = 0
    union all
    select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
  )
select name
from b
order by cid desc
limit 1;

Alternatively, just use group_concat:

select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')

Both yield:

|a|b|c|

What are some reasons for jquery .focus() not working?

The problem in my case was that I entered a value IN THE LAST NOT DISABLED ELEMENT of the site and used tab to raise the onChange-Event. After that there is no next element to get the focus, so the "browser"-Focus switches to the browser-functionality (tabs, menu, and so on) and is not any longer inside the html-content.

To understand that, place a displayed, not disabled dummy-textbox at the end of your html-code. In that you can "park" the focus for later replacing. Should work. In my case. All other tries didnt work, also the setTimeout-Version.

Checked this out for about an hour, because it made me insane :)

Mätes

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

CASE expression
      WHEN value1 THEN result1
      WHEN value2 THEN result2
      ...
      WHEN valueN THEN resultN

      [
        ELSE elseResult
      ]
END

http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.

How to check if spark dataframe is empty?

On PySpark, you can also use this bool(df.head(1)) to obtain a True of False value

It returns False if the dataframe contains no rows

Change UITableView height dynamically

I found adding constraint programmatically much easier than in storyboard.

    var leadingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: 0.0)

    var trailingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: mView, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1, constant: 0.0)

    var height = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: screenSize.height - 55)

    var bottom = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: screenSize.height - 200)

    var top = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 250)

    self.view.addConstraint(leadingMargin)
    self.view.addConstraint(trailingMargin)
    self.view.addConstraint(height)
    self.view.addConstraint(bottom)
    self.view.addConstraint(top)

How do I connect to an MDF database file?

For Visual Studio 2015 the connection string is:

"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True"

How to start working with GTest and CMake

The OP is using Windows, and a much easier way to use GTest today is with vcpkg+cmake.


Install vcpkg as per https://github.com/microsoft/vcpkg , and make sure you can run vcpkg from the cmd line. Take note of the vcpkg installation folder, eg. C:\bin\programs\vcpkg.

Install gtest using vcpkg install gtest: this will download, compile, and install GTest.

Use a CmakeLists.txt as below: note we can use targets instead of including folders.

cmake_minimum_required(VERSION 3.15)
project(sample CXX)
enable_testing()
find_package(GTest REQUIRED)
add_executable(test1 test.cpp source.cpp)
target_link_libraries(test1 GTest::GTest GTest::Main)
add_test(test-1 test1)

Run cmake with: (edit the vcpkg folder if necessary, and make sure the path to the vcpkg.cmake toolchain file is correct)

cmake -B build -DCMAKE_TOOLCHAIN_FILE=C:\bin\programs\vcpkg\scripts\buildsystems\vcpkg.cmake

and build using cmake --build build as usual. Note that, vcpkg will also copy the required gtest(d).dll/gtest(d)_main.dll from the install folder to the Debug/Release folders.

Test with cd build & ctest.

How to display (print) vector in Matlab?

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

Origin is not allowed by Access-Control-Allow-Origin

if you're under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

Postgresql: password authentication failed for user "postgres"

This was frustrating, most of the above answers are correct but they fail to mention you have to restart the database service before the changes in the pg_hba.conf file will take affect.

so if you make the changes as mentioned above:

local all postgres ident

then restart as root ( on centos its something like service service postgresql-9.2 restart ) now you should be able to access the db as the user postgres

$psql
psql (9.2.4)
Type "help" for help.

postgres=# 

Hope this adds info for new postgres users

Adding Lombok plugin to IntelliJ project

To add the Lombok IntelliJ plugin to add lombok support IntelliJ:

  • Go to File > Settings > Plugins
  • Click on Browse repositories...
  • Search for Lombok Plugin
  • Click on Install plugin
  • Restart IntelliJ IDEA

How can I turn a List of Lists into a List in Java 8?

List<List> list = map.values().stream().collect(Collectors.toList());

    List<Employee> employees2 = new ArrayList<>();
    
     list.stream().forEach(
             
             n-> employees2.addAll(n));

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

How to add to an NSDictionary

For reference, you can also utilize initWithDictionary to init the NSMutableDictionary with a literal one:

NSMutableDictionary buttons = [[NSMutableDictionary alloc] initWithDictionary: @{
    @"touch": @0,
    @"app": @0,
    @"back": @0,
    @"volup": @0,
    @"voldown": @0
}];

rsync copy over only certain types of files using include option

If someone looks for this… I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files

With rsync-files:

my-dir/
my-file.txt

- /*

How much data can a List can hold at the maximum?

java.util.List is an interface. How much data a list can hold is dependant on the specific implementation of List you choose to use.

Generally, a List implementation can hold any number of items (If you use an indexed List, it may be limited to Integer.MAX_VALUE or Long.MAX_VALUE). As long as you don't run out of memory, the List doesn't become "full" or anything.

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Sometime the default version will not update. Add this command

AWS_S3_SIGNATURE_VERSION = "s3v4"

in settings.py

Can't subtract offset-naive and offset-aware datetimes

Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like

select *, age(timeStampField) as timeStampAge from myTable

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

Context is stored at the application level scope where as request is stored at page level i.e to say

Web Container brings up the applications one by one and run them inside its JVM. It stores a singleton object in its jvm where it registers anyobject that is put inside it.This singleton is shared across all applications running inside it as it is stored inside the JVM of the container itself.

However for requests, the container creates a request object that is filled with data from request and is passed along from one thread to the other (each thread is a new request that is coming to the server), also request is passed to the threads of same application.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

Real-world examples of recursion

I have a system that uses pure tail recursion in a few places to simulate a state machine.

Angular2: Cannot read property 'name' of undefined

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

How to unapply a migration in ASP.NET Core with EF Core

1.find table "dbo._EFMigrationsHistory", then delete the migration record that you want to remove. 2. run "remove-migration" in PM(Package Manager Console). Works for me.

docker error - 'name is already in use by container'

The OP's problem is the error. Deleting state isn't the only solution - or even a good one. The problem is docker run isn't re-entrant, and docker start is impotent w/o run. So we have to combine them.

For example to run Postgres w/o destroying previous state, try this:

docker start postgres || docker run -d -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=password postgres:13-alpine

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

ssh : Permission denied (publickey,gssapi-with-mic)

Maybe you should assign the public key to the authorized_keys, the simple way to do this is using ssh-copy-id -i your-pub-key-file user@dest.

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Example using Hyperlink in WPF

Hope this help someone as well.

using System.Diagnostics;
using System.Windows.Documents;

namespace Helpers.Controls
{
    public class HyperlinkEx : Hyperlink
    {
        protected override void OnClick()
        {
            base.OnClick();

            Process p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = this.NavigateUri.AbsoluteUri
                }
            };
            p.Start();
        }
    }
}

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

This problem may occur because your MySQL server is not installed and running. To do that start command prompt as admin and enter command:

"C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\mysqld" --install

If you get "service successfully installed" message then you need to start the MySQL service. To do that: go to Services window (Task Manager -> Services -> Open Services) Search for MySQL and Start it from the top navigation bar. Then if try to open mysql.exe it will work.

Maintain/Save/Restore scroll position when returning to a ListView

If you're using fragments hosted on an activity you can do something like this:

public abstract class BaseFragment extends Fragment {
     private boolean mSaveView = false;
     private SoftReference<View> mViewReference;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          if (mSaveView) {
               if (mViewReference != null) {
                    final View savedView = mViewReference.get();
                    if (savedView != null) {
                         if (savedView.getParent() != null) {
                              ((ViewGroup) savedView.getParent()).removeView(savedView);
                              return savedView;
                         }
                    }
               }
          }

          final View view = inflater.inflate(getFragmentResource(), container, false);
          mViewReference = new SoftReference<View>(view);
          return view;
     }

     protected void setSaveView(boolean value) {
           mSaveView = value;
     }
}

public class MyFragment extends BaseFragment {
     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          setSaveView(true);
          final View view = super.onCreateView(inflater, container, savedInstanceState);
          ListView placesList = (ListView) view.findViewById(R.id.places_list);
          if (placesList.getAdapter() == null) {
               placesList.setAdapter(createAdapter());
          }
     }
}

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Number of times a particular character appears in a string

You can do that using replace and len.

Count number of x characters in str:

len(str) - len(replace(str, 'x', ''))

Reading/parsing Excel (xls) files with Python

For older Excel files there is the OleFileIO_PL module that can read the OLE structured storage format used.

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Understanding the Rails Authenticity Token

What is an authentication_token ?

This is a random string used by rails application to make sure that the user is requesting or performing an action from the app page, not from another app or site.

Why is an authentication_token is necessary ?

To protect your app or site from cross-site request forgery.

How to add an authentication_token to a form ?

If you are generating a form using form_for tag an authentication_token is automatically added else you can use <%= csrf_meta_tag %>.

How to add app icon within phonegap projects?

Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.

Where the files are placed Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/ folder.

Inside that folder is a folder with the name of your app. Which in turn contains a resources/ directory where you will find the icons/ and splashscreen/ folders.

In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.

What to do

All you have to do is save the icon files in this folder. So that's:

YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons

Same for splashscreen files.

Notes

  1. After placing the files there, rebuild the project using cordova build ios AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.

  2. It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.

  3. And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected] instead of icon-57-2x.png.

  4. Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).

python BeautifulSoup parsing table

Solved, this is how your parse their html results:

table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")
    if len(cells) == 9:
        summons = cells[1].find(text=True)
        plateType = cells[2].find(text=True)
        vDate = cells[3].find(text=True)
        location = cells[4].find(text=True)
        borough = cells[5].find(text=True)
        vCode = cells[6].find(text=True)
        amount = cells[7].find(text=True)
        print amount

raw_input function in Python

The raw_input() function reads a line from input (i.e. the user) and returns a string

Python v3.x as raw_input() was renamed to input()

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

Ref: Docs Python 3

SQL query to group by day

actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101) will change the DATETIME format to date (one day)

so:

SELECT 
    sum(amount) 
FROM 
    sales 
GROUP BY 
    convert(varchar,created,101)

the magix number 101 is what date format it is converted to

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Short answer

Either:

  • ,[\s\S]*$ or ,.*$ to match everything after the first comma (see explanation for which one to use); or

  • [^,]*$ to match everything after the last comma (which is probably what you want).

You can use, for example, /[^,]*/.exec(s)[0] in JavaScript, where s is the original string. If you wanted to use multiline mode and find all matches that way, you could use s.match(/[^,]*/mg) to get an array (if you have more than one of your posted example lines in the variable on separate lines).

Explanation

  • [\s\S] is a character class that matches both whitespace and non-whitespace characters (i.e. all of them). This is different from . in that it matches newlines.
  • [^,] is a negated character class that matches everything except for commas.
  • * means that the previous item can repeat 0 or more times.
  • $ is the anchor that requires that the end of the match be at the end of the string (or end of line if using the /m multiline flag).

For the first match, the first regex finds the first comma , and then matches all characters afterward until the end of line [\s\S]*$, including commas.

The second regex matches as many non-comma characters as possible before the end of line. Thus, the entire match will be after the last comma.

Moment js get first and last day of current month

There would be another way to do this:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

Print the address or pointer for value in C

Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:

char **a;
char *b;
char c = 'H';

b = &c;
a = &b;

You would be able to access the address of the double pointer a by doing:

printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I tried with browser URL for the repository then

git clone $(browserURL)

it prompted for my username and then my password

It worked fine then

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

javascript find and remove object in array based on key value

I agree with the answers, a simple way if you want to find an object by id and remove it is simply like below code.

   var obj = JSON.parse(data);
   var newObj = obj.filter(item=>item.Id!=88);
       

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

This is not an error. This is a warning. The difference is pretty huge. This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.

Eclipse WTP adds a custom attribute source to the project related <Context> element in the server.xml of Tomcat which identifies the source of the context (the actual project in the workspace which is deployed to the particular server). This way Eclipse can correlate the deployed webapplication with an project in the workspace. Since Tomcat version 6.0.16, any unspecified XML tags and attributes in the server.xml will produce a warning during Tomcat's startup, even though there is no DTD nor XSD for server.xml.

Just ignore it. Your web project is fine. It should run fine. This issue is completely unrelated to JSF.

How to invoke bash, run commands inside the new shell, and then give control back to user?

Append to ~/.bashrc a section like this:

if [ "$subshell" = 'true' ]
then
    # commands to execute only on a subshell
    date
fi
alias sub='subshell=true bash'

Then you can start the subshell with sub.

How can I calculate an md5 checksum of a directory?

If you want one md5sum spanning the whole directory, I would do something like

cat *.py | md5sum 

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path (make sure you use this in the script context).

The reason you should use that and not anything else can be illustrated with this example script.

## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path

Here are some results.

PS C:\Users\JasonAr> .\ScriptTest.ps1
InvocationName: .\ScriptTest.ps1
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> . .\ScriptTest.ps1
InvocationName: .
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> & ".\ScriptTest.ps1"
InvocationName: &
Path: C:\Users\JasonAr\ScriptTest.ps1

In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot:

## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1
Script: C:\Users\jarcher\ScriptTest.ps1
Path: C:\Users\jarcher

How to change background and text colors in Sublime Text 3

  1. Go to the preferences
  2. Click on color scheme
  3. Choose your color scheme
  4. I chose plastic, for my case.

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

Fatal error: Call to undefined function curl_init()

On old versions of Debian and Ubuntu, you solved this by installing the Curl extension for PHP, and restarting the webserver. Assuming the webserver is Apache 2:

sudo apt-get install php5-curl
sudo service apache2 restart

On newer versions, the package name as changed:

sudo apt install php-curl

It's possible you'll need to install more:

sudo apt-get install curl libcurl3 libcurl3-dev;

Can we write our own iterator in Java?

This is the complete code to write an iterator such that it iterates over elements that begin with 'a':

import java.util.Iterator;

public class AppDemo {

    public static void main(String args[]) {

        Bag<String> bag1 = new Bag<>();

        bag1.add("alice");
        bag1.add("bob"); 
        bag1.add("abigail");
        bag1.add("charlie"); 

        for (Iterator<String> it1 = bag1.iterator(); it1.hasNext();) {

            String s = it1.next();
            if (s != null)
                System.out.println(s); 
        }
    }
}

Custom Iterator class

import java.util.ArrayList;
import java.util.Iterator;

public class Bag<T> {

    private ArrayList<T> data;

    public Bag() {

        data = new ArrayList<>();
    }

    public void add(T e) {

        data.add(e); 
    }

    public Iterator<T> iterator() {

        return new BagIterator();
    }

    public class BagIterator<T> implements Iterator<T> {

        private int index; 
        private String str;

        public BagIterator() {

            index = 0;
        }

        @Override
        public boolean hasNext() {

             return index < data.size();  
        }

        @Override
        public T next() {

            str = (String) data.get(index); 
            if (str.startsWith("a"))
                return (T) data.get(index++); 
            index++; 
            return null; 
        }
    } 
}

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

Vertically align text next to an image?

Using flex property in css.

To align text vertically center by using in flex using align-items:center; if you want to align text horizontally center by using in flex using justify-content:center;.

_x000D_
_x000D_
div{
  display: flex;
  align-items: center;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Using table-cell in css.

_x000D_
_x000D_
div{
  display: table;
}
div *{
  display: table-cell;
  vertical-align: middle;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.

Passing HTML input value as a JavaScript Function Parameter

   <form action="" onsubmit="additon()" name="form1" id="form1">
      a: <input type="number" name="a" id="a"><br>
      b: <input type="number" name="b" id="b"><br>
      <input type="submit" value="Submit" name="submit">
   </form>
  <script>
      function additon() 
      {
           var a = document.getElementById('a').value;
           var b = document.getElementById('b').value;
           var sum = parseInt(a) + parseInt(b);
           return sum;
      }
  </script>

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

What are good examples of genetic algorithms/genetic programming solutions?

It was a while ago, but I rolled a GA to evolve what were in effect image processing kernels to remove cosmic ray traces from Hubble Space Telescope (HST) images. The standard approach is to take multiple exposures with the Hubble and keep only the stuff that is the same in all the images. Since HST time is so valuable, I'm an astronomy buff, and had recently attended the Congress on Evolutionary Computation, I thought about using a GA to clean up single exposures.

The individuals were in the form of trees that took a 3x3 pixel area as input, performed some calculations, and produced a decision about whether and how to modify the center pixel. Fitness was judged by comparing the output with an image cleaned up in the traditional way (i.e. stacking exposures).

It actually sort of worked, but not well enough to warrant foregoing the original approach. If I hadn't been time-constrained by my thesis, I might have expanded the genetic parts bin available to the algorithm. I'm pretty sure I could have improved it significantly.

Libraries used: If I recall correctly, IRAF and cfitsio for astronomical image data processing and I/O.

How do I merge my local uncommitted changes into another Git branch?

Since your files are not yet committed in branch1:

git stash
git checkout branch2
git stash pop

or

git stash
git checkout branch2
git stash list       # to check the various stash made in different branch
git stash apply x    # to select the right one

As commented by benjohn (see git stash man page):

To also stash currently untracked (newly added) files, add the argument -u, so:

git stash -u

The Use of Multiple JFrames: Good or Bad Practice?

I'm just wondering whether it is good practice to use multiple JFrames?

Bad (bad, bad) practice.

  • User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..
  • A nightmare to code and maintain:
    • A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.
    • A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.

There are any number of ways of displaying many elements in one GUI, e.g.:

  • CardLayout (short demo.). Good for:
    1. Showing wizard like dialogs.
    2. Displaying list, tree etc. selections for items that have an associated component.
    3. Flipping between no component and visible component.
  • JInternalFrame/JDesktopPane typically used for an MDI.
  • JTabbedPane for groups of components.
  • JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.
  • JLayeredPane far many well ..layered components.
  • JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.
  • As items in a JList (simple example below).
  • As nodes in a JTree.
  • Nested layouts.

But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.

Many images

In this case where the multiple elements are images, it would be better to use either of the following instead:

  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.
  2. A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).

What is the difference between max-device-width and max-width for mobile web?

max-device-width is the device rendering width

@media all and (max-device-width: 400px) {
    /* styles for devices with a maximum width of 400px and less
       Changes only on device orientation */
}

@media all and (max-width: 400px) {
    /* styles for target area with a maximum width of 400px and less
       Changes on device orientation , browser resize */
}

The max-width is the width of the target display area means the current size of browser.

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

Attach the Java Source Code

What worked for me (with JDK7) was the following:

  1. Download the openjdk-xy-sources.jar from GrepCode,
  2. rename the file to src.zip,
  3. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  4. restart eclipse

Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.

If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:

  1. Download the JDK sources from here,
  2. extract all folders from the zip file's *openjdk\jdk\src\share\classes* folder,
  3. create a file src.zip and add these folders to it,
  4. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  5. restart eclipse

A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.

'Java' is not recognized as an internal or external command

In my case, PATH was properly SET but PATHEXT has been cleared by me by mistake with .exe extension. That why window can't find java or anything .exe application from command prompt. Hope it can help someone.

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Django ChoiceField

First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like choices.py:

STATUS_CHOICES = (
    (1, _("Not relevant")),
    (2, _("Review")),
    (3, _("Maybe relevant")),
    (4, _("Relevant")),
    (5, _("Leading candidate"))
)
RELEVANCE_CHOICES = (
    (1, _("Unread")),
    (2, _("Read"))
)

Now you need to import them on the models, so the code is easy to understand like this(models.py):

from myApp.choices import * 

class Profile(models.Model):
    user = models.OneToOneField(User)    
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)   
    relevance = models.IntegerField(choices=RELEVANCE_CHOICES, default=1)

And you have to import the choices in the forms.py too:

forms.py:

from myApp.choices import * 

class CViewerForm(forms.Form):

    status = forms.ChoiceField(choices = STATUS_CHOICES, label="", initial='', widget=forms.Select(), required=True)
    relevance = forms.ChoiceField(choices = RELEVANCE_CHOICES, required=True)

Anyway you have an issue with your template, because you're not using any {{form.field}}, you generate a table but there is no inputs only hidden_fields.

When the user is staff you should generate as many input fields as users you can manage. I think django form is not the best solution for your situation.

I think it will be better for you to use html form, so you can generate as many inputs using the boucle: {% for user in users_list %} and you generate input with an ID related to the user, and you can manage all of them in the view.

How do I insert datetime value into a SQLite database?

Read This: 1.2 Date and Time Datatype best data type to store date and time is:

TEXT best format is: yyyy-MM-dd HH:mm:ss

Then read this page; this is best explain about date and time in SQLite. I hope this help you

Connect to Amazon EC2 file directory using Filezilla and SFTP

If anyone is following all the steps and having no success, make sure that you are using the correct user. I was attempting to use "ec2-user" but I needed to use "ubuntu."

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

How do you remove Subversion control for a folder?

For those using NetBeans with SVN, there is an option 'Subversion > Export'.

How to apply color in Markdown?

I've had success with

<span class="someclass"></span>

Caveat : the class must already exist on the site.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I ran to a similar error running Excel in VBA, what I've learned is that when I pull data from MSSQL, and then using get_range and .Value2 apply it's out of the range, any value that was of type uniqueidentifier (GUID) resulted in this error. Only when I cast the value to nvarcahr(max) it worked.

How do I efficiently iterate over each entry in a Java Map?

Java 8:

You can use lambda expressions:

myMap.entrySet().stream().forEach((entry) -> {
    Object currentKey = entry.getKey();
    Object currentValue = entry.getValue();
});

For more information, follow this.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

I found that putting this section in my web.config for each view folder solved it.

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="4.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

Eclipse error: "The import XXX cannot be resolved"

Removing the "module-info.java" did resolve the issue for me!

This file was automatically generated and did appear in my hierarchy...

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

minimize app to system tray

...and for your right click notification menu add a context menu to the form and edit it and set mouseclick events for each of contextmenuitems by double clicking them and then attach it to the notifyicon1 by selecting the ContextMenuStrip in notifyicon property.

Running a command in a new Mac OS X Terminal window

Here's my awesome script, it creates a new terminal window if needed and switches to the directory Finder is in if Finder is frontmost. It has all the machinery you need to run commands.

on run
    -- Figure out if we want to do the cd (doIt)
    -- Figure out what the path is and quote it (myPath)
    try
        tell application "Finder" to set doIt to frontmost
        set myPath to finder_path()
        if myPath is equal to "" then
            set doIt to false
        else
            set myPath to quote_for_bash(myPath)
        end if
    on error
        set doIt to false
    end try

    -- Figure out if we need to open a window
    -- If Terminal was not running, one will be opened automatically
    tell application "System Events" to set isRunning to (exists process "Terminal")

    tell application "Terminal"
        -- Open a new window
        if isRunning then do script ""
        activate
        -- cd to the path
        if doIt then
            -- We need to delay, terminal ignores the second do script otherwise
            delay 0.3
            do script " cd " & myPath in front window
        end if
    end tell
end run

on finder_path()
    try
        tell application "Finder" to set the source_folder to (folder of the front window) as alias
        set thePath to (POSIX path of the source_folder as string)
    on error -- no open folder windows
        set thePath to ""
    end try

    return thePath
end finder_path

-- This simply quotes all occurrences of ' and puts the whole thing between 's
on quote_for_bash(theString)
    set oldDelims to AppleScript's text item delimiters
    set AppleScript's text item delimiters to "'"
    set the parsedList to every text item of theString
    set AppleScript's text item delimiters to "'\\''"
    set theString to the parsedList as string
    set AppleScript's text item delimiters to oldDelims
    return "'" & theString & "'"
end quote_for_bash

git: Your branch is ahead by X commits

I actually had this happening when I was doing a switch/checkout with TortiseGIT.

My problem was that I had created the branch based on another local branch. It created a "merge" entry in /.git/config that looked something like this:

[branch "web"]
    merge = refs/heads/develop
    remote = gitserver

Where whenever I switched to the "web" branch, it was telling me I was 100+ commits ahead of develop. Well, I was no longer committing to develop so that was true. I was able to simply remove this entry and it seems to be functioning as expected. It is properly tracking with the remote ref instead of complaining about being behind the develop branch.

As Vikram said, this Stack Overflow thread is the top result in Google when searching for this problem so I thought I'd share my situation and solution.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

how to insert value into DataGridView Cell?

int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

hope this help! :)

Python: access class property from string

Extending Alex's answer slightly:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")

will yield:

[1, 2, 3]
[4, 5, 6]

However, personally I don't think that's great style - getattr will let you access any attribute of the instance, including things like the doSomething method itself, or even the __dict__ of the instance. I would suggest that instead you implement a dictionary of data sources, like so:

class User:
    def __init__(self):

        self.data_sources = {
            "data": [1,2,3],
            "other_data":[4,5,6],
        }

    def doSomething(self, source):
        dataSource = self.data_sources[source]
        return dataSource

A = User()

print A.doSomething("data")
print A.doSomething("other_data")

again yielding:

[1, 2, 3]
[4, 5, 6]

Java: Clear the console

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

HTML5 placeholder css padding

If you want to keep your line-height and force the placeholder to have the same, you can directly edit the placeholder CSS since the newer browser versions. That did the trick for me:

input::-webkit-input-placeholder { /* WebKit browsers */
  line-height: 1.5em;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
  line-height: 1.5em;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
  line-height: 1.5em;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
  line-height: 1.5em;
}

How to use Tomcat 8 in Eclipse?

If you have untarred your own version of tomcat v8 with a root user into a custom directory (linux) then the default permissions on the TOMCATROOT/lib directory do not allow normal user access.

Eclipse will not be able to see the catalina.jar to check the version. So no amount of fiddling aorund with the server.properties will help!

just add chmod u+x lib/ to allow normal user access to the libs.

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

How do you unit test private methods?

For JAVA language

Here, you can over-ride a particular method of the testing class with mock behavior.

For the below code:

public class ClassToTest 
{
    public void methodToTest()
    {
        Integer integerInstance = new Integer(0);
        boolean returnValue= methodToMock(integerInstance);
        if(returnValue)
        {
            System.out.println("methodToMock returned true");
        }
        else
        {
            System.out.println("methodToMock returned true");
        }
        System.out.println();
    }
    private boolean methodToMock(int value)
    {
        return true;
    }
}

Test class would be:

public class ClassToTestTest{

    @Test
    public void testMethodToTest(){

        new Mockup<ClassToTest>(){
            @Mock
            private boolean methodToMock(int value){
                return true;
            }
        };

        ....    

    }
}

How to set the max size of upload file

For Spring Boot 2.+, make sure you are using spring.servlet instead of spring.http.

---
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.

If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.

How to link an image and target a new window

you can do like this

<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>

find this page

http://www.corelangs.com/html/links/new-window.html

goreb

How to truncate a foreign key constrained table?

Yes you can:

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE table1;
TRUNCATE table2;

SET FOREIGN_KEY_CHECKS = 1;

With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY constraints.

How to inject a Map using the @Value Spring Annotation?

You can inject .properties as a map in your class using @Resource annotation.

If you are working with XML based configuration, then add below bean in your spring configuration file:

 <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

Then you can pick them up in your application as a Map:

@Resource(name = "myProperties")
private Map<String, String> myProperties;

File Not Found when running PHP with Nginx

try this command

sudo chmod 755 -R htdocs/

Viewing full output of PS command

Using the auxww flags, you will see the full path to output in both your terminal window and from shell scripts.

darragh@darraghserver ~ $uname -a
SunOS darraghserver 5.10 Generic_142901-13 i86pc i386 i86pc

darragh@darraghserver ~ $which ps
/usr/bin/ps<br>

darragh@darraghserver ~ $/usr/ucb/ps auxww | grep ps
darragh 13680  0.0  0.0 3872 3152 pts/1    O 14:39:32  0:00 /usr/ucb/ps -auxww
darragh 13681  0.0  0.0 1420  852 pts/1    S 14:39:32  0:00 grep ps

ps aux lists all processes executed by all users. See man ps for details. The ww flag sets unlimited width.

-w         Wide output. Use this option twice for unlimited width.
w          Wide output. Use this option twice for unlimited width.

I found the answer on the following blog:
http://www.snowfrog.net/2010/06/10/solaris-ps-output-truncated-at-80-columns/

Generating random numbers with normal distribution in Excel

As @osknows said in a comment above (rather than an answer which is why I am adding this), the Analysis Pack includes Random Number Generation functions (e.g. NORM.DIST, NORM.INV) to generate a set of numbers. A good summary link is at http://www.bettersolutions.com/excel/EUN147/YI231420881.htm.