Programs & Examples On #Abaddressbook

The ABAddressBook opaque type provides a programming interface to the Address Book — a centralized database used by multiple applications to store personal information about people. Available on iOS 2.0 or above , and Mac OS X

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Move the most recent commit(s) to a new branch with Git

Much simpler solution using git stash

Here's a far simpler solution for commits to the wrong branch. Starting on branch master that has three mistaken commits:

git reset HEAD~3
git stash
git checkout newbranch
git stash pop

When to use this?

  • If your primary purpose is to roll back master
  • You want to keep file changes
  • You don't care about the messages on the mistaken commits
  • You haven't pushed yet
  • You want this to be easy to memorize
  • You don't want complications like temporary/new branches, finding and copying commit hashes, and other headaches

What this does, by line number

  1. Undoes the last three commits (and their messages) to master, yet leaves all working files intact
  2. Stashes away all the working file changes, making the master working tree exactly equal to the HEAD~3 state
  3. Switches to an existing branch newbranch
  4. Applies the stashed changes to your working directory and clears the stash

You can now use git add and git commit as you normally would. All new commits will be added to newbranch.

What this doesn't do

  • It doesn't leave random temporary branches cluttering your tree
  • It doesn't preserve the mistaken commit messages, so you'll need to add a new commit message to this new commit
  • Update! Use up-arrow to scroll through your command buffer to reapply the prior commit with its commit message (thanks @ARK)

Goals

The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.

I do this at least once a week when I accidentally make new commits to master instead of develop. Usually I have only one commit to rollback in which case using git reset HEAD^ on line 1 is a simpler way to rollback just one commit.

Don't do this if you pushed master's changes upstream

Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.

Find integer index of rows with NaN in pandas dataframe

For DataFrame df:

import numpy as np
index = df['b'].index[df['b'].apply(np.isnan)]

will give you back the MultiIndex that you can use to index back into df, e.g.:

df['a'].ix[index[0]]
>>> 1.452354

For the integer index:

df_index = df.index.values.tolist()
[df_index.index(i) for i in index]
>>> [3, 6]

Android button onClickListener

Use OnClicklistener or you can use android:onClick="myMethod" in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod function in class look like this.

public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}

And in that SecondActivity.class set new layout in contentview.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

OR YOU CAN USE ANOTHER WAY

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES 
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

PHP equivalent of .NET/Java's toString()

You can always create a method named .ToString($in) that returns

$in . '';  

Defining static const integer members in class definition

C++ allows static const members to be defined inside a class

Nope, 3.1 §2 says:

A declaration is a definition unless it declares a function without specifying the function's body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), or a using-directive (7.3.4).

How to set the From email address for mailx command?

The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.

-a "From: Foo Bar <[email protected]>"

Can't start Tomcat as Windows Service

I have the problem because I updated Java version.

The following steps work for me:

  1. Run \Tomcat\bin\tomcat7w.exe
  2. Confirm "Startup" tab -> "Mode" choose "jvm"
  3. "Java" tab -> update "Java Virtual Machine" path to new version path
  4. Restart Tomcat

Done.

Trying to use Spring Boot REST to Read JSON String from POST

The issue appears with parsing the JSON from request body, tipical for an invalid JSON. If you're using curl on windows, try escaping the json like -d "{"name":"value"}" or even -d "{"""name""":"value"""}"

On the other hand you can ommit the content-type header in which case whetewer is sent will be converted to your String argument

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I am using Visual Studio 2013 Update 2. In my case, I have a web project and a Web Api project and unit test project and other class libraries in a single solution.

I've spent couple of days to solve the problem. Below is the step-by-step solution that I have found.

  1. Right click on Web Api project. Select "Set as StartUp Project"
  2. Right click on Web Api project. Go to Properties ( Alt + Enter ).
  3. On the Application tab on left hand side menu, select Application
  4. Find Target framework. Change it to 4.5.1 and save. However, it is showing error in "Error List" window. After Rebuild, there is no error.
  5. Remove all Newtonsoft.Json packs from solution by using below query from Package Manager Console ( to get it View > Other Window > Package Manager Console ).

uninstall-package newtonsoft.json -force

  1. Reinstall Newtonsoft.Json from Package Manager Console

install-package newtonsoft.json

  1. If you have latest update for Visual Studio 2013, you might not encounter with this problem. As I am using Update 2, so, while trying to install Newtonsoft.Json, I have encountered with the following error.

The 'Newtonsoft.Json 10.0.3' package requires NuGet client version '2.12' or above, but the current NuGet version i s '2.8.50313.46'

  1. To solve this problem, we need to update the Package Manager Console. Got to

Tools > Extensions and Updates... > In left pane.. select Updates > Visual Studio Gallery.

  1. Update the NuGet Package Manager Extension. Follow the steps that are coming afterwards.

  2. Visual Studio will take a restart after that.

  3. Execute step 6 again.

After Installation packages.config will be added with this below line

  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net451" />

After installation web.config will be added with this below lines

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>

It will execute successfully, if there is no other error.

Insert data into a view (SQL Server)

Looks like you are running afoul of this rule for updating views from Books Online: "INSERT statements must specify values for any columns in the underlying table that do not allow null values and have no DEFAULT definitions."

How to store a list in a column of a database table

You can just forget SQL all together and go with a "NoSQL" approach. RavenDB, MongoDB and CouchDB jump to mind as possible solutions. With a NoSQL approach, you are not using the relational model..you aren't even constrained to schemas.

Write bytes to file

Try this:

private byte[] Hex2Bin(string hex) 
{
 if ((hex == null) || (hex.Length < 1)) {
  return new byte[0];
 }
 int num = hex.Length / 2;
 byte[] buffer = new byte[num];
 num *= 2;
 for (int i = 0; i < num; i++) {
  int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
  buffer[i / 2] = (byte) num3;
  i++;
 }
 return buffer;
}

private string Bin2Hex(byte[] binary) 
{
 StringBuilder builder = new StringBuilder();
 foreach(byte num in binary) {
  if (num > 15) {
   builder.AppendFormat("{0:X}", num);
  } else {
   builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
  }
 }
 return builder.ToString();
}

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

Convert between UIImage and Base64 string

Swift 5, Xcode 10.

_x000D_
_x000D_
 let imageData = UIImage(named:"imagename").pngData()?.base64EncodedString(options: .lineLength64Characters)_x000D_
_x000D_
print(imageData)
_x000D_
_x000D_
_x000D_

How to create a stopwatch using JavaScript?

well after a few modification of the code provided by mace,i ended up building a stopwatch. https://codepen.io/truestbyheart/pen/EGELmv

  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Stopwatch</title>
    <style>
    #center {
     margin: 30%  30%;
     font-family: tahoma;
     }
    .stopwatch {
         border:1px solid #000;
         background-color: #eee;
         text-align: center;
         width:656px;
         height: 230px;
         overflow: hidden;
     }
     .stopwatch span{
         display: block;
         font-size: 100px;
     }
     .stopwatch p{
         display: inline-block;
         font-size: 40px;
     }
     .stopwatch a{
       font-size:45px;
     }
     a:link,
     a:visited{
         color :#000;
         text-decoration: none;
         padding: 12px 14px;
         border: 1px solid #000;
     }
    </style>
  </head>
  <body>
      <div id="center">
            <div class="timer stopwatch"></div>
      </div>

    <script>
      const Stopwatch = function(elem, options) {
        let timer = createTimer(),
          startButton = createButton("start", start),
          stopButton = createButton("stop", stop),
          resetButton = createButton("reset", reset),
          offset,
          clock,
          interval,
          hrs = 0,
          min = 0;

        // default options
        options = options || {};
        options.delay = options.delay || 1;

        // append elements
        elem.appendChild(timer);
        elem.appendChild(startButton);
        elem.appendChild(stopButton);
        elem.appendChild(resetButton);

        // initialize
        reset();

        // private functions
        function createTimer() {
          return document.createElement("span");
        }

        function createButton(action, handler) {
          if (action !== "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              handler();
              event.preventDefault();
            });
            return a;
          } else if (action === "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              clean();
              event.preventDefault();
            });
            return a;
          }
        }

        function start() {
          if (!interval) {
            offset = Date.now();
            interval = setInterval(update, options.delay);
          }
        }

        function stop() {
          if (interval) {
            clearInterval(interval);
            interval = null;
          }
        }

        function reset() {
          clock = 0;
          render(0);
        }

        function clean() {
          min = 0;
          hrs = 0;
          clock = 0;
          render(0);
        }

        function update() {
          clock += delta();
          render();
        }

        function render() {
          if (Math.floor(clock / 1000) === 60) {
            min++;
            reset();
            if (min === 60) {
              min = 0;
              hrs++;
            }
          }
          timer.innerHTML =
            hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
        }

        function delta() {
          var now = Date.now(),
            d = now - offset;

          offset = now;
          return d;
        }
      };

      // Initiating the Stopwatch
      var elems = document.getElementsByClassName("timer");

      for (var i = 0, len = elems.length; i < len; i++) {
        new Stopwatch(elems[i]);
      }
    </script>
  </body>
</html>

What does Visual Studio mean by normalize inconsistent line endings?

When you copy paste something from web, you might get the inconsistent line endings.
In order to fix this, you can use Visual studio extension "Line Endings Unifier" which can make line ending consistent automatically while saving file.

enter image description here

Random / noise functions for GLSL

Please see below an example how to add white noise to the rendered texture. The solution is to use two textures: original and pure white noise, like this one: wiki white noise

private static final String VERTEX_SHADER =
    "uniform mat4 uMVPMatrix;\n" +
    "uniform mat4 uMVMatrix;\n" +
    "uniform mat4 uSTMatrix;\n" +
    "attribute vec4 aPosition;\n" +
    "attribute vec4 aTextureCoord;\n" +
    "varying vec2 vTextureCoord;\n" +
    "varying vec4 vInCamPosition;\n" +
    "void main() {\n" +
    "    vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
    "    gl_Position = uMVPMatrix * aPosition;\n" +
    "}\n";

private static final String FRAGMENT_SHADER =
        "precision mediump float;\n" +
        "uniform sampler2D sTextureUnit;\n" +
        "uniform sampler2D sNoiseTextureUnit;\n" +
        "uniform float uNoseFactor;\n" +
        "varying vec2 vTextureCoord;\n" +
        "varying vec4 vInCamPosition;\n" +
        "void main() {\n" +
                "    gl_FragColor = texture2D(sTextureUnit, vTextureCoord);\n" +
                "    vec4 vRandChosenColor = texture2D(sNoiseTextureUnit, fract(vTextureCoord + uNoseFactor));\n" +
                "    gl_FragColor.r += (0.05 * vRandChosenColor.r);\n" +
                "    gl_FragColor.g += (0.05 * vRandChosenColor.g);\n" +
                "    gl_FragColor.b += (0.05 * vRandChosenColor.b);\n" +
        "}\n";

The fragment shared contains parameter uNoiseFactor which is updated on every rendering by main application:

float noiseValue = (float)(mRand.nextInt() % 1000)/1000;
int noiseFactorUniformHandle = GLES20.glGetUniformLocation( mProgram, "sNoiseTextureUnit");
GLES20.glUniform1f(noiseFactorUniformHandle, noiseFactor);

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

How to remove all numbers from string?

Regex

   $words = preg_replace('#[0-9 ]*#', '', $words);

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You guys copied the wrong code.

Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)

What is the difference between Sessions and Cookies in PHP?

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.

You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.

Screenshot of a Cookie

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

How do I make a Docker container start automatically on system boot?

You can run a container that restart always by:

$ docker run -dit --restart unless-stopped <image name OR image hash>

If you want to change a running container's configs, you should update it by:

$ docker update --restart=<options> <container ID OR name>

And if you want to see current policy of the container, run the following command before above at the first place:

docker inspect gateway | grep RestartPolicy -A 3

After all, Not to forget to make installed docker daemon enable at system boot by:

$ systemctl enable docker

To see a full list of restart policies, see: Restart Policies

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

how to delete the content of text file without deleting itself

You can use

FileWriter fw = new FileWriter(/*your file path*/);
PrintWriter pw = new PrintWriter(fw);
pw.write("");
pw.flush(); 
pw.close();

Remember not to use

FileWriter fw = new FileWriter(/*your file path*/,true);

True in the filewriter constructor will enable append.

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

How to get a reversed list view on a list in Java?

Collections.reverse(nums) ... It actually reverse the order of the elements. Below code should be much appreciated -

List<Integer> nums = new ArrayList<Integer>();
nums.add(61);
nums.add(42);
nums.add(83);
nums.add(94);
nums.add(15);
//Tosort the collections uncomment the below line
//Collections.sort(nums); 

Collections.reverse(nums);

System.out.println(nums);

Output: 15,94,83,42,61

How to set editor theme in IntelliJ Idea

IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar files.

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Define static method in source-file with declaration in header-file in C++

Remove static keyword in method definition. Keep it just in your class definition.

static keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

Python String and Integer concatenation

Concatenation of a string and integer is simple: just use

abhishek+str(2)

How to completely DISABLE any MOUSE CLICK

You can overlay a big, semi-transparent <div> that takes all the clicks. Just append a new <div> to <body> with this style:

.overlay {
    background-color: rgba(1, 1, 1, 0.7);
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
}

How to save a new sheet in an existing excel file, using Pandas?

I would strongly recommend you work directly with openpyxl since it now supports Pandas DataFrames.

This allows you to concentrate on the relevant Excel and Pandas code.

django - get() returned more than one topic

To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

def updateUserCollection(request):
    data = json.loads(request.body)
    card_id = data['card_id']
    action = data['action']

    user = request.user
    card = Cards.objects.get(card_id=card_id)

    if data-action == 'add':
        collection = Collection.objects.get_or_create(user=user, card=card)
        collection.quantity + 1
        collection.save()

    elif data-action == 'remove':
        collection = Cards.objects.filter(user=user, card=card)
        collection.quantity = 0
        collection.update()

Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

Border color on default input style

If I understand your question correctly this should solve it:

http://jsfiddle.net/wvk2mnsf/

HTML - create a simple input field.

<input type="text" id="giraffe" />

CSS - clear out the native outline so you can set your own and it doesn't look weird with a bluey red outline.

input:focus {
    outline: none;
}
.error-input-border {
    border: 1px solid #FF0000;
}

JS - on typing in the field set red border class declared in the CSS

document.getElementById('giraffe').oninput = function() { this.classList.add('error-input-border'); }

This has a lot of information on the latest standards too: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

Regular expression to match any character being repeated more than 10 times

use the {10,} operator:

$: cat > testre
============================
==
==============

$: grep -E '={10,}' testre
============================
==============

What is the Ruby <=> (spaceship) operator?

Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or -1 depending on the value of the left argument relative to the right argument.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

It's useful for sorting an array.

How to read until EOF from cin in C++

Probable simplest and generally efficient:

#include <iostream>
int main()
{
    std::cout << std::cin.rdbuf();
}

If needed, use stream of other types like std::ostringstream as buffer instead of standard output stream here.

Can I remove the URL from my print css, so the web address doesn't print?

Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.

http://css-discuss.incutio.com/wiki/Print_Stylesheets#Print_headers.2Ffooters_and_print_margins

However, as of 2017, the @page at-rule has been standardized, which can be used to hide the page title and date in modern browsers:

@page { size: auto; margin: 0mm; }

Credit to Vigneswaran S for this tip.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

If you are migrated for AndroidX and getting this error, you need to set the compile SDK to Android 9.0 (API level 28) or higher

How can I change the font-size of a select option?

Tell the option element to be 13pt

select option{
    font-size: 13pt;
}

and then the first option element to be 7pt

select option:first-child {
    font-size: 7pt;
}

Running demo: http://jsfiddle.net/VggvD/1/

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

C# - Substring: index and length must refer to a location within the string

How about something like this :

string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension =  Path.GetExtension(path_Query);

path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • Install apps silently, with granted INSTALL_PACKAGES permission

    An 3rd party application cannot install an Android App sliently. However, a 3rd party application can ask the Android OS to install a application.

    So you should define this:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file:///sdcard/app.apk", "application/vnd.android.package-archive");
    startActivity(intent);
    

    You can also try to install it as a system app to grant the permission and ignore this define. (Root Required)

    You can run the following command on your 3rd party app to install an app on the rooted device.

    The code is:

    private void installApk(String filename) {
    File file = new File(filename); 
    if(file.exists()){
        try {   
            final String command = "pm install -r " + file.getAbsolutePath();
            Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
     }
    }
    

    I hope that this answer is helpful for you.

    How to check if activity is in foreground or in visible background?

    Use the time gap between pause and resume from background to determine whether it is awake from background

    In Custom Application

    private static boolean isInBackground;
    private static boolean isAwakeFromBackground;
    private static final int backgroundAllowance = 10000;
    
    public static void activityPaused() {
        isInBackground = true;
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isInBackground) {
                    isAwakeFromBackground = true;
                }
            }
        }, backgroundAllowance);
        Log.v("activity status", "activityPaused");
    }
    
    public static void activityResumed() {
        isInBackground = false;
        if(isAwakeFromBackground){
            // do something when awake from background
            Log.v("activity status", "isAwakeFromBackground");
        }
        isAwakeFromBackground = false;
        Log.v("activity status", "activityResumed");
    }
    

    In BaseActivity Class

    @Override
    protected void onResume() {
      super.onResume();
      MyApplication.activityResumed();
    }
    
    @Override
    protected void onPause() {
      super.onPause();
      MyApplication.activityPaused();
    }
    

    Swift UIView background color opacity

    The question is old, but it seems that there are people who have the same concerns.

    What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?


    The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.

    As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.

    self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)
    

    extension is

    extension UIColor {
        convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
            self.init(red: CGFloat(red) / 255.0,
                      green: CGFloat(green) / 255.0,
                      blue: CGFloat(blue) / 255.0,
                      alpha: alpha)
        }
    }
    

    However, the actual view was

    • 'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
    • 'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8

    Calculating it,

    • 0x12 = 18(decimal)
    • 18/255 = 0.07058...
    • 255 * 0.09 = 22.95
    • 23(decimal) = 0x17

    So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.

    self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)
    

    Or can anyone tell me what I'm missing?

    How to change navbar/container width? Bootstrap 3

    Hello this working you try! in your case is .navbar-fixed-top{}

    .navbar-fixed-bottom{
        width:1200px;
        left:20%;
    }
    

    Should I use typescript? or I can just use ES6?

    Decision tree between ES5, ES6 and TypeScript

    Do you mind having a build step?

    • Yes - Use ES5
    • No - keep going

    Do you want to use types?

    • Yes - Use TypeScript
    • No - Use ES6

    More Details

    ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

    ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

    TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

    Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

    Changing the tmp folder of mysql

    This is answered in the documentation:

    Where MySQL Stores Temporary Files

    On Unix, MySQL uses the value of the TMPDIR environment variable as the path name of the directory in which to store temporary files. If TMPDIR is not set, MySQL uses the system default, which is usually /tmp, /var/tmp, or /usr/tmp.

    On Windows, Netware and OS2, MySQL checks in order the values of the TMPDIR, TEMP, and TMP environment variables. For the first one found to be set, MySQL uses it and does not check those remaining. If none of TMPDIR, TEMP, or TMP are set, MySQL uses the Windows system default, which is usually C:\windows\temp.

    Finding the source code for built-in Python functions?

    Quite an unknown resource is the Python Developer Guide.

    In a (somewhat) recent GH issue, a new chapter was added for to address the question you're asking: CPython Source Code Layout. If something should change, that resource will also get updated.

    Creating a system overlay window (always on top)

    This is an old Question but recently Android has a support for Bubbles. Bubbles are soon going to be launched but currently developers can start using them.They are designed to be an alternative to using SYSTEM_ALERT_WINDOW. Apps like (Facebook Messenger and MusiXMatch use the same concept).

    Bubbles

    Bubbles are created via the Notification API, you send your notification as normal. If you want it to bubble you need to attach some extra data to it. For more information about Bubbles you can go to the official Android Developer Guide on Bubbles.

    VB.NET - If string contains "value1" or "value2"

    You have ("Something2") by itself - you need to test it so a boolean is returned:

    If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
    

    Creating your own header file in C

    foo.h

    #ifndef FOO_H_   /* Include guard */
    #define FOO_H_
    
    int foo(int x);  /* An example function declaration */
    
    #endif // FOO_H_
    

    foo.c

    #include "foo.h"  /* Include the header (not strictly necessary here) */
    
    int foo(int x)    /* Function definition */
    {
        return x + 5;
    }
    

    main.c

    #include <stdio.h>
    #include "foo.h"  /* Include the header here, to obtain the function declaration */
    
    int main(void)
    {
        int y = foo(3);  /* Use the function here */
        printf("%d\n", y);
        return 0;
    }
    

    To compile using GCC

    gcc -o my_app main.c foo.c
    

    What is the best way to get the first letter from a string in Java, returned as a string of length 1?

    Performance wise substring(0, 1) is better as found by following:

        String example = "something";
        String firstLetter  = "";
    
        long l=System.nanoTime();
        firstLetter = String.valueOf(example.charAt(0));
        System.out.println("String.valueOf: "+ (System.nanoTime()-l));
    
        l=System.nanoTime();
        firstLetter = Character.toString(example.charAt(0));
        System.out.println("Character.toString: "+ (System.nanoTime()-l));
    
        l=System.nanoTime();
        firstLetter = example.substring(0, 1);
        System.out.println("substring: "+ (System.nanoTime()-l));
    

    Output:

    String.valueOf: 38553
    Character.toString: 30451
    substring: 8660
    

    How do I unload (reload) a Python module?

    The following code allows you Python 2/3 compatibility:

    try:
        reload
    except NameError:
        # Python 3
        from imp import reload
    

    The you can use it as reload() in both versions which makes things simpler.

    How to implement a Keyword Search in MySQL?

    SELECT 
        *
    FROM 
        yourtable
    WHERE 
        id LIKE '%keyword%' 
        OR position LIKE '%keyword%'
        OR category LIKE '%keyword%'
        OR location LIKE '%keyword%'
        OR description LIKE '%keyword%'
        OR refno LIKE '%keyword%';
    

    What is so bad about singletons?

    Too many people put objects which are not thread safe in a singleton pattern. I've seen examples of a DataContext (LINQ to SQL) done in a singleton pattern, despite the fact that the DataContext is not thread safe and is purely a unit-of-work object.

    Position Relative vs Absolute?

    Another thing to note is that if you want a absolute element to be confined to a parent element then you need to set the parent element's position to relative. That will keep the child element contained within the parent element and it won't be "relative" to the entire window.

    I wrote a blog post that gives a simple example that creates the following affect:

    enter image description here

    That has a green div that is absolutely positioned to the bottom of the parent yellow div.

    1 http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/

    How do I hide anchor text without hiding the anchor?

    text-indent :-9999px 
    

    Works flawlessly.

    How do you add a JToken to an JObject?

    Just adding .First to your bananaToken should do it:
    foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
    .First basically moves past the { to make it a JProperty instead of a JToken.

    @Brian Rogers, Thanks I forgot the .Parent. Edited

    How to know if other threads have finished?

    Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:

    (1) I created the global variable: boolean end1 = false; The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.

    (2) My thread contains:

    void myThread() {
        end1 = false;
        new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
            public void onFinish()
            {
                // do stuff here once at end of time.
                end1 = true; // signal that the thread has ended.
            }
            public void onTick(long millisUntilFinished)
            {
              // do stuff here repeatedly.
            }
        }.start();
    
    }
    

    (3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.

    Handler h1 = new Handler();
    
    private void checkThread() {
       h1.postDelayed(new Runnable() {
          public void run() {
             if (end1)
                // resond to the second thread ending here.
             else
                h1.postDelayed(this, 1000);
          }
       }, 1000);
    }
    

    (4) Finally, start the whole thing running somewhere in your code by calling:

    void startThread()
    {
       myThread();
       checkThread();
    }
    

    java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

    localhost and 127.0.0.1 are both ways of saying 'the current machine'. So localhost on your PC is the PC and localhost on the android is the phone. Since your phone isn't running a webserver of course it will refuse the connection.

    You need to get the IP address of your machine (use ipconfig on windows to find out) and use that instead of 127.0.0.1. This may still not working depending on how your network/firewalls are set up. But that is a completely different topic.

    Attaching click to anchor tag in angular

    <a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>

    Set ImageView width and height programmatically?

    kotlin

    val density = Resources.getSystem().displayMetrics.density
    view.layoutParams.height = 20 * density.toInt()
    

    Gradle task - pass arguments to Java application

    Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use

    gradle run --args='foo --bar'

    See Also Gradle Application Plugin

    How to upgrade Gradle wrapper

    How can I make Bootstrap columns all the same height?

    There is a problem with using Solution 1 while appling it on only column in rows. Would like to improve Solution 1.

     [class^="col-"]:not([class*="-12"]){
          margin-bottom: -99999px;
          padding-bottom: 99999px;
      }
    

    (Sorry, can't comment Popnoodles's anwer. I have not enough reputations)

    Set default heap size in Windows

    Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

    Usage of MySQL's "IF EXISTS"

    The accepted answer works well and one can also just use the

    If Exists (...) Then ... End If; 
    

    syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert

    One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

    How to pass a value from one Activity to another in Android?

    Its simple If you are passing String X from A to B.
    A--> B

    In Activity A
    1) Create Intent
    2) Put data in intent using putExtra method of intent
    3) Start activity

    Intent i = new Intent(A.this, B.class);
    i.putExtra("MY_kEY",X);
    

    In Activity B
    inside onCreate method
    1) Get intent object
    2) Get stored value using key(MY_KEY)

    Intent intent = getIntent();
    String result = intent.getStringExtra("MY_KEY");
    

    This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call

    intent.getIntExtra("KEY");
    

    You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.

    TransactionTooLargeException

    How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.

    What are static factory methods?

    One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.

    The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.

    From Effective Java, Joshua Bloch(Item 1,page 6)

    dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

    This might be a problem because of having the older version of brew and installed byobu which require new dependency in order to solve this problem run the following command

    brew update && brew upgrade
    brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
    

    Replace invalid values with None in Pandas DataFrame

    df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
    df = df.where(df!='-', None)
    

    How do I prevent Conda from activating the base environment by default?

    The answer depends a little bit on the version of conda that you have installed. For versions of conda >= 4.4, it should be enough to deactivate the conda environment after the initialization, so add

    conda deactivate
    

    right underneath

    # <<< conda initialize <<<
    

    What's the difference between Docker Compose vs. Dockerfile

    In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.

    Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db and no longer by its IP.

    Sending GET request with Authentication headers using restTemplate

    A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

    @Configuration
    public class RestTemplateConfig {
    
        @Bean
        public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
                HttpHeaders headers = request.getHeaders();
                if (!headers.containsKey("Authorization")) {
                    String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                    request.getHeaders().add("Authorization", token);
                }
                return clientHttpRequestExecution.execute(request, body);
            });
            return restTemplate;
        }
    }
    

    Update query with PDO and MySQL

    Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

    $sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
    

    How to create a user in Django?

    Bulk user creation with set_password

    I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

    set_password is another way to generate the hashed passwords:

    def users_iterator():
        for i in range(nusers):
            is_superuser = (i == 0)
            user = User(
                first_name='First' + str(i),
                is_staff=is_superuser,
                is_superuser=is_superuser,
                last_name='Last' + str(i),
                username='user' + str(i),
            )
            user.set_password('asdfqwer')
            yield user
    
    class Command(BaseCommand):
        def handle(self, **options):
            User.objects.bulk_create(iter(users_iterator()))
    

    Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

    Tested in Django 1.9.

    Expression ___ has changed after it was checked

    I switched from AfterViewInit to AfterContentChecked and It worked for me.

    Here is the process

    1. Add dependency in your constructor:

      constructor (private cdr: ChangeDetectorRef) {}

    2. and call your login in implemented method code here:

       ngAfterContentChecked() {
           this.cdr.detectChanges();
        // call or add here your code
       }
      

    Connecting client to server using Socket.io

    You need to make sure that you add forward slash before your link to socket.io:

    <script src="/socket.io/socket.io.js"></script>
    

    Then in the view/controller just do:

    var socket = io.connect()
    

    That should solve your problem.

    In STL maps, is it better to use map::insert than []?

    If your application is speed critical i will advice using [] operator because it creates total 3 copies of the original object out of which 2 are temporary objects and sooner or later destroyed as.

    But in insert(), 4 copies of the original object are created out of which 3 are temporary objects( not necessarily "temporaries") and are destroyed.

    Which means extra time for: 1. One objects memory allocation 2. One extra constructor call 3. One extra destructor call 4. One objects memory deallocation

    If your objects are large, constructors are typical, destructors do a lot of resource freeing, above points count even more. Regarding readability, i think both are fair enough.

    The same question came into my mind but not over readability but speed. Here is a sample code through which I came to know about the point i mentioned.

    class Sample
    {
        static int _noOfObjects;
    
        int _objectNo;
    public:
        Sample() :
            _objectNo( _noOfObjects++ )
        {
            std::cout<<"Inside default constructor of object "<<_objectNo<<std::endl;
        }
    
        Sample( const Sample& sample) :
        _objectNo( _noOfObjects++ )
        {
            std::cout<<"Inside copy constructor of object "<<_objectNo<<std::endl;
        }
    
        ~Sample()
        {
            std::cout<<"Destroying object "<<_objectNo<<std::endl;
        }
    };
    int Sample::_noOfObjects = 0;
    
    
    int main(int argc, char* argv[])
    {
        Sample sample;
        std::map<int,Sample> map;
    
        map.insert( std::make_pair<int,Sample>( 1, sample) );
        //map[1] = sample;
        return 0;
    }
    

    Output when insert() is used Output when [] operator is used

    Function pointer as parameter

    You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

    ADB error: cannot connect to daemon

    Go to windows task manager and end process tree of adb. It will make attempts to start adb.

    Sometimes on Windows adb kill-server and adb start-server fail to start adb.

    In Bash, how do I add a string after each line in a file?

    I prefer using awk. If there is only one column, use $0, else replace it with the last column.

    One way,

    awk '{print $0, "string to append after each line"}' file > new_file
    

    or this,

    awk '$0=$0"string to append after each line"' file > new_file
    

    How to write hello world in assembler under Windows?

    NASM examples.

    Calling libc stdio printf, implementing int main(){ return printf(message); }

    ; ----------------------------------------------------------------------------
    ; helloworld.asm
    ;
    ; This is a Win32 console program that writes "Hello, World" on one line and
    ; then exits.  It needs to be linked with a C library.
    ; ----------------------------------------------------------------------------
    
        global  _main
        extern  _printf
    
        section .text
    _main:
        push    message
        call    _printf
        add     esp, 4
        ret
    message:
        db  'Hello, World', 10, 0
    

    Then run

    nasm -fwin32 helloworld.asm
    gcc helloworld.obj
    a
    

    There's also The Clueless Newbies Guide to Hello World in Nasm without the use of a C library. Then the code would look like this.

    16-bit code with MS-DOS system calls: works in DOS emulators or in 32-bit Windows with NTVDM support. Can't be run "directly" (transparently) under any 64-bit Windows, because an x86-64 kernel can't use vm86 mode.

    org 100h
    mov dx,msg
    mov ah,9
    int 21h
    mov ah,4Ch
    int 21h
    msg db 'Hello, World!',0Dh,0Ah,'$'
    

    Build this into a .com executable so it will be loaded at cs:100h with all segment registers equal to each other (tiny memory model).

    Good luck.

    How can I selectively merge or pick changes from another branch in Git?

    Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.

    First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:

    git merge --no-ff --no-commit -s ours branchname1
    

    ... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.

    git checkout branchname1 -- file1 file2 etc.
    

    If you were merging from more than one other branch, repeat as needed.

    git checkout branchname2 -- file3 file4 etc.
    

    Now the files from the other branch are in the index, ready to be committed, with history.

    git commit
    

    And you'll have a lot of explaining to do in that commit message.

    Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.

    How to create a .NET DateTime from ISO 8601 format

    This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

    DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
    

    This prints the solution perfectly.

    How do I sort a Set to a List in Java?

    @Jeremy Stein I wanted to implement same code. As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable. This code helped me,

    set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());
    

    Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

    In my case it was an old dependency that was using compile for the transitive dependencies : com.jakewharton.hugo

    After removing it from my gradle it compiled.

    Oracle Convert Seconds to Hours:Minutes:Seconds

    My version. Show Oracle DB uptime in format DDd HHh MMm SSs

    select to_char(trunc((((86400*x)/60)/60)/24)) || 'd ' ||
       to_char(trunc(((86400*x)/60)/60)-24*(trunc((((86400*x)/60)/60)/24)), 'FM00') || 'h ' ||
       to_char(trunc((86400*x)/60)-60*(trunc(((86400*x)/60)/60)), 'FM00') || 'm ' ||
       to_char(trunc(86400*x)-60*(trunc((86400*x)/60)), 'FM00') || 's' "UPTIME"
     from (select (sysdate - t.startup_time) x from V$INSTANCE t);
    

    idea from Date / Time Arithmetic with Oracle 9/10

    Getting a File's MD5 Checksum in Java

    We were using code that resembles the code above in a previous post using

    ...
    String signature = new BigInteger(1,md5.digest()).toString(16);
    ...
    

    However, watch out for using BigInteger.toString() here, as it will truncate leading zeros... (for an example, try s = "27", checksum should be "02e74f10e0327ad868d138f2b4fdd6f0")

    I second the suggestion to use Apache Commons Codec, I replaced our own code with that.

    How to recursively find and list the latest modified files in a directory with subdirectories and times

    I have this alias in my .profile that I use quite often:

    $ alias | grep xlogs
    xlogs='sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R'
    

    So it does what you are looking for (with exception it doesn't traverse change date/time multiple levels) - looks for latest files (*.log and *.trc files in this case); also it only finds files modified in the last day, and then sorts by time and pipes the output through less:

    sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R
    

    PS.: Notice I don't have root on some of the servers, but always have sudo, so you may not need that part.

    Disabling Minimize & Maximize On WinForm?

    How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
    FormBorderStyle: FixedDialog
    MinimizeBox: false
    MaximizeBox: false

    Posting parameters to a url using the POST method without using a form

    If you're trying to link to something, rather than do it from code you can redirect your request through: http://getaspost.appspot.com/

    How to get first N number of elements from an array

    I believe what you're looking for is:

    // ...inside the render() function
    
    var size = 3;
    var items = list.slice(0, size).map(i => {
        return <myview item={i} key={i.id} />
    }
    
    return (
      <div>
        {items}
      </div>   
    )
    

    What does the Excel range.Rows property really do?

    Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:

    ?TypeName(Selection.rows)
    Range
    
    However, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.

    So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.

    But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;

    ...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.

    The easiest way to understand this is to step through this code and watch what's selected:

    Public Sub Test() 
    Dim SubRange As Range Dim ParentRange As Range
    Set ParentRange = ActiveSheet.Range("B2:E5")

    For Each SubRange In ParentRange.Cells SubRange.Select Next
    For Each SubRange In ParentRange.Rows SubRange.Select Next
    For Each SubRange In ParentRange.Columns SubRange.Select Next
    For Each SubRange In ParentRange SubRange.Select Next
    End Sub
    Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.

    scrollable div inside container

    Adding position: relative to the parent, and a max-height:100%; on div2 works.

    _x000D_
    _x000D_
    <body>_x000D_
      <div id="div1" style="height: 500px;position:relative;">_x000D_
        <div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
          <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
        </div>_x000D_
      </div>_x000D_
    _x000D_
    </body>?
    _x000D_
    _x000D_
    _x000D_


    Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/

    The secret there is to use box-sizing: border-box, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.

    C++ program converts fahrenheit to celsius

    In your code sample you are trying to divide an integer with another integer. This is the cause of all your trouble. Here is an article that might find interesting on that subject.

    With the notion of integer division you can see right away that this is not what you want in your formula. Instead, you need to use some floating point literals.

    I am a rather confused by the title of this thread and your code sample. Do you want to convert Celsius degrees to Fahrenheit or do the opposite?

    I will base my code sample on your own code sample until you give more details on what you want.

    Here is an example of what you can do :

    #include <iostream>
    //no need to use the whole std namespace... use what you need :)                        
    using std::cout;
    using std::cin;
    using std::endl;                      
    
    int main() 
    {   
        //Variables                           
        float celsius,    //represents the temperature in Celsius degrees
              fahrenheit; //represents the converted temperature in Fahrenheit degrees
    
        //Ask for the temperature in Celsius degrees
        cout << "Enter Celsius temperature: "; 
        cin >> celsius;
    
        //Formula to convert degrees in Celsius to Fahrenheit degrees
        //Important note: floating point literals need to have the '.0'!
        fahrenheit = celsius * 9.0/5.0 + 32.0;
    
        //Print the converted temperature to the console
        cout << "Fahrenheit = " << fahrenheit << endl;                            
    }
    

    How do I get the entity that represents the current user in Symfony2?

    The thread is a bit old but i think this could probably save someone's time ...

    I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

    It eventually turned out that i was logged in using an in memory user

    my security.yml looks something like this

    security:
        providers:
            chain_provider:
                chain:
                    providers: [in_memory, fos_userbundle]
            fos_userbundle:
                id: fos_user.user_manager
            in_memory:
                memory:
                    users:
                        user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                        admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }
    

    the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

    Thanks, hj

    What is the @Html.DisplayFor syntax for?

    I think the main benefit would be when you define your own Display Templates, or use Data annotations.

    So for example if your title was a date, you could define

    [DisplayFormat(DataFormatString = "{0:d}")]
    

    and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

    For example instead of an email address being a plain string it could show up as a link:

    <a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>
    

    How to make exe files from a node.js app?

    Since this question has been answered, another solution has been launched.

    https://github.com/appjs/appjs

    At the time of this writing, this is the end-all solution for packaging node.js apps through a stripped down chromium package compiled into an executable.

    Edit: AppJS is no longer active, but itself suggests a fork called deskshell.

    https://github.com/sihorton/appjs-deskshell/

    Event binding on dynamically created elements?

    You can attach event to element when dynamically created using jQuery(html, attributes).

    As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

    _x000D_
    _x000D_
    function handleDynamicElementEvent(event) {_x000D_
      console.log(event.type, this.value)_x000D_
    }_x000D_
    // create and attach event to dynamic element_x000D_
    jQuery("<select>", {_x000D_
        html: $.map(Array(3), function(_, index) {_x000D_
          return new Option(index, index)_x000D_
        }),_x000D_
        on: {_x000D_
          change: handleDynamicElementEvent_x000D_
        }_x000D_
      })_x000D_
      .appendTo("body");
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">_x000D_
    </script>
    _x000D_
    _x000D_
    _x000D_

    NGinx Default public www location?

    The default is related to the prefix option of the configure script when nginx is compiled; here's some strange sample from Debian:

    % nginx -V | & tr ' ' "\n" | fgrep -e path -e prefix
    --prefix=/etc/nginx
    --conf-path=/etc/nginx/nginx.conf
    --error-log-path=/var/log/nginx/error.log
    --http-client-body-temp-path=/var/lib/nginx/body
    --http-fastcgi-temp-path=/var/lib/nginx/fastcgi
    --http-log-path=/var/log/nginx/access.log
    --http-proxy-temp-path=/var/lib/nginx/proxy
    --http-scgi-temp-path=/var/lib/nginx/scgi
    --http-uwsgi-temp-path=/var/lib/nginx/uwsgi
    --lock-path=/var/lock/nginx.lock
    --pid-path=/var/run/nginx.pid
    

    Subsequently, the default value of root is set to the html directory (as per the documentation of the root directive), which happens to be within prefix , as can be verified by looking at the $document_root variable from a simple configuration file:

    # printf 'server{listen 4867;return 200 $document_root\\n;}\n' \
        >/etc/nginx/conf.d/so.10674867.conf
    
    # nginx -s reload && curl localhost:4867
    /etc/nginx/html
    

    However, evil distributions like Debian seem to modify it quite a bit, to keep you extra entertained:

    % fgrep -e root -e include /etc/nginx/nginx.conf
        include /etc/nginx/mime.types;
        #include /etc/nginx/naxsi_core.rules;
        #passenger_root /usr;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    
    % fgrep -e root -e include \
        /etc/nginx/conf.d/*.conf /etc/nginx/sites-enabled/*
    /etc/nginx/conf.d/so.10674867.conf:server{listen 4867;return 200 $document_root\n;}
    /etc/nginx/sites-enabled/default:   root /usr/share/nginx/www;
    /etc/nginx/sites-enabled/default:       # include /etc/nginx/naxsi.rules
    /etc/nginx/sites-enabled/default:   #   root /usr/share/nginx/www;
    /etc/nginx/sites-enabled/default:   #   include fastcgi_params;
    /etc/nginx/sites-enabled/default:   # deny access to .htaccess files, if Apache's document root
    /etc/nginx/sites-enabled/default:#  root html;
    /etc/nginx/sites-enabled/default:#  root html;
    

    So, on this instance of Debian, you can see that the root is finally set to /usr/share/nginx/www.

    But as you saw with the sample server configuration that would serve its $document_root value over http, configuring nginx is simple enough that you can write your own configuration in a matter of a single line or two, specifying the required root to meet your exact needs.

    Remove duplicates from a list of objects based on property in Java 8

    There are a lot of good answers here but I didn't find the one about using reduce method. So for your case, you can apply it in following way:

     List<Employee> employeeList = employees.stream()
          .reduce(new ArrayList<>(), (List<Employee> accumulator, Employee employee) ->
          {
            if (accumulator.stream().noneMatch(emp -> emp.getId().equals(employee.getId())))
            {
              accumulator.add(employee);
            }
            return accumulator;
          }, (acc1, acc2) ->
          {
            acc1.addAll(acc2);
            return acc1;
          });
    

    Regular Expression For Duplicate Words

    I believe this regex handles more situations:

    /(\b\S+\b)\s+\b\1\b/
    

    A good selection of test strings can be found here: http://callumacrae.github.com/regex-tuesday/challenge1.html

    How to set maximum height for table-cell?

    Use the style below:

    div {
      display: fixed;
      max-height: 100px;
      max-width: 100px;
      overflow: hidden;
    }
    

    With the HTML being:

    <div>
        your long text here
    </div>
    

    HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

    I know it's late in the day but might help someone else!

    body,html {
      height: 100%;
    }
    
    .contentarea {
    
     /* 
      * replace 160px with the sum of height of all other divs 
      * inc padding, margins etc 
      */
      min-height: calc(100% - 160px); 
    }
    

    Keeping session alive with Curl and PHP

    You also need to set the option CURLOPT_COOKIEFILE.

    The manual describes this as

    The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

    Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.

    How to create/read/write JSON files in Qt5

    Example: Read json from file

    /* test.json */
    {
       "appDesc": {
          "description": "SomeDescription",
          "message": "SomeMessage"
       },
       "appName": {
          "description": "Home",
          "message": "Welcome",
          "imp":["awesome","best","good"]
       }
    }
    
    
    void readJson()
       {
          QString val;
          QFile file;
          file.setFileName("test.json");
          file.open(QIODevice::ReadOnly | QIODevice::Text);
          val = file.readAll();
          file.close();
          qWarning() << val;
          QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
          QJsonObject sett2 = d.object();
          QJsonValue value = sett2.value(QString("appName"));
          qWarning() << value;
          QJsonObject item = value.toObject();
          qWarning() << tr("QJsonObject of description: ") << item;
    
          /* in case of string value get value and convert into string*/
          qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
          QJsonValue subobj = item["description"];
          qWarning() << subobj.toString();
    
          /* in case of array get array and convert into string*/
          qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
          QJsonArray test = item["imp"].toArray();
          qWarning() << test[1].toString();
       }
    

    OUTPUT

    QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
    "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
    "QJsonObject[appName] of description: " QJsonValue(string, "Home") 
    "Home" 
    "QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
    "best" 
    

    Example: Read json from string

    Assign json to string as below and use the readJson() function shown before:

    val =   
    '  {
           "appDesc": {
              "description": "SomeDescription",
              "message": "SomeMessage"
           },
           "appName": {
              "description": "Home",
              "message": "Welcome",
              "imp":["awesome","best","good"]
           }
        }';
    

    OUTPUT

    QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
    "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
    "QJsonObject[appName] of description: " QJsonValue(string, "Home") 
    "Home" 
    "QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
    "best" 
    

    C++ vector's insert & push_back difference

    The functions have different purposes. vector::insert allows you to insert an object at a specified position in the vector, whereas vector::push_back will just stick the object on the end. See the following example:

    using namespace std;
    vector<int> v = {1, 3, 4};
    v.insert(next(begin(v)), 2);
    v.push_back(5);
    // v now contains {1, 2, 3, 4, 5}
    

    You can use insert to perform the same job as push_back with v.insert(v.end(), value).

    How do I select an entire row which has the largest ID in the table?

    Try with this

     SELECT top 1  id, Col2,  row_number() over (order by id desc)  FROM Table
    

    label or @html.Label ASP.net MVC 4

    When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

    • When dealing with hyperlinks, since the HTML helper simplifies routing
    • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
    • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

    Html.BeginForm and adding properties

    I know this is old but you could create a custom extension if you needed to create that form over and over:

    public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
    {
        return htmlHelper.BeginForm(null, null, FormMethod.Post, 
         new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
    }
    

    Usage then just becomes

    <% using(Html.BeginMultipartForm()) { %>
    

    Swap two items in List<T>

    Maybe someone will think of a clever way to do this, but you shouldn't. Swapping two items in a list is inherently side-effect laden but LINQ operations should be side-effect free. Thus, just use a simple extension method:

    static class IListExtensions {
        public static void Swap<T>(
            this IList<T> list,
            int firstIndex,
            int secondIndex
        ) {
            Contract.Requires(list != null);
            Contract.Requires(firstIndex >= 0 && firstIndex < list.Count);
            Contract.Requires(secondIndex >= 0 && secondIndex < list.Count);
            if (firstIndex == secondIndex) {
                return;
            }
            T temp = list[firstIndex];
            list[firstIndex] = list[secondIndex];
            list[secondIndex] = temp;
        }
    }
    

    Implementing autocomplete

    Update: This answer has led to the development of ng2-completer an Angular2 autocomplete component. This is the list of existing autocomplete components for Angular2:

    1. ng2-completer
    2. ng2-auto-complete
    3. ng2-typeahead

    Credit goes to @dan-cancro for coming up with the idea

    Keeping the original answer for those who wish to create their own directive:

    To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:

    1. Obtain a reference to the nativeElement and manipulate the DOM directly
    2. Dynamically load a list component using DynamicComponentLoader

    It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.

    This is the directive code:

    "use strict";
    import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
    import {Promise} from "es6-promise";
    import {AutocompleteList} from "./autocomplete-list";
    
    @Directive({
        selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
        host: {
            "(keyup)": "onKey($event)" // Liten to keyup events on the host component
        }
    })
    export class AutocompleteDirective implements OnInit {
        // The search function should be passed as an input
        @Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
        // The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
        @Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();
    
        private term = "";
        private listCmp: ComponentRef<AutocompleteList> = undefined;
        private refreshTimer: any = undefined;
        private searchInProgress = false;
        private searchRequired = false;
    
        constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
        /**
         * On key event is triggered when a key is released on the host component
         * the event starts a timer to prevent concurrent requests
         */
        public onKey(event: any) {
            if (!this.refreshTimer) {
                this.refreshTimer = setTimeout(
                () => {
                    if (!this.searchInProgress) {
                        this.doSearch();
                    } else {
                        // If a request is in progress mark that a new search is required
                        this.searchRequired = true;
                    }
                },
                200);
            }
            this.term = event.target.value;
            if (this.term === "" && this.listCmp) {
                // clean the list if the search term is empty
                this.removeList();
            }
        }
    
        public ngOnInit() {
            // When an item is selected remove the list
            this.selected.subscribe(() => {
                this.removeList();
            });
        }
    
        /**
         * Call the search function and handle the results
         */
        private doSearch() {
            this.refreshTimer = undefined;
            // if we have a search function and a valid search term call the search
            if (this.search && this.term !== "") {
                this.searchInProgress = true;
                this.search(this.term)
                .then((res) => {
                    this.searchInProgress = false;
                    // if the term has changed during our search do another search
                    if (this.searchRequired) {
                        this.searchRequired = false;
                        this.doSearch();
                    } else {
                        // display the list of results
                        this.displayList(res);
                    }
                })
                .catch(err => {
                    console.log("search error:", err);
                    this.removeList();
                });
            }
        }
    
        /**
         * Display the list of results
         * Dynamically load the list component if it doesn't exist yet and update the suggestions list
         */
        private displayList(list: Array<{ text: string, data: any }>) {
            if (!this.listCmp) {
                this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
                .then(cmp => {
                    // The component is loaded
                    this.listCmp = cmp;
                    this.updateList(list);
                    // Emit the selectd event when the component fires its selected event
                    (<AutocompleteList>(this.listCmp.instance)).selected
                        .subscribe(selectedItem => {
    
                        this.selected.emit(selectedItem);
                    });
                });
            } else {
                this.updateList(list);
            }
        }
    
        /**
         * Update the suggestions list in the list component
         */
        private updateList(list: Array<{ text: string, data: any }>) {
            if (this.listCmp) {
                (<AutocompleteList>(this.listCmp.instance)).list = list;
            }
        }
    
        /**
         * remove the list component
         */
        private removeList() {
            this.searchInProgress = false;
            this.searchRequired = false;
            if (this.listCmp) {
                this.listCmp.destroy();
                this.listCmp = undefined;
            }
        }
    }
    

    The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:

    "use strict";
    import {Component, Output, EventEmitter} from "@angular/core";
    
    @Component({
        selector: "autocomplete-list",
        template: `<div class="dropdown-menu  search-results">
                        <a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
                   </div>`, // Use a bootstrap 4 dropdown-menu to display the list
        styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
    })
    export class AutocompleteList  {
        // Emit a selected event when an item in the list is selected
        @Output() public selected = new EventEmitter();
    
        public list;
    
        /**
         * Listen for a click event on the list
         */
        public onClick(item: {text: string, data: any}) {
            this.selected.emit(item);
        }
    }
    

    To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:

     "use strict";
    import {Component} from "@angular/core";
    
    import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";
    
    @Component({
        selector: "my-cmp",
        directives: [AutocompleteDirective],
        template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
    })
    export class MyComponent  {
    
        /**
         * generate a search function that returns a Promise that resolves to array of text and optionally additional data
         */  
        public search() {
            return (filter: string): Promise<Array<{ text: string, data: any }>> => {
                // do the search
                resolve({text: "one item", data: null});
            };
        }
    
        /**
         * handle item selection
         */  
        public onItemSelected(selected: { text: string, data: any }) {
            console.log("selected: ", selected.text);
        }
    }
    

    Update: code compatible with angular2 rc.1

    php_network_getaddresses: getaddrinfo failed: Name or service not known

    You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

    If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

    If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

    $fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
    fputs($fp, "GET /1/file.php HTTP/1.1\n");
    fputs($fp, "Host: www.mydomain.net\n");
    fputs($fp, "Connection: close\n\n"); 
    

    That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.

    Should I use the datetime or timestamp data type in MySQL?

    I prefer using timestamp so to keep everything in one common raw format and format the data in PHP code or in your SQL query. There are instances where it comes in handy in your code to keep everything in plain seconds.

    difference between css height : 100% vs height : auto

    The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

    How to align input forms in HTML

    Another example, this uses CSS, I simply put the form in a div with the container class. And specified that input elements contained within are to be 100% of the container width and not have any elements on either side.

    _x000D_
    _x000D_
    .container {_x000D_
      width: 500px;_x000D_
      clear: both;_x000D_
    }_x000D_
    _x000D_
    .container input {_x000D_
      width: 100%;_x000D_
      clear: both;_x000D_
    }
    _x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <title>Example form</title>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <div class="container">_x000D_
        <form>_x000D_
          <label>First Name</label>_x000D_
          <input type="text" name="first"><br />_x000D_
          <label>Last Name</label>_x000D_
          <input type="text" name="last"><br />_x000D_
          <label>Email</label>_x000D_
          <input type="text" name="email"><br />_x000D_
        </form>_x000D_
      </div>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    How should I print types like off_t and size_t?

    use "%zo" for off_t. (octal) or "%zu" for decimal.

    CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

    If it works fine on your local environment, probably your remote server's IP is being blocked by the server at the target URL you've set for cURL to use. You need to verify that your remote server is allowed to access the URL you've set for CURLOPT_URL.

    How can I find all *.js file in directory recursively in Linux?

    If you just want the list, then you should ask here: http://unix.stackexchange.com

    The answer is: cd / && find -name *.js

    If you want to implement this, you have to specify the language.

    Bootstrap 3: how to make head of dropdown link clickable in navbar

    i know its too late but anyone who came here for help now you can see this post .There are two options either use css/ JavaScript and if you use css it will be applicable to devices greater that 769px width for clickable top menu, that will be work perfectly f

    See here for article

    HTML Canvas Full Screen

    If you want to show it in a presentation then consider using requestFullscreen() method

    let canvas = document.getElementById("canvas_id");
    canvas.requestFullscreen();
    

    that should make it fullscreen whatever the current circumstances are.

    also check the support table https://caniuse.com/?search=requestFullscreen

    Default value for field in Django model

    You can also use a callable in the default field, such as:

    b = models.CharField(max_length=7, default=foo)
    

    And then define the callable:

    def foo():
        return 'bar'
    

    How do you do a limit query in JPQL or HQL?

    If you don't want to use setMaxResults, you can also use Query.scroll instead of list, and fetch the rows you desire. Useful for paging for instance.

    Setting PATH environment variable in OSX permanently

    For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

    For example: to add a new path /usr/local/sbin to the PATH variable:

    cd /etc/paths.d
    sudo vi newfile
    

    Add the path to the newfile and save it.

    Restart the terminal and type echo $PATH to confirm

    Column standard deviation R

    Use colSds function from matrixStats library.

    library(matrixStats)
    set.seed(42)
    M <- matrix(rnorm(40),ncol=4)
    colSds(M)
    
    [1] 0.8354488 1.6305844 1.1560580 1.1152688
    

    How to get the width and height of an android.widget.ImageView?

    my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview

    How to throw a C++ exception

    Simple:

    #include <stdexcept>
    
    int compare( int a, int b ) {
        if ( a < 0 || b < 0 ) {
            throw std::invalid_argument( "received negative value" );
        }
    }
    

    The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

    try {
        compare( -1, 3 );
    }
    catch( const std::invalid_argument& e ) {
        // do stuff with exception... 
    }
    

    You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

    You can also re-throw exceptions:

    catch( const std::invalid_argument& e ) {
        // do something
    
        // let someone higher up the call stack handle it if they want
        throw;
    }
    

    And to catch exceptions regardless of type:

    catch( ... ) { };
    

    Getting all documents from one collection in Firestore

    I prefer to hide all code complexity in my services... so, I generally use something like this:

    In my events.service.ts

        async getEvents() {
            const snapchot = await this.db.collection('events').ref.get();
            return new Promise <Event[]> (resolve => {
                const v = snapchot.docs.map(x => {
                    const obj = x.data();
                    obj.id = x.id;
                    return obj as Event;
                });
                resolve(v);
            });
        }
    

    In my sth.page.ts

       myList: Event[];
    
       construct(private service: EventsService){}
    
       async ngOnInit() {
          this.myList = await this.service.getEvents();
       }
    
    

    Enjoy :)

    How do I remove all HTML tags from a string without knowing which tags are in it?

    You can use the below code on your string and you will get the complete string without html part.

    string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
            string s = Regex.Replace(title, "<.*?>", String.Empty);
    

    Click a button programmatically

    Best implementation depends of what you are attempting to do exactly. Nadeem_MK gives you a valid one. Know you can also:

    1. raise the Button2_Click event using PerformClick() method:

      Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
          'do stuff
          Me.Button2.PerformClick()
      End Sub
      
    2. attach the same handler to many buttons:

      Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
          Handles Button1.Click, Button2.Click
          'do stuff
      End Sub
      
    3. call the Button2_Click method using the same arguments than Button1_Click(...) method (IF you need to know which is the sender, for example) :

      Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
          'do stuff
           Button2_Click(sender, e)
      End Sub
      

    Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

    This is possible with a bit of format conversion.

    To extract the private key in a format openssh can use:

    openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
    

    To convert the private key to a public key:

    openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
    

    To extract the public key in a format openssh can use:

    openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
    

    Convert IEnumerable to DataTable

    I've written a library to handle this for me. It's called DataTableProxy and is available as a NuGet package. Code and documentation is on Github

    how to use php DateTime() function in Laravel 5

    DateTime is not a function, but the class.

    When you just reference a class like new DateTime() PHP searches for the class in your current namespace. However the DateTime class obviously doesn't exists in your controllers namespace but rather in root namespace.

    You can either reference it in the root namespace by prepending a backslash:

    $now = new \DateTime();
    

    Or add an import statement at the top:

    use DateTime;
    
    $now = new DateTime();
    

    Get list of databases from SQL Server

    In SQL Server 7, dbid 1 thru 4 are the system dbs.

    Psql could not connect to server: No such file or directory, 5432 error?

    I recommend you should clarify port that postgres. In my case I didn't know which port postgres was running on.

    lsof -i | grep 'post'
    

    then you can know which port is listening.

    psql -U postgres -p "port_in_use"
    

    with port option, might be answer. you can use psql.

    BigDecimal setScale and round

    One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

    The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

    setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

    If you move the decimal point one place to the right, the difference will become clear:

    // 1.
    new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
    //result = 35.35
    // 2.
    new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
    // result = 35.3456
    

    notifyDataSetChanged example

    I had the same problem and I prefer not to replace the entire ArrayAdapter with a new instance continuously. Thus I have the AdapterHelper do the heavy lifting somewhere else.

    Add this where you would normally (try to) call notify

    new AdapterHelper().update((ArrayAdapter)adapter, new ArrayList<Object>(yourArrayList));
    adapter.notifyDataSetChanged();
    

    AdapterHelper class

    public class AdapterHelper {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        public void update(ArrayAdapter arrayAdapter, ArrayList<Object> listOfObject){
            arrayAdapter.clear();
            for (Object object : listOfObject){
                arrayAdapter.add(object);
            }
        }
    }
    

    How to delete a column from a table in MySQL

    ALTER TABLE `tablename` DROP `columnname`;
    

    Or,

    ALTER TABLE `tablename` DROP COLUMN `columnname`;
    

    extra qualification error in C++

    Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::.

    Invoke native date picker from web-app on iOS/Android

    iOS 5 now supports HTML5 better. in your webapp do

    <input type="date" name="date" />
    

    Android as of 4.0 lacks this type of native menu support.

    JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

    - First to me Iterating and Looping are 2 different things.

    Eg: Increment a variable till 5 is Looping.

        int count = 0;
    
        for (int i=0 ; i<5 ; i++){
    
            count = count + 1;
    
       }
    

    Eg: Iterate over the Array to print out its values, is about Iteration

        int[] arr = {5,10,15,20,25};
    
        for (int i=0 ; i<arr.length ; i++){
    
            System.out.println(arr[i]);
    
       }
    

    Now about all the Loops:

    - Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

    For Loop :

    int sum = 0; 
    
    for (int i = 1; i <= 100; i++) {
    
      sum += i; 
    
    }
    
     System.out.println("The sum is " + sum);
    

    The Difference between While and Do-While is as Follows :

    - While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

    - Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

    While Loop :

    int sum = 0; 
    int i = 0;       // i is 0 Here
    
        while (i<100) {
    
          sum += i; 
          i++;
    
        }
    
      System.out.println("The sum is " + sum);
    

    do-While :

    int sum = 0; 
    int i = 0;      // i is 0 Here
    
        do{ 
    
          sum += i; 
           i++
        }while(i < 100; );
    
         System.out.println("The sum is " + sum);
    

    From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

    ArrayList<String> arr = new ArrayList<String>();
    
    arr.add("Vivek");
    arr.add("Is");
    arr.add("Good");
    arr.add("Boy");
    
    for (String str : arr){         // str represents the value in each index of arr
    
        System.out.println(str);     
    
     }
    

    Serializing a list to JSON

    If using .Net Core 3.0 or later;

    Default to using the built in System.Text.Json parser implementation.

    e.g.

    using System.Text.Json;
    
    var json = JsonSerializer.Serialize(aList);
    

    alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.

    If stuck using .Net Core 2.2 or earlier;

    Default to using Newtonsoft JSON.Net as your first choice JSON Parser.

    e.g.

    using Newtonsoft.Json;
    
    var json = JsonConvert.SerializeObject(aList);
    

    you may need to install the package first.

    PM> Install-Package Newtonsoft.Json
    

    For more details see and upvote the answer that is the source of this information.

    For reference only, this was the original answer, many years ago;

    // you need to reference System.Web.Extensions
    
    using System.Web.Script.Serialization;
    
    var jsonSerialiser = new JavaScriptSerializer();
    var json = jsonSerialiser.Serialize(aList);
    

    How can I concatenate two arrays in Java?

    String [] both = new ArrayList<String>(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);
    

    How to check if a string contains an element from a list in Python

    It is better to parse the URL properly - this way you can handle http://.../file.doc?foo and http://.../foo.doc/file.exe correctly.

    from urlparse import urlparse
    import os
    path = urlparse(url_string).path
    ext = os.path.splitext(path)[1]
    if ext in extensionsToCheck:
      print(url_string)
    

    How to use the IEqualityComparer

    IEquatable<T> can be a much easier way to do this with modern frameworks.

    You get a nice simple bool Equals(T other) function and there's no messing around with casting or creating a separate class.

    public class Person : IEquatable<Person>
    {
        public Person(string name, string hometown)
        {
            this.Name = name;
            this.Hometown = hometown;
        }
    
        public string Name { get; set; }
        public string Hometown { get; set; }
    
        // can't get much simpler than this!
        public bool Equals(Person other)
        {
            return this.Name == other.Name && this.Hometown == other.Hometown;
        }
    
        public override int GetHashCode()
        {
            return Name.GetHashCode();  // see other links for hashcode guidance 
        }
    }
    

    Note you DO have to implement GetHashCode if using this in a dictionary or with something like Distinct.

    PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.

    If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode defined (with override keyword).

    Laravel Eloquent: Ordering results of all()

    You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

    Ascending Order

    $results = Project::all()->sortBy("name");
    

    Descending Order

    $results = Project::all()->sortByDesc("name");
    

    Check out the documentation about Collections for more details.

    https://laravel.com/docs/5.1/collections

    fastest MD5 Implementation in JavaScript

    Node.js has built-in support

    const crypto = require('crypto')
    crypto.createHash('md5').update('hello world').digest('hex')
    

    Code snippet above computes MD5 hex string for string hello world

    The advantage of this solution is you don't need to install additional library.

    I think built in solution should be the fastest. If not, we should create issue/PR for the Node.js project.

    Running Python from Atom

    Follow the steps:

    1. Install Python
    2. Install Atom
    3. Install and configure Atom package for Python
    4. Install and configure Python Linter
    5. Install Script Package in Atom
    6. Download and install Syntax Highlighter for Python
    7. Install Version control package Run Python file

    More details for each step Click Here

    How can I change the value of the elements in a vector?

    You can access the values in a vector just as you access any other array.

    for (int i = 0; i < v.size(); i++)
    {         
      v[i] -= 1;         
    } 
    

    How to specify multiple conditions in an if statement in javascript

    just add them within the main bracket of the if statement like

    if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
                PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
    }
    

    Logically this can be rewritten in a better way too! This has exactly the same meaning

    if (Type == 2 && (PageCount == 0 || PageCount == '')) {
    

    What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

    You can use instance_of?

    e.g

    @some_var.instance_of?(Hash)
    

    How to add composite primary key to table

    alter table d add constraint pkc_Name primary key (id, code)

    should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

    What is the shortest function for reading a cookie by name in JavaScript?

    Here is the simplest solution using javascript string functions.

    document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"), 
                              document.cookie.indexOf(";", 
                              document.cookie.indexOf("COOKIE_NAME"))).
      substr(COOKIE_NAME.length);
    

    convert ArrayList<MyCustomClass> to JSONArray

    I know its already answered, but theres a better solution here use this code :

    for ( Field f : context.getFields() ) {
         if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
               //DO String To JSON
         }
         /// And so on...
    }
    

    This way you can access variables from class without manually typing them..

    Faster and better .. Hope this helps.

    Cheers. :D

    Swap x and y axis without manually swapping values

    -Right click on either axis

    -Click "Select Data..."

    -Then Press the "Edit" button

    -Copy the "Series X values" to the "Series Y values" and vise versa finally hit ok

    I found this answer on this youtube video https://www.youtube.com/watch?v=xLKIWWIWltE

    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

    Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

    I solved the problem adding a slash at the end of the requesting url

    This way: '/data/180/' instead of: '/data/180'

    How to properly apply a lambda function into a pandas data frame column

    You need mask:

    sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
    

    Another solution with loc and boolean indexing:

    sample.loc[sample['PR'] < 90, 'PR'] = np.nan
    

    Sample:

    import pandas as pd
    import numpy as np
    
    sample = pd.DataFrame({'PR':[10,100,40] })
    print (sample)
        PR
    0   10
    1  100
    2   40
    
    sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
    print (sample)
          PR
    0    NaN
    1  100.0
    2    NaN
    
    sample.loc[sample['PR'] < 90, 'PR'] = np.nan
    print (sample)
          PR
    0    NaN
    1  100.0
    2    NaN
    

    EDIT:

    Solution with apply:

    sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)
    

    Timings len(df)=300k:

    sample = pd.concat([sample]*100000).reset_index(drop=True)
    
    In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
    10 loops, best of 3: 102 ms per loop
    
    In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
    The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
    100 loops, best of 3: 3.71 ms per loop
    

    How can I run a windows batch file but hide the command window?

    Native C++ codified version of Oleg's answer -- this is copy/pasted from a project I work on under the Boost Software License.

    BOOL noError;
    STARTUPINFO startupInfo;
    PROCESS_INFORMATION processInformation;
    ZeroMemory(&startupInfo, sizeof(startupInfo));
    startupInfo.cb = sizeof(startupInfo);
    startupInfo.dwFlags = STARTF_USESHOWWINDOW;
    startupInfo.wShowWindow = SW_HIDE;
    noError = CreateProcess(
        NULL,                                           //lpApplicationName
        //Okay the const_cast is bad -- this code was written a while ago.
        //should probably be &commandLine[0] instead. Oh, and commandLine is
        //a std::wstring
        const_cast<LPWSTR>(commandLine.c_str()),        //lpCommandLine
        NULL,                                           //lpProcessAttributes
        NULL,                                           //lpThreadAttributes
        FALSE,                                          //bInheritHandles
        CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,  //dwCreationFlags
        //This is for passing in a custom environment block -- you can probably
        //just use NULL here.
        options.e ? environment : NULL,                 //lpEnvironment
        NULL,                                           //lpCurrentDirectory
        &startupInfo,                                   //lpStartupInfo
        &processInformation                             //lpProcessInformation
    );
    
    if(!noError)
    {
        return GetLastError();
    }
    
    DWORD exitCode = 0;
    
    if (options.w) //Wait
    {
        WaitForSingleObject(processInformation.hProcess, INFINITE);
        if (GetExitCodeProcess(processInformation.hProcess, &exitCode) == 0)
        {
            exitCode = (DWORD)-1;
        }
    }
    
    CloseHandle( processInformation.hProcess );
    CloseHandle( processInformation.hThread );
    

    Adding a background image to a <div> element

    You can simply add an img src Attribute with id:

    <body>
    <img id="backgroundimage" src="bgimage.jpg" border="0" alt="">
    </body>
    

    and in your CSS file (stretch background):

    #backgroundimage
    {
       height: auto;
       left: 0;
       margin: 0;
       min-height: 100%;
       min-width: 674px;
       padding: 0;
       position: fixed;
       top: 0;
       width: 100%;
       z-index: -1;
    }
    

    Entity framework self referencing loop detected

    This happens because you're trying to serialize the EF object collection directly. Since department has an association to employee and employee to department, the JSON serializer will loop infinetly reading d.Employee.Departments.Employee.Departments etc...

    To fix this right before the serialization create an anonymous type with the props you want

    example (psuedo)code:

    departments.select(dep => new { 
        dep.Id, 
        Employee = new { 
            dep.Employee.Id, dep.Employee.Name 
        }
    });
    

    How to use WPF Background Worker

    using System;  
    using System.ComponentModel;   
    using System.Threading;    
    namespace BackGroundWorkerExample  
    {   
        class Program  
        {  
            private static BackgroundWorker backgroundWorker;  
    
            static void Main(string[] args)  
            {  
                backgroundWorker = new BackgroundWorker  
                {  
                    WorkerReportsProgress = true,  
                    WorkerSupportsCancellation = true  
                };  
    
                backgroundWorker.DoWork += backgroundWorker_DoWork;  
                //For the display of operation progress to UI.    
                backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
                //After the completation of operation.    
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
                backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  
    
                Console.ReadLine();  
    
                if (backgroundWorker.IsBusy)  
                { 
                    backgroundWorker.CancelAsync();  
                    Console.ReadLine();  
                }  
            }  
    
            static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
            {  
                for (int i = 0; i < 200; i++)  
                {  
                    if (backgroundWorker.CancellationPending)  
                    {  
                        e.Cancel = true;  
                        return;  
                    }  
    
                    backgroundWorker.ReportProgress(i);  
                    Thread.Sleep(1000);  
                    e.Result = 1000;  
                }  
            }  
    
            static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
            {  
                Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
            }  
    
            static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
            {  
    
                if (e.Cancelled)  
                {  
                    Console.WriteLine("Operation Cancelled");  
                }  
                else if (e.Error != null)  
                {  
                    Console.WriteLine("Error in Process :" + e.Error);  
                }  
                else  
                {  
                    Console.WriteLine("Operation Completed :" + e.Result);  
                }  
            }  
        }  
    } 
    

    Also, referr the below link you will understand the concepts of Background:

    http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

    How to validate phone number using PHP?

    Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

    php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

    An example

    $phone = '000-0000-0000';
    
    if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
      // $phone is valid
    }
    

    Error C1083: Cannot open include file: 'stdafx.h'

    You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

    Unique random string generation

    If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.

    As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.

    Random random = new Random();
    
    int outputLength = 10;
    int byteLength = (int)Math.Ceiling(3f / 4f * outputLength); // Base64 uses 4 characters for every 3 bytes of data; so in random bytes we need only 3/4 of the desired length
    byte[] randomBytes = new byte[byteLength];
    string output;
    do
    {
        random.NextBytes(randomBytes); // Fill bytes with random data
        output = Convert.ToBase64String(randomBytes); // Convert to base64
        output = output.Substring(0, outputLength); // Truncate any superfluous characters and/or padding
    } while (output.Contains('/') || output.Contains('+')); // Repeat if we contain non-alphanumeric characters (~25% chance if length=10; ~50% chance if length=20; ~35% chance if length=32)
    

    Get Request and Session Parameters and Attributes from JSF pages

    You can also use a bean (request scoped is suggested) and directly access the context by way of the FacesContext.

    You can get the HttpServletRequest and HttpServletResposne objects by using the following code:

    HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
    

    After this, you can access individual parameters via getParameter(paramName) or access the full map via getParameterMap() req object

    The reason I suggest a request scoped bean is that you can use these during initialization (worst case scenario being the constructor. Most frameworks give you some place to do code at bean initialization time) and they will be done as your request comes in.

    It is, however, a bit of a hack. ;) You may want to look into seeing if there is a JSF Acegi module that will allow you to get access to the variables you need.

    convert epoch time to date

    EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

    import java.util.*;
    import java.text.*;
    
    public class Test {
        public static void main(String[] args) throws InterruptedException {
            Date date = new Date(1318386508000L);
            DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
            String formatted = format.format(date);
            System.out.println(formatted);
            format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
            formatted = format.format(date);
            System.out.println(formatted);
        }
    }
    

    Output:

    12/10/2011 02:28:28
    12/10/2011 13:28:28
    

    I would also suggest you start using Joda Time which is simply a much nicer date/time API...

    EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

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

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

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

    List<String> list = new ArrayList();
    

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

    How to Publish Web with msbuild?

    Using the deployment profiles introduced in VS 2012, you can publish with the following command line:

    msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0
    

    For more information on the parameters see this.

    The values for the /p:VisualStudioVersion parameter depend on your version of Visual Studio. Wikipedia has a table of Visual Studio releases and their versions.

    "Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

    Everything was working fine one second and then my server started giving me this error. I went through all the answers mentioned here and what worked for me was this simple solution:

    Deleting the server and then configuring a new one

    If you're sure that you didn't change anything and the error just popped up, DO NOT start deleting .snap files or other temp files. Doing that will only cause more problems. And if the error occurred because of some changes made by you, this error is definitely going to be because of some errors in web.xml file.

    P.S. Changing the workspace will do you absolutely no good, because if the problem is in your project, then it'll still occur in the new work space when you'll import the project!

    How do I get AWS_ACCESS_KEY_ID for Amazon?

    Amit's answer tells you how to get your AWS_ACCESS_KEY_ID, but the Your Security Credentials page won't reveal your AWS_SECRET_ACCESS_KEY. As this blog points out:

    Secret access keys are, as the name implies, secrets, like your password. Just as AWS doesn’t reveal your password back to you if you forgot it (you’d have to set a new password), the new security credentials page does not allowing retrieval of a secret access key after its initial creation. You should securely store your secret access keys as a security best practice, but you can always generate new access keys at any time.

    So if you don't remember your AWS_SECRET_ACCESS_KEY, the blog goes on to tell how to create a new one:

    1. Create a new access key:

    enter image description here

    1. "Download the .csv key file, which contains the access key ID and secret access key.":

    enter image description here

    As for your other questions:

    • I'm not sure about MERCHANT_ID and MARKETPLACE_ID.
    • I believe your sandbox question was addressed by Amit's point that you can play with AWS for a year without paying.

    HttpServletRequest get JSON POST data

    Normaly you can GET and POST parameters in a servlet the same way:

    request.getParameter("cmd");
    

    But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

    If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

    BufferedReader reader = request.getReader();
    

    Json post processing example (uses org.json package )

    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    
      StringBuffer jb = new StringBuffer();
      String line = null;
      try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
          jb.append(line);
      } catch (Exception e) { /*report an error*/ }
    
      try {
        JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
      } catch (JSONException e) {
        // crash and burn
        throw new IOException("Error parsing JSON request string");
      }
    
      // Work with the data using methods like...
      // int someInt = jsonObject.getInt("intParamName");
      // String someString = jsonObject.getString("stringParamName");
      // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
      // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
      // etc...
    }
    

    What is "Advanced" SQL?

    Basics


    1. SELECTing columns from a table
    2. Aggregates Part 1: COUNT, SUM, MAX/MIN
    3. Aggregates Part 2: DISTINCT, GROUP BY, HAVING

    Intermediate


    1. JOINs, ANSI-89 and ANSI-92 syntax
    2. UNION vs UNION ALL
    3. NULL handling: COALESCE & Native NULL handling
    4. Subqueries: IN, EXISTS, and inline views
    5. Subqueries: Correlated
    6. WITH syntax: Subquery Factoring/CTE
    7. Views

    Advanced Topics


    • Functions, Stored Procedures, Packages
    • Pivoting data: CASE & PIVOT syntax
    • Hierarchical Queries
    • Cursors: Implicit and Explicit
    • Triggers
    • Dynamic SQL
    • Materialized Views
    • Query Optimization: Indexes
    • Query Optimization: Explain Plans
    • Query Optimization: Profiling
    • Data Modelling: Normal Forms, 1 through 3
    • Data Modelling: Primary & Foreign Keys
    • Data Modelling: Table Constraints
    • Data Modelling: Link/Corrollary Tables
    • Full Text Searching
    • XML
    • Isolation Levels
    • Entity Relationship Diagrams (ERDs), Logical and Physical
    • Transactions: COMMIT, ROLLBACK, Error Handling

    Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

    Install the View In Browser plugin using Package Control or download package from github and unzip this package in your packages folder(that from browse packages)

    after this, go to Preferences, Key Bindings - User, paste this

    [{ "keys": [ "f12" ], "command": "view_in_browser" }]

    now F12 will be your shortcut key.

    CSS selectors ul li a {...} vs ul > li > a {...}

    ul > li > a selects only the direct children. In this case only the first level <a> of the first level <li> inside the <ul> will be selected.

    ul li a on the other hand will select ALL <a>-s in ALL <li>-s in the unordered list

    Example of ul > li

    _x000D_
    _x000D_
    ul > li.bg {_x000D_
      background: red;_x000D_
    }
    _x000D_
    <ul>_x000D_
      <li class="bg">affected</li>_x000D_
      <li class="bg">affected</li>    _x000D_
      <li>_x000D_
        <ol>_x000D_
          <li class="bg">NOT affected</li>_x000D_
          <li class="bg">NOT affected</li>_x000D_
        </ol>_x000D_
      </li>_x000D_
    </ul>
    _x000D_
    _x000D_
    _x000D_

    if you'd be using ul li - ALL of the li-s would be affected

    UPDATE The order of more to less efficient CSS selectors goes thus:

    • ID, e.g.#header
    • Class, e.g. .promo
    • Type, e.g. div
    • Adjacent sibling, e.g. h2 + p
    • Child, e.g. li > ul
    • Descendant, e.g. ul a
    • Universal, i.e. *
    • Attribute, e.g. [type="text"]
    • Pseudo-classes/-elements, e.g. a:hover

    So your better bet is to use the children selector instead of just descendant. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.

    Correct way to use StringBuilder in SQL

    In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the + operation on Strings using the append method. You should use it this way:

    return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();
    

    In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.

    StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings

    This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.

    private void addWhereClause(StringBuilder sql, String column, String value) {
       //WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
       sql.append(" where ").append(column).append(" = ").append(value);
    }
    

    More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html

    How do I code my submit button go to an email address

    You might use Form tag with action attribute to submit the mailto.

    Here is an example:

    <form method="post" action="mailto:[email protected]" >
    <input type="submit" value="Send Email" /> 
    </form>
    

    ASP.NET IIS Web.config [Internal Server Error]

    If you have python, you can use a package called iis_bridge that solves the problem. To install:

    pip install iis_bridge
    

    then in the python console:

    import iis_bridge as iis
    iis.install()
    

    Convert string to symbol-able in ruby

    from: http://ruby-doc.org/core/classes/String.html#M000809

    str.intern => symbol
    str.to_sym => symbol
    

    Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

    "Koala".intern         #=> :Koala
    s = 'cat'.to_sym       #=> :cat
    s == :cat              #=> true
    s = '@cat'.to_sym      #=> :@cat
    s == :@cat             #=> true
    

    This can also be used to create symbols that cannot be represented using the :xxx notation.

    'cat and dog'.to_sym   #=> :"cat and dog"
    

    But for your example ...

    "Book Author Title".gsub(/\s+/, "_").downcase.to_sym
    

    should go ;)

    Check if the number is integer

    Once can also use dplyr::near:

    library(dplyr)
    
    near(a, as.integer(a))
    

    It applies to any vector a, and has an optional tolerance parameter.

    How do I mock a service that returns promise in AngularJS Jasmine unit test?

    describe('testing a method() on a service', function () {    
    
        var mock, service
    
        function init(){
             return angular.mock.inject(function ($injector,, _serviceUnderTest_) {
                    mock = $injector.get('service_that_is_being_mocked');;                    
                    service = __serviceUnderTest_;
                });
        }
    
        beforeEach(module('yourApp'));
        beforeEach(init());
    
        it('that has a then', function () {
           //arrange                   
            var spy= spyOn(mock, 'actionBeingCalled').and.callFake(function () {
                return {
                    then: function (callback) {
                        return callback({'foo' : "bar"});
                    }
                };
            });
    
            //act                
            var result = service.actionUnderTest(); // does cleverness
    
            //assert 
            expect(spy).toHaveBeenCalled();  
        });
    });
    

    Is there a way to get a list of all current temporary tables in SQL Server?

    If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)

    If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.

    You can trace the SQL being executed using SQL Profiler:

    [These articles target SQL Server versions later than 2000, but much of the advice is the same.]

    If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.

    How do I test a website using XAMPP?

    create a folder inside htdocs, place your website there, access it via localhost or Internal IP (if you're behind a router) - check out this video demo here

    How do you specify a debugger program in Code::Blocks 12.11?

    Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.

    How to find cube root using Python?

    You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

    The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

    def is_perfect_cube(x):
        x = abs(x)
        return int(round(x ** (1. / 3))) ** 3 == x
    
    print(is_perfect_cube(63))
    print(is_perfect_cube(64))
    print(is_perfect_cube(65))
    print(is_perfect_cube(-63))
    print(is_perfect_cube(-64))
    print(is_perfect_cube(-65))
    print(is_perfect_cube(2146689000)) # no other currently posted solution
                                       # handles this correctly
    

    This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

    The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).