Programs & Examples On #Unicorn

A unicorn is a magical weaponized HTTP server for Ruby.

How to preserve request url with nginx proxy_pass

for my auth server... this works. i like to have options for /auth for my own humanized readability... or also i have it configured by port/upstream for machine to machine.

.

at the beginning of conf

####################################################
upstream auth {
    server 127.0.0.1:9011 weight=1 fail_timeout=300s;
    keepalive 16;
  }

Inside my 443 server block

          if (-d $request_filename) {
          rewrite [^/]$ $scheme://$http_host$uri/ permanent;
      }

  location /auth {
          proxy_pass http://$http_host:9011;
          proxy_set_header Origin           http://$host;
          proxy_set_header Host             $http_host:9011;
          proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade          $http_upgrade;
          proxy_set_header Connection       $http_connection;
          proxy_http_version 1.1;
      }

At the bottom of conf

#####################################################################
#                                                                   #
#     Proxies for all the Other servers on other ports upstream     #
#                                                                   #
#####################################################################


#######################
#        Fusion       #
#######################

server {
    listen 9001 ssl;

#############  Lock it down  ################

# SSL certificate locations
    ssl_certificate /etc/letsencrypt/live/allineed.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/allineed.app/privkey.pem;

# Exclusions

    include snippets/exclusions.conf;

# Security

    include snippets/security.conf;
    include snippets/ssl.conf;

# Fastcgi cache rules

    include snippets/fastcgi-cache.conf;
    include snippets/limits.conf;
    include snippets/nginx-cloudflare.conf;

###########  Location upstream ##############

    location  ~ / {
        proxy_pass http://auth;
        proxy_set_header Origin           http://$host;
        proxy_set_header Host             $host:$server_port;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade          $http_upgrade;
        proxy_set_header Connection       $http_connection;
        proxy_http_version 1.1;
    }
        if (-d $request_filename) {
        rewrite [^/]$ $scheme://$http_host$uri/ permanent;
    }
}

Iterate through dictionary values?

Create the opposite dictionary:

PIX1 = {}
for key in PIX0.keys():
    PIX1[PIX0.get(key)] = key

Then run the same code on this dictionary instead (using PIX1 instead of PIX0).

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.

How to execute shell command in Javascript

If you are using npm you can use the shelljs package

To install: npm install [-g] shelljs

var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});

See more: https://www.npmjs.com/package/shelljs

How to save S3 object to a file using boto3

Note: I'm assuming you have configured authentication separately. Below code is to download the single object from the S3 bucket.

import boto3

#initiate s3 client 
s3 = boto3.resource('s3')

#Download object to the file    
s3.Bucket('mybucket').download_file('hello.txt', '/tmp/hello.txt')

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Here we are just by passing the check by checking for OPTIONS verb.

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

Incorrect syntax near ''

You can identify the encoding used for the file (in this case sql file) using an editor (I used Visual studio code). Once you open the file, it shows you the encoding of the file at the lower right corner on the editor.

encoding

I had this issue when I was trying to check-in a file that was encoded UTF-BOM (originating from a non-windows machine) that had special characters appended to individual string characters

You can change the encoding of your file as follows:

In the bottom bar of VSCode, you'll see the label UTF-8 With BOM. Click it. A popup opens. Click Save with encoding. You can now pick a new encoding for that file (UTF-8)

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

What are the different types of keys in RDBMS?

There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

How do I ZIP a file in C#, using no 3rd-party APIs?

    private static string CompressFile(string sourceFileName)
    {
        using (ZipArchive archive = ZipFile.Open(Path.ChangeExtension(sourceFileName, ".zip"), ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(sourceFileName, Path.GetFileName(sourceFileName));
        }
        return Path.ChangeExtension(sourceFileName, ".zip");
    }

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

How to set up a Web API controller for multipart/form-data

check ur WebApiConfig and add this

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

oracle sql: update if exists else insert

The way I always do it (assuming the data is never to be deleted, only inserted) is to

  • Firstly do an insert, if this fails with a unique constraint violation then you know the row is there,
  • Then do an update

Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert command.)

You can't just do a select count(*) .. where .. as even if that returns zero, and therefore you choose to do an insert, between the time you do the select and the insert someone else might have inserted the row and therefore your insert will fail.

How can I make a list of installed packages in a certain virtualenv?

If you're still a bit confused about virtualenv you might not pick up how to combine the great tips from the answers by Ioannis and Sascha. I.e. this is the basic command you need:

/YOUR_ENV/bin/pip freeze --local

That can be easily used elsewhere. E.g. here is a convenient and complete answer, suited for getting all the local packages installed in all the environments you set up via virtualenvwrapper:

cd ${WORKON_HOME:-~/.virtualenvs}
for dir in *; do [ -d $dir ] && $dir/bin/pip freeze --local >  /tmp/$dir.fl; done
more /tmp/*.fl

Find commit by hash SHA in Git

git log -1 --format="%an %ae%n%cn %ce" a2c25061

The Pretty Formats section of the git show documentation contains

  • format:<string>

The format:<string> format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with %n instead of \n

The placeholders are:

  • %an: author name
  • %ae: author email
  • %cn: committer name
  • %ce: committer email

Open Url in default web browser

Try this:

import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
  Linking.openURL(url);
};

const App = () => {
  return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};

Hope this will solve your problem.

Latex - Change margins of only a few pages

Use the "geometry" package and write \newgeometry{left=3cm,bottom=0.1cm} where you want to change your margins. When you want to reset your margins, you write \restoregeometry.

"ssl module in Python is not available" when installing package with pip3

If you are on OSX and have compiled python from source:

Install openssl using brew brew install openssl

Make sure to follow the instructions brew gives you about setting your CPPFLAGS and LDFLAGS. In my case I am using the [email protected] brew formula and I need these 3 settings for the python build process to correctly link to my SSL library:

export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
export CPPFLAGS="-I/usr/local/opt/[email protected]/include"
export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig"

Assuming the library is installed at that location.

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

Android: How do bluetooth UUIDs work?

UUID is similar in notion to port numbers in Internet. However, the difference between Bluetooth and the Internet is that, in Bluetooth, port numbers are assigned dynamically by the SDP (service discovery protocol) server during runtime where each UUID is given a port number. Other devices will ask the SDP server, who is registered under a reserved port number, about the available services on the device and it will reply with different services distinguishable from each other by being registered under different UUIDs.

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

In Asp.Net Web API - webconfig. This works in all browser.

Add the following code inside the System.web tag

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

Replace your system.webserver tag with this below code

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="false">
  <remove name="WebDAVModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />
<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />

  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

</handlers>

Markdown to create pages and table of contents?

Um... use Markdown's headings!?

That is:

# This is the equivalent of < h1 >

## This is the equivalent of < h4>

### This is the equivalent of < h4>

Many editors will show you a TOC. You can also grep for the heading tags and create your own.

Hope that helps!

--JF

SELECT DISTINCT on one column

Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():

SELECT  *
FROM    (SELECT ID, SKU, Product,
                ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
         FROM   MyTable
         WHERE  SKU LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

"Insert if not exists" statement in SQLite

If you never want to have duplicates, you should declare this as a table constraint:

CREATE TABLE bookmarks(
    users_id INTEGER,
    lessoninfo_id INTEGER,
    UNIQUE(users_id, lessoninfo_id)
);

(A primary key over both columns would have the same effect.)

It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:

INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)

fs: how do I locate a parent folder?

this will also work:

fs.readFile(`${__dirname}/../../foo.bar`);

Trying to get property of non-object - CodeIgniter

To get the value:

$query = $this->db->query("YOUR QUERY");

Then, for single row from(in controller):

$query1 = $query->row();
$data['product'] = $query1;

In view, you can use your own code (above code)

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

How to create a CPU spike with a bash command

Just paste this bad boy into the SSH or console of any server running linux. You can kill the processes manually, but I just shutdown the server when I'm done, quicker.

Edit: I have updated this script to now have a timer feature so that there is no need to kill the processes.

read -p "Please enter the number of minutes for test >" MINTEST && [[ $MINTEST == ?(-)+([0-9]) ]]; NCPU="$(grep -c ^processor /proc/cpuinfo)";  ((endtime=$(date +%s) + ($MINTEST*60))); NCPU=$((NCPU-1)); for ((i=1; i<=$NCPU; i++)); do while (($(date +%s) < $endtime)); do : ; done & done

How to solve SyntaxError on autogenerated manage.py?

You can solve this by adapting the code in your manage.py file to the following

#!/usr/bin/env python
import os
import sys


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangochallenge.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

and your server should work fine.

LINQ extension methods - Any() vs. Where() vs. Exists()

Just so you can find it next time, here is how you search for the enumerable Linq extensions. The methods are static methods of Enumerable, thus Enumerable.Any, Enumerable.Where and Enumerable.Exists.

As the third returns no usable result, I found that you meant List.Exists, thus:

I also recommend hookedonlinq.com as this is has very comprehensive and clear guides, as well clear explanations of the behavior of Linq methods in relation to deferness and lazyness.

Redefine tab as 4 spaces

Make sure vartabstop is unset

set vartabstop=

Set tabstop to 4

set tabstop=4

What's the use of session.flush() in Hibernate

As rightly said in above answers, by calling flush() we force hibernate to execute the SQL commands on Database. But do understand that changes are not "committed" yet. So after doing flush and before doing commit, if you access DB directly (say from SQL prompt) and check the modified rows, you will NOT see the changes.

This is same as opening 2 SQL command sessions. And changes done in 1 session are not visible to others until committed.

How to create a stopwatch using JavaScript?

This is my simple take on this question, I hope it helps someone out oneday, somewhere...

_x000D_
_x000D_
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;

function timer() {
    ms++;
    if(ms >= 100){
        sec++
        ms = 0
    }
    if(sec === 60){
        min++
        sec = 0
    }
    if(min === 60){
        ms, sec, min = 0;
    }

    //Doing some string interpolation
    let milli = ms < 10 ? `0`+ ms : ms;
    let seconds = sec < 10 ? `0`+ sec : sec;
    let minute = min < 10 ? `0` + min : min;

    let timer= `${minute}:${seconds}:${milli}`;
    output.innerHTML =timer;
};
//Start timer
function start(){
 time = setInterval(timer,10);
}
//stop timer
function stop(){
    clearInterval(time)
}
//reset timer
function reset(){
    ms = 0;
    sec = 0;
    min = 0;

    output.innerHTML = `00:00:00`
}
const startBtn = document.getElementById('startBtn');
const stopBtn =  document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');

startBtn.addEventListener('click',start,false);
stopBtn.addEventListener('click',stop,false);
resetBtn.addEventListener('click',reset,false);
_x000D_
    <p class="stopwatch" id="stopwatch">
        <!-- stopwatch goes here -->
    </p>
    <button class="btn-start" id="startBtn">Start</button>
    <button class="btn-stop" id="stopBtn">Stop</button>
    <button class="btn-reset" id="resetBtn">Reset</button>
_x000D_
_x000D_
_x000D_

diff to output only the file names

rsync -rvc --delete --size-only --dry-run source dir target dir

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

You are doing it right with ServerCertificateValidationCallback. This is not the problem you are facing. The problem you are facing is most likely the version of SSL/TLS protocol.

For example, if your server offers only SSLv3 and TLSv10 and your client needs TLSv12 then you will receive this error message. What you need to do is to make sure that both client and server have a common protocol version supported.

When I need a client that is able to connect to as many servers as possible (rather than to be as secure as possible) I use this (together with setting the validation callback):

  ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

How can I style a PHP echo text?

Echo inside an HTML element with class and style the element:

echo "<span class='name'>" . $ip['cityName'] . "</span>";

Binding multiple events to a listener (without JQuery)?

I have a simpler solution for you:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

Redirect stdout to a file in Python?

Programs written in other languages (e.g. C) have to do special magic (called double-forking) expressly to detach from the terminal (and to prevent zombie processes). So, I think the best solution is to emulate them.

A plus of re-executing your program is, you can choose redirections on the command-line, e.g. /usr/bin/python mycoolscript.py 2>&1 1>/dev/null

See this post for more info: What is the reason for performing a double fork when creating a daemon?

Connecting to SQL Server Express - What is my server name?

If sql server is installed on your machine, you should check

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Services You'll see "SQL Server (MSSQLSERVER)"

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> TCP/IP Make sure it's using port number 1433

If you want to see if the port is open and listening try this from your command prompt... telnet 127.0.0.1 1433

And yes, SQL Express installs use localhost\SQLEXPRESS as the instance name by default.

HTML -- two tables side by side

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

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

or simply use css:

div>table {
  float: left
}

What does mvn install in maven exactly do

The install:install goal is provided by «Apache Maven Install Plugin»:

Apache Maven Install Plugin

The Install Plugin is used during the install phase to add artifact(s) to the local repository. The Install Plugin uses the information in the POM (groupId, artifactId, version) to determine the proper location for the artifact within the local repository.

The local repository is the local cache where all artifacts needed for the build are stored. By default, it is located within the user's home directory (~/.m2/repository) but the location can be configured in ~/.m2/settings.xml using the <localRepository> element.

Apache Maven Install Plugin - Introduction.

Having said that, the exact goal purpose:

install:install is used to automatically install the project's main artifact (the JAR, WAR or EAR), its POM and any attached artifacts (sources, javadoc, etc) produced by a particular project.

Apache Maven Install Plugin - Introduction.

For additional details on the goal, please refer to the Apache Maven Install Plugin - install:install page.

For additional details on the build lifecycle in general and on which place the goal has in the build lifecycle, please refer to the Maven – Introduction to the Build Lifecycle page.

Git - Won't add files?

Here you can find an answer to the same problem:

basically in this case the problem was the global_git ignore

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

pycharm convert tabs to spaces automatically

ctrl + shift + A => open pop window to select options, select to spaces to convert all tabs as space, or to tab to convert all spaces as tab.

jQuery datepicker, onSelect won't work

<script type="text/javascript">
    $(function() {
        $("#datepicker").datepicker({ 
              onSelect: function(value, date) { 
                 window.location = 'day.jsp' ; 
              } 
        });
    });
 </script>

<div id="datepicker"></div>

I think you can try this .It works fine .

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

Could not commit JPA transaction: Transaction marked as rollbackOnly

My guess is that ServiceUser.method() is itself transactional. It shouldn't be. Here's the reason why.

Here's what happens when a call is made to your ServiceUser.method() method:

  1. the transactional interceptor intercepts the method call, and starts a transaction, because no transaction is already active
  2. the method is called
  3. the method calls MyService.doSth()
  4. the transactional interceptor intercepts the method call, sees that a transaction is already active, and doesn't do anything
  5. doSth() is executed and throws an exception
  6. the transactional interceptor intercepts the exception, marks the transaction as rollbackOnly, and propagates the exception
  7. ServiceUser.method() catches the exception and returns
  8. the transactional interceptor, since it has started the transaction, tries to commit it. But Hibernate refuses to do it because the transaction is marked as rollbackOnly, so Hibernate throws an exception. The transaction interceptor signals it to the caller by throwing an exception wrapping the hibernate exception.

Now if ServiceUser.method() is not transactional, here's what happens:

  1. the method is called
  2. the method calls MyService.doSth()
  3. the transactional interceptor intercepts the method call, sees that no transaction is already active, and thus starts a transaction
  4. doSth() is executed and throws an exception
  5. the transactional interceptor intercepts the exception. Since it has started the transaction, and since an exception has been thrown, it rollbacks the transaction, and propagates the exception
  6. ServiceUser.method() catches the exception and returns

Android SDK Manager Not Installing Components

Try running Android Studio as an administrator, by right-clicking on the .exe and selecting "Run As Administrator".

Also, some anti-virus programs have been known to interfere with SDK Manager.

The difference between Classes, Objects, and Instances

Class is a template or type. An object is an instance of the class.

For example:

public class Tweet {

}

Tweet newTweet = new Tweet();

Tweet is a class and newTweet is an object of the class.

How to deal with persistent storage (e.g. databases) in Docker

While this is still a part of Docker that needs some work, you should put the volume in the Dockerfile with the VOLUME instruction so you don't need to copy the volumes from another container.

That will make your containers less inter-dependent and you don't have to worry about the deletion of one container affecting another.

How to pass command line arguments to a shell alias?

You found the way: create a function instead of an alias. The C shell has a mechanism for doing arguments to aliases, but bash and the Korn shell don't, because the function mechanism is more flexible and offers the same capability.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

How to calculate date difference in JavaScript?

Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

var difference = date2 - date1;

From there, you can use simple arithmetic to derive the other values.

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

I need to round a float to two decimal places in Java

Try looking at the BigDecimal Class. It is the go to class for currency and support accurate rounding.

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

Remove HTML tags from a String

This should work -

use this

  text.replaceAll('<.*?>' , " ") -> This will replace all the html tags with a space.

and this

  text.replaceAll('&.*?;' , "")-> this will replace all the tags which starts with "&" and ends with ";" like &nbsp;, &amp;, &gt; etc.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

You can also use this stored procedure if you only want to truncate all tables in a specific schema:

-- =============================================
-- Author:      Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
    @schema nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @table nVARCHAR(255)

    DECLARE db_cursor CURSOR FOR 
        select t.name
          from sys.tables t inner join
               sys.schemas s on 
                    t.schema_id=s.schema_id
         where s.name=@schema
         order by 1

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @table   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           declare @sql nvarchar(1000)

           set @sql = 'truncate table [' + @schema + '].[' + @table + ']'

           exec sp_sqlexec @sql

           FETCH NEXT FROM db_cursor INTO @table   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor 

END
GO

Difference between 'struct' and 'typedef struct' in C++?

There is no difference in C++, but I believe in C it would allow you to declare instances of the struct Foo without explicitly doing:

struct Foo bar;

How can I verify a Google authentication API access token?

you can verify a Google authentication access token by using this endpoint:

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>

This is Google V3 OAuth AccessToken validating endpoint, you can refer from google document below: (In OAUTH 2.0 ENDPOINTS Tab)

https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token

Is it possible to get only the first character of a String?

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

JVM heap parameters

The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.

It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.

As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.

How to convert a multipart file to File?

Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());

Where multipartFile is your org.springframework.web.multipart.MultipartFile.

Call a React component method from outside

I've done something like this:

class Cow extends React.Component {

    constructor (props) {
        super(props);
        this.state = {text: 'hello'};
    }

    componentDidMount () {
        if (this.props.onMounted) {
            this.props.onMounted({
                say: text => this.say(text)
            });
        }
    }

    render () {
        return (
            <pre>
                 ___________________
                < {this.state.text} >
                 -------------------
                        \   ^__^
                         \  (oo)\_______
                            (__)\       )\/\
                                ||----w |
                                ||     ||
            </pre>
        );
    }

    say (text) {
        this.setState({text: text});
    }

}

And then somewhere else:

class Pasture extends React.Component {

    render () {
        return (
            <div>
                <Cow onMounted={callbacks => this.cowMounted(callbacks)} />
                <button onClick={() => this.changeCow()} />
            </div>
        );
    }

    cowMounted (callbacks) {
        this.cowCallbacks = callbacks;
    }

    changeCow () {
        this.cowCallbacks.say('moo');
    }

}

I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.

Remove insignificant trailing zeros from a number?

I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

In addition to trimming the trailing zeros, I also had the need to round off and format the output for the user's current locale (i.e. 123,456.789).

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js


Usage Examples:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)


Updated - August, 2018


All modern browsers now support the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

let formatters = {
    default: new Intl.NumberFormat(),
    currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
    twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};

formatters.twoDecimal.format(1234.5678);  // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"

For older browsers, you can use this polyfill: https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en

Set div height to fit to the browser using CSS

Setting window full height for empty divs

1st solution with absolute positioning - FIDDLE

.div1 {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 25%;
}
.div2 {
  position: absolute;
  top: 0;
  left: 25%;
  bottom: 0;
  width: 75%;
}

2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE

.div1 {
  float: left;
  width: 25%;
}
.div2 {
  float: left;
  width: 75%;
}

$(function(){
  $('.div1, .div2').css({ height: $(window).innerHeight() });
  $(window).resize(function(){
    $('.div1, .div2').css({ height: $(window).innerHeight() });
  });
});

loading json data from local file into React JS

If you have couple of json files:

import data from 'sample.json';

If you were to dynamically load one of the many json file, you might have to use a fetch instead:

fetch(`${fileName}.json`)
  .then(response => response.json())
  .then(data => console.log(data))

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

What's the difference between ASCII and Unicode?

java provides support for Unicode i.e it supports all world wide alphabets. Hence the size of char in java is 2 bytes. And range is 0 to 65535.

enter image description here

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

If you are using WAMP/XAMP server turn it off. This resolved my problem.

How to disable sort in DataGridView?

If you can extend the DataGridView you can override the Sort method with am empty one. This disables Sort for the DataGridView entirely.

public override void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction)
{
    //base.Sort(dataGridViewColumn, direction);
}

Note: You cannot even programmatically sort any column.

Add a space (" ") after an element using :after

element::after { 
    display: block;
    content: " ";
}

This worked for me.

Big-oh vs big-theta

I'm a mathematician and I have seen and needed big-O O(n), big-Theta T(n), and big-Omega O(n) notation time and again, and not just for complexity of algorithms. As people said, big-Theta is a two-sided bound. Strictly speaking, you should use it when you want to explain that that is how well an algorithm can do, and that either that algorithm can't do better or that no algorithm can do better. For instance, if you say "Sorting requires T(n(log n)) comparisons for worst-case input", then you're explaining that there is a sorting algorithm that uses O(n(log n)) comparisons for any input; and that for every sorting algorithm, there is an input that forces it to make O(n(log n)) comparisons.

Now, one narrow reason that people use O instead of O is to drop disclaimers about worst or average cases. If you say "sorting requires O(n(log n)) comparisons", then the statement still holds true for favorable input. Another narrow reason is that even if one algorithm to do X takes time T(f(n)), another algorithm might do better, so you can only say that the complexity of X itself is O(f(n)).

However, there is a broader reason that people informally use O. At a human level, it's a pain to always make two-sided statements when the converse side is "obvious" from context. Since I'm a mathematician, I would ideally always be careful to say "I will take an umbrella if and only if it rains" or "I can juggle 4 balls but not 5", instead of "I will take an umbrella if it rains" or "I can juggle 4 balls". But the other halves of such statements are often obviously intended or obviously not intended. It's just human nature to be sloppy about the obvious. It's confusing to split hairs.

Unfortunately, in a rigorous area such as math or theory of algorithms, it's also confusing not to split hairs. People will inevitably say O when they should have said O or T. Skipping details because they're "obvious" always leads to misunderstandings. There is no solution for that.

How do I auto-hide placeholder text upon focus using css or jquery?

To further refine Wallace Sidhrée's code sample:

$(function()
{  
      $('input').focusin(function()
      {
        input = $(this);
        input.data('place-holder-text', input.attr('placeholder'))
        input.attr('placeholder', '');
      });

      $('input').focusout(function()
      {
          input = $(this);
          input.attr('placeholder', input.data('place-holder-text'));
      });
})

This ensures that each input stores the correct placeholder text in the data attribute.

See a working example here in jsFiddle.

Tracking the script execution time in PHP

Just to contribute to this conversation:

  • what happens if the measurement targets two points A and B in different php files?

  • what if we need different measurements like time based, code execution duration, external resource access duration?

  • what if we need to organize our measurements in categories where every one has a different starting point?

As you suspect we need some global variables to be accessed by a class object or a static method: I choose the 2nd approach and here it is:

namespace g3;

class Utils {
   public function __construct() {}

   public static $UtilsDtStart = [];
   public static $UtilsDtStats = [];

   public static function dt() {
      global $UtilsDtStart, $UtilsDtStats;
      $obj = new \stdClass();
      $obj->start = function(int $ndx = 0) use (&$UtilsDtStart) {
         $UtilsDtStart[$ndx] = \microtime(true) * 1000;
      };
      $obj->codeStart = function(int $ndx = 0) use (&$UtilsDtStart) {
         $use = \getrusage();
         $UtilsDtStart[$ndx] = ($use["ru_utime.tv_sec"] * 1000) + ($use["ru_utime.tv_usec"] / 1000);
      };
      $obj->resourceStart = function(int $ndx = 0) use (&$UtilsDtStart) {
         $use = \getrusage();
         $UtilsDtStart[$ndx] = $use["ru_stime.tv_usec"] / 1000;
      };
      $obj->end = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $end = \microtime(true) * 1000;
         $dt = $end - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->codeEnd = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $use = \getrusage();
         $dt = ($use["ru_utime.tv_sec"] * 1000) + ($use["ru_utime.tv_usec"] / 1000) - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->resourceEnd = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $use = \getrusage();
         $dt = ($use["ru_stime.tv_usec"] / 1000) - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->stats = function(int $ndx = 0) use (&$UtilsDtStats) {
         $s = @$UtilsDtStats[$ndx];
         if($s !== null)
            $s = \array_slice($s, 0);
         else
            $s = false;
         return $s;
      };
      $obj->statsLength = function() use (&$UtilsDtStats) {
         return \count($UtilsDtStats);
      };
      return $obj;
   }
}

Now all you have is to call the method that belongs to the specific category with the index that denotes it's unique group:

File A
------
\call_user_func_array(\g3\Utils::dt()->start, [0]);   // point A
...
File B
------
$dt = \call_user_func_array(\g3\Utils::dt()->end, [0]);  // point B

Value $dt contains the milliseconds of wall clock duration between points A and B.

To estimate the time took for php code to run:

File A
------
\call_user_func_array(\g3\Utils::dt()->codeStart, [1]);   // point A
...
File B
------
$dt = \call_user_func_array(\g3\Utils::dt()->codeEnd, [1]);  // point B

Notice how we changed the index that we pass at the methods.

The code is based on the closure effect that happens when we return an object/function from a function (see that \g3\Utils::dt() repeated at the examples).

I tested with php unit and between different test methods at the same test file it behaves fine so far!

Hope that helps someone!

What is a mixin, and why are they useful?

OP mentioned that he/she never heard of mixin in C++, perhaps that is because they are called Curiously Recurring Template Pattern (CRTP) in C++. Also, @Ciro Santilli mentioned that mixin is implemented via abstract base class in C++. While abstract base class can be used to implement mixin, it is an overkill as the functionality of virtual function at run-time can be achieved using template at compile time without the overhead of virtual table lookup at run-time.

The CRTP pattern is described in detail here

I have converted the python example in @Ciro Santilli's answer into C++ using template class below:

    #include <iostream>
    #include <assert.h>

    template <class T>
    class ComparableMixin {
    public:
        bool operator !=(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) == static_cast<T&>(other));
        }
        bool operator <(ComparableMixin &other) {
            return ((*(this) != other) && (*static_cast<T*>(this) <= static_cast<T&>(other)));
        }
        bool operator >(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) <= static_cast<T&>(other));
        }
        bool operator >=(ComparableMixin &other) {
            return ((*static_cast<T*>(this) == static_cast<T&>(other)) || (*(this) > other));
        }
        protected:
            ComparableMixin() {}
    };

    class Integer: public ComparableMixin<Integer> {
    public:
     Integer(int i) {
         this->i = i;
     }
     int i;
     bool operator <=(Integer &other) {
         return (this->i <= other.i);
     }
     bool operator ==(Integer &other) {
         return (this->i == other.i);
     }
    };

int main() {

    Integer i(0) ;
    Integer j(1) ;
    //ComparableMixin<Integer> c; // this will cause compilation error because constructor is protected.
    assert (i < j );
    assert (i != j);
    assert (j >  i);
    assert (j >= i);

    return 0;
}

EDIT: Added protected constructor in ComparableMixin so that it can only be inherited and not instantiated. Updated the example to show how protected constructor will cause compilation error when an object of ComparableMixin is created.

C# equivalent of the IsNull() function in SQL Server

public static T isNull<T>(this T v1, T defaultValue)
{
    return v1 == null ? defaultValue : v1;
}

myValue.isNull(new MyValue())

Detect & Record Audio in Python

I believe the WAVE module does not support recording, just processing existing files. You might want to look at PyAudio for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is quieter. I can't remember if WAV files are high byte first or low byte, but something like this ought to work (sorry, I'm not really a python programmer:

from array import array

# you'll probably want to experiment on threshold
# depends how noisy the signal
threshold = 10 
max_value = 0

as_ints = array('h', data)
max_value = max(as_ints)
if max_value > threshold:
    # not silence

PyAudio code for recording kept for reference:

import pyaudio
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS, 
                rate=RATE, 
                input=True,
                output=True,
                frames_per_buffer=chunk)

print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
    data = stream.read(chunk)
    # check for silence here by comparing the level with 0 (or some threshold) for 
    # the contents of data.
    # then write data or not to a file

print "* done"

stream.stop_stream()
stream.close()
p.terminate()

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

Pure Javascript listen to input value change

As a basic example...

HTML:

<input type="text" name="Thing" value="" />

Script:

/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);

/* function */
function doThing(){
   alert('Horray! Someone wrote "' + this.value + '"!');
}

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

Going to a specific line number using Less in Unix

For editing this is possible in nano via +n from command line, e.g.,

nano +16 file.txt

To open file.txt to line 16.

MySQL "incorrect string value" error when save unicode string in Django

You can change the collation of your text field to UTF8_general_ci and the problem will be solved.

Notice, this cannot be done in Django.

Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

How can I write output from a unit test?

I think it is still actual.

You can use this NuGet package: Bitoxygen.Testing.Pane

Call the custom WriteLine method from this library. It creates a Testing pane inside the Output window and puts messages there always (during each test, it runs independently of DEBUG and TRACE flags).

To make tracing more easy I can recommend to create a base class:

[TestClass]
public abstract class BaseTest
{
    #region Properties
    public TestContext TestContext { get; set; }

    public string Class
    {
        get { return this.TestContext.FullyQualifiedTestClassName; }
    }
    public string Method
    {
        get { return this.TestContext.TestName; }
    }
    #endregion

    #region Methods
    protected virtual void Trace(string message)
    {
        System.Diagnostics.Trace.WriteLine(message);

        Output.Testing.Trace.WriteLine(message);
    }
    #endregion
}

[TestClass]
public class SomeTest : BaseTest
{
    [TestMethod]
    public void SomeTest1()
    {
        this.Trace(string.Format("Yeah: {0} and {1}", this.Class, this.Method));
    }
}

How to redirect the output of the time command to a file in Linux?

Wrap time and the command you are timing in a set of brackets.

For example, the following times ls and writes the result of ls and the results of the timing into outfile:

$ (time ls) > outfile 2>&1

Or, if you'd like to separate the output of the command from the captured output from time:

$ (time ls) > ls_results 2> time_results

Array.size() vs Array.length

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

Flask ImportError: No Module Named Flask

  1. Edit /etc/apache2/sites-available/FlaskApp.conf
  2. Add the following two lines before the "WSGIScriptAlias" line:

WSGIDaemonProcess FlaskApp python-home=/var/www/FlaskApp/FlaskApp/venv/FlaskApp WSGIProcessGroup FlaskApp

  1. Restart Apache:service apache2 restart

I'm following the Flask tutorial too.And I met the same problem.I found this way to fix it.

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

How do I find the install time and date of Windows?

Try this powershell command:

Get-ChildItem -Path HKLM:\System\Setup\Source* | 
 ForEach-Object {Get-ItemProperty -Path Registry::$_} | 
     Select-Object ProductName, ReleaseID, CurrentBuild, @{n="Install Date"; e={([DateTime]'1/1/1970').AddSeconds($_.InstallDate)}} | 
         Sort-Object "Install Date"

What is difference between png8 and png24

You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

  • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
  • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
  • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
  • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
  • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

Confused about Service vs Factory

There is also a way to return a constructor function so you can return newable classes in factories, like this:

function MyObjectWithParam($rootScope, name) {
  this.$rootScope = $rootScope;
  this.name = name;
}
MyObjectWithParam.prototype.getText = function () {
  return this.name;
};

App.factory('MyObjectWithParam', function ($injector) {
  return function(name) { 
    return $injector.instantiate(MyObjectWithParam,{ name: name });
  };
}); 

So you can do this in a controller, which uses MyObjectWithParam:

var obj = new MyObjectWithParam("hello"),

See here the full example:
http://plnkr.co/edit/GKnhIN?p=preview

And here the google group pages, where it was discussed:
https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/b8hdPskxZXsJ

How to display pdf in php

if(isset($_GET['content'])){
  $content = $_GET['content'];
  $dir = $_GET['dir'];
  header("Content-type:".$content);
  @readfile($dir);
}

$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
 //the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
 if($handle = opendir($directory)){ //opens directory if existing.
   while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
     echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';
}

}

if you click the link a new window will appear with the pdf file

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me it was a silly mistake. I inadvertently set the test as private instead of public:

@Test
private void thisTestWasCausingProblems() {
...
}

it should have been

@Test
public void thisTestIsOK() {
...
}

Regex to remove letters, symbols except numbers

Try the following regex:

var removedText = self.val().replace(/[^0-9]/, '');

This will match every character that is not (^) in the interval 0-9.

Demo.

default select option as blank

Try this:

<h2>Favorite color</h2>
<select name="color">
<option value=""></option>
<option>Pink</option>
<option>Red</option>
<option>Blue</option>
</select>

The first option in the drop down would be blank.

How to add a search box with icon to the navbar in Bootstrap 3?

I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form need to be added an attribute width.

<form role="search" style="width: 15em; margin: 0.3em 2em;">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="Search">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default">
                <span class="glyphicon glyphicon-search"></span>
            </button>
        </div>
    </div>
</form> 

<Django object > is not JSON serializable

Another great way of solving it while using a model is by using the values() function.

def returnResponse(date):
    response = ScheduledDate.objects.filter(date__startswith=date).values()
    return Response(response)

Returning first x items from array

If you just want to output the first 5 elements, you should write something like:

<?php

  if (!empty ( $an_array ) ) {

    $min = min ( count ( $an_array ), 5 );

    $i = 0;

    foreach ($value in $an_array) {

      echo $value;
      $i++;
      if ($i == $min) break;

    }

  }

?>

If you want to write a function which returns part of the array, you should use array_slice:

<?php

  function GetElements( $an_array, $elements ) {
    return array_slice( $an_array, 0, $elements );
  }

?>

How to implement a binary tree?

Here is a simple solution which can be used to build a binary tree using a recursive approach to display the tree in order traversal has been used in the below code.

class Node(object):

    def __init__(self):
        self.left = None
        self.right = None
        self.value = None
    @property
    def get_value(self):
        return self.value

    @property
    def get_left(self):
        return self.left

    @property
    def get_right(self):
        return self.right

    @get_left.setter
    def set_left(self, left_node):
        self.left = left_node
    @get_value.setter
    def set_value(self, value):
        self.value = value
    @get_right.setter
    def set_right(self, right_node):
        self.right = right_node



    def create_tree(self):
        _node = Node() #creating new node.
        _x = input("Enter the node data(-1 for null)")
        if(_x == str(-1)): #for defining no child.
            return None
        _node.set_value = _x #setting the value of the node.
        print("Enter the left child of {}".format(_x))
        _node.set_left = self.create_tree() #setting the left subtree
        print("Enter the right child of {}".format(_x))
        _node.set_right = self.create_tree() #setting the right subtree.

        return _node

    def pre_order(self, root):
        if root is not None:
            print(root.get_value)
            self.pre_order(root.get_left)
            self.pre_order(root.get_right)

if __name__ == '__main__':
    node = Node()
    root_node = node.create_tree()
    node.pre_order(root_node)

Code taken from : Binary Tree in Python

Parsing jQuery AJAX response

Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

Or you can parse the data string into JSON after you receive it, like so:

    success: function (data) {
         var obj = $.parseJSON(data);
         console.log(obj);
    },

check if "it's a number" function in Oracle

One additional idea, mentioned here is to use a regular expression to check:

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^[[:digit:]]+$');

The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.

See :hover state in Chrome Developer Tools

I don't think there is a way to do this. I submitted a feature request. If there is a way, the developers at Google will surly point it out and I will edit my answer. If not, we will have to wait and watch. (you can star the issue to vote for it)


Comment 1 by Chrome project member: In 10.0.620.0, the Styles panel shows the :hover styles for the selected element but not :active.


(as of this post) Current Stable channel version is 8.0.552.224.

You can replace your Stable channel installation of Google Chrome with the Beta channel or the Dev channel (See Early Access Release Channels).

You can also install a secondary installation of chrome that is even more up to date than the Dev channel.

... The Canary build is updated even more frequently than the Dev channel and is not tested before being released. Because the Canary build may at times be unusable, it cannot be set as your default browser and may be installed in addition to any of the above channels of Google Chrome. ...

Best way to handle multiple constructors in Java

Several people have recommended adding a null check. Sometimes that's the right thing to do, but not always. Check out this excellent article showing why you'd skip it.

http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/

HttpContext.Current.Session is null when routing requests

Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

How do I see the current encoding of a file in Sublime Text?

With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.

Demo

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Use oracle.jdbc.OracleDriver, not oracle.jdbc.driver.OracleDriver. You do not need to register it if the driver jar file is in the "WEB-INF\lib" directory, if you are using Tomcat. Save this as test.jsp and put it in your web directory, and redeploy your web app folder in Tomcat manager:

<%@ page import="java.sql.*" %>

<HTML>
<HEAD>
<TITLE>Simple JSP Oracle Test</TITLE>
</HEAD><BODY>
<%
Connection conn = null;
try {
    Class.forName("oracle.jdbc.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@XXX.XXX.XXX.XXX:XXXX:dbName", "user", "password");
    Statement stmt = conn.createStatement();
    out.println("Connection established!");
}
catch (Exception ex)
{
    out.println("Exception: " + ex.getMessage() + "");

}
finally
{
    if (conn != null) {
        try {
            conn.close();   
        }
        catch (Exception ignored) {
            // ignore
        }
    }
}

%>

Angular 2.0 router not working on reloading the browser

The error you are seeing is because you are requesting http://localhost/route which doesn't exist. According to Simon.

When using html5 routing you need to map all routes in your app(currently 404) to index.html in your server side. Here are some options for you:

  1. using live-server: https://www.npmjs.com/package/live-server

    $live-server --entry-file=index.html`
    
  2. using nginx: http://nginx.org/en/docs/beginners_guide.html

    error_page 404 /index.html
    
  3. Tomcat - configuration of web.xml. From Kunin's comment

    <error-page>
          <error-code>404</error-code>
          <location>/index.html</location>
    </error-page>
    

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I am not sure this will help but I resolved the issue by importing mongoose like below and implementing it as below

const mongoose = require('mongoose')

_id: new mongoose.Types.ObjectId(),

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Yes, __attribute__((packed)) is potentially unsafe on some systems. The symptom probably won't show up on an x86, which just makes the problem more insidious; testing on x86 systems won't reveal the problem. (On the x86, misaligned accesses are handled in hardware; if you dereference an int* pointer that points to an odd address, it will be a little slower than if it were properly aligned, but you'll get the correct result.)

On some other systems, such as SPARC, attempting to access a misaligned int object causes a bus error, crashing the program.

There have also been systems where a misaligned access quietly ignores the low-order bits of the address, causing it to access the wrong chunk of memory.

Consider the following program:

#include <stdio.h>
#include <stddef.h>
int main(void)
{
    struct foo {
        char c;
        int x;
    } __attribute__((packed));
    struct foo arr[2] = { { 'a', 10 }, {'b', 20 } };
    int *p0 = &arr[0].x;
    int *p1 = &arr[1].x;
    printf("sizeof(struct foo)      = %d\n", (int)sizeof(struct foo));
    printf("offsetof(struct foo, c) = %d\n", (int)offsetof(struct foo, c));
    printf("offsetof(struct foo, x) = %d\n", (int)offsetof(struct foo, x));
    printf("arr[0].x = %d\n", arr[0].x);
    printf("arr[1].x = %d\n", arr[1].x);
    printf("p0 = %p\n", (void*)p0);
    printf("p1 = %p\n", (void*)p1);
    printf("*p0 = %d\n", *p0);
    printf("*p1 = %d\n", *p1);
    return 0;
}

On x86 Ubuntu with gcc 4.5.2, it produces the following output:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = 0xbffc104f
p1 = 0xbffc1054
*p0 = 10
*p1 = 20

On SPARC Solaris 9 with gcc 4.5.1, it produces the following:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = ffbff317
p1 = ffbff31c
Bus error

In both cases, the program is compiled with no extra options, just gcc packed.c -o packed.

(A program that uses a single struct rather than array doesn't reliably exhibit the problem, since the compiler can allocate the struct on an odd address so the x member is properly aligned. With an array of two struct foo objects, at least one or the other will have a misaligned x member.)

(In this case, p0 points to a misaligned address, because it points to a packed int member following a char member. p1 happens to be correctly aligned, since it points to the same member in the second element of the array, so there are two char objects preceding it -- and on SPARC Solaris the array arr appears to be allocated at an address that is even, but not a multiple of 4.)

When referring to the member x of a struct foo by name, the compiler knows that x is potentially misaligned, and will generate additional code to access it correctly.

Once the address of arr[0].x or arr[1].x has been stored in a pointer object, neither the compiler nor the running program knows that it points to a misaligned int object. It just assumes that it's properly aligned, resulting (on some systems) in a bus error or similar other failure.

Fixing this in gcc would, I believe, be impractical. A general solution would require, for each attempt to dereference a pointer to any type with non-trivial alignment requirements either (a) proving at compile time that the pointer doesn't point to a misaligned member of a packed struct, or (b) generating bulkier and slower code that can handle either aligned or misaligned objects.

I've submitted a gcc bug report. As I said, I don't believe it's practical to fix it, but the documentation should mention it (it currently doesn't).

UPDATE: As of 2018-12-20, this bug is marked as FIXED. The patch will appear in gcc 9 with the addition of a new -Waddress-of-packed-member option, enabled by default.

When address of packed member of struct or union is taken, it may result in an unaligned pointer value. This patch adds -Waddress-of-packed-member to check alignment at pointer assignment and warn unaligned address as well as unaligned pointer

I've just built that version of gcc from source. For the above program, it produces these diagnostics:

c.c: In function ‘main’:
c.c:10:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   10 |     int *p0 = &arr[0].x;
      |               ^~~~~~~~~
c.c:11:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   11 |     int *p1 = &arr[1].x;
      |               ^~~~~~~~~

PostgreSQL "DESCRIBE TABLE"

Try this (in the psql command-line tool):

\d+ tablename

See the manual for more info.

How to destroy an object?

I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.

In Perl, how do I create a hash whose keys come from a given array?

In perl 5.10, there's the close-to-magic ~~ operator:

sub invite_in {
    my $vampires = [ qw(Angel Darla Spike Drusilla) ];
    return ($_[0] ~~ $vampires) ? 0 : 1 ;
}

See here: http://dev.perl.org/perl5/news/2007/perl-5.10.0.html

How do I right align div elements?

Floats are okay, but problematic with IE 6 & 7.
I'd prefer using the following on the inner div:

margin-left: auto; 
margin-right: 0;

See the IE Double Margin Bug for clarification on why.

What do I use for a max-heap implementation in Python?

The solution is to negate your values when you store them in the heap, or invert your object comparison like so:

import heapq

class MaxHeapObj(object):
  def __init__(self, val): self.val = val
  def __lt__(self, other): return self.val > other.val
  def __eq__(self, other): return self.val == other.val
  def __str__(self): return str(self.val)

Example of a max-heap:

maxh = []
heapq.heappush(maxh, MaxHeapObj(x))
x = maxh[0].val  # fetch max value
x = heapq.heappop(maxh).val  # pop max value

But you have to remember to wrap and unwrap your values, which requires knowing if you are dealing with a min- or max-heap.

MinHeap, MaxHeap classes

Adding classes for MinHeap and MaxHeap objects can simplify your code:

class MinHeap(object):
  def __init__(self): self.h = []
  def heappush(self, x): heapq.heappush(self.h, x)
  def heappop(self): return heapq.heappop(self.h)
  def __getitem__(self, i): return self.h[i]
  def __len__(self): return len(self.h)

class MaxHeap(MinHeap):
  def heappush(self, x): heapq.heappush(self.h, MaxHeapObj(x))
  def heappop(self): return heapq.heappop(self.h).val
  def __getitem__(self, i): return self.h[i].val

Example usage:

minh = MinHeap()
maxh = MaxHeap()
# add some values
minh.heappush(12)
maxh.heappush(12)
minh.heappush(4)
maxh.heappush(4)
# fetch "top" values
print(minh[0], maxh[0])  # "4 12"
# fetch and remove "top" values
print(minh.heappop(), maxh.heappop())  # "4 12"

How do I pass multiple parameters into a function in PowerShell?

You can pass parameters in a function like this also:

function FunctionName()
{
    Param ([string]$ParamName);
    # Operations
}

shell script to remove a file if it already exist

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f "$file" ] ; then
    rm "$file"
fi

How to view data saved in android database(SQLite)?

1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.

Synchronous Requests in Node.js

In 2018, you can program the "usual" style using async and await in Node.js.

Below is an example, that wraps request callback in a promise and then uses await to get the resolved value.

const request = require('request');

// wrap a request in an promise
function downloadPage(url) {
    return new Promise((resolve, reject) => {
        request(url, (error, response, body) => {
            if (error) reject(error);
            if (response.statusCode != 200) {
                reject('Invalid status code <' + response.statusCode + '>');
            }
            resolve(body);
        });
    });
}

// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
    try {
        const html = await downloadPage('https://microsoft.com')
        console.log('SHOULD WORK:');
        console.log(html);

        // try downloading an invalid url
        await downloadPage('http://      .com')
    } catch (error) {
        console.error('ERROR:');
        console.error(error);
    }
}

// run your async function
myBackEndLogic();

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

Printing pointers in C

"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

What data type to use for hashed password field and what length?

You might find this Wikipedia article on salting worthwhile. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.

Dynamic constant assignment

Ruby doesn't like that you are assigning the constant inside of a method because it risks re-assignment. Several SO answers before me give the alternative of assigning it outside of a method--but in the class, which is a better place to assign it.

Variable length (Dynamic) Arrays in Java

Arrays are fixed size once instantiated. You can use a List instead.

Autoboxing make a List usable similar to an array, you can put simply int-values into it:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to use EditText onTextChanged event when I press the number?

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

How can I get a count of the total number of digits in a number?

Create a method that returns all digits, and another that counts them:

public static int GetNumberOfDigits(this long value)
{
    return value.GetDigits().Count();
}

public static IEnumerable<int> GetDigits(this long value)
{
    do
    {
        yield return (int)(value % 10);
        value /= 10;
    } while (value != 0);
}

This felt like the more intuitive approach to me when tackling this problem. I tried the Log10 method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.

I also found the if-chain proposed in the other answer to a bit ugly to look at.

I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private if you don't need to use it outside the class).

Keep in mind that it does not consider the negative sign as a digit.

How can I convert integer into float in Java?

Here is how you can do it :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you !

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

How do I disable directory browsing?

Edit/Create an .htaccess file inside /galerias with this:

Options -Indexes

Directory browsing is provided by the mod_autoindex module.

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

If you have UTF8, use this (actually works with SVG source), like:

btoa(unescape(encodeURIComponent(str)))

example:

 var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup)));
 var img = new Image(1, 1); // width, height values are optional params 
 img.src = imgsrc;

If you need to decode that base64, use this:

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Example:

var str = "äöüÄÖÜçéèñ";
var b64 = window.btoa(unescape(encodeURIComponent(str)))
console.log(b64);

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Note: if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...

function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(escape(window.atob( str )));
}

2017 Update

This problem has been bugging me again.
The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only.
Also, I wouldn't use bloatware like js-base64.
But webtoolkit does have a small, nice and very maintainable implementation:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info
*
**/
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="

    // public method for encoding
    , encode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length)
        {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2))
            {
                enc3 = enc4 = 64;
            }
            else if (isNaN(chr3))
            {
                enc4 = 64;
            }

            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        } // Whend 

        return output;
    } // End Function encode 


    // public method for decoding
    ,decode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length)
        {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64)
            {
                output = output + String.fromCharCode(chr2);
            }

            if (enc4 != 64)
            {
                output = output + String.fromCharCode(chr3);
            }

        } // Whend 

        output = Base64._utf8_decode(output);

        return output;
    } // End Function decode 


    // private method for UTF-8 encoding
    ,_utf8_encode: function (string)
    {
        var utftext = "";
        string = string.replace(/\r\n/g, "\n");

        for (var n = 0; n < string.length; n++)
        {
            var c = string.charCodeAt(n);

            if (c < 128)
            {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048))
            {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else
            {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        } // Next n 

        return utftext;
    } // End Function _utf8_encode 

    // private method for UTF-8 decoding
    ,_utf8_decode: function (utftext)
    {
        var string = "";
        var i = 0;
        var c, c1, c2, c3;
        c = c1 = c2 = 0;

        while (i < utftext.length)
        {
            c = utftext.charCodeAt(i);

            if (c < 128)
            {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224))
            {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else
            {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        } // Whend 

        return string;
    } // End Function _utf8_decode 

}

https://www.fileformat.info/info/unicode/utf8.htm

  • For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.

  • For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).

  • For all characters equal to or greater than 2048 but less that 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.

Why extend the Android Application class?

You can access variables to any class without creating objects, if its extended by Application. They can be called globally and their state is maintained till application is not killed.

Git pushing to remote branch

First, let's note that git push "wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec.

The remote part is usually trivial as it's almost always just the word origin. The trickier part is the refspec. Most commonly, people write a branch name here: git push origin master, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.

In particular, a refspec has two colon-separated parts. For git push, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name and the part on the right would be branch_name_test. For instance:

git push origin foo:foo_test

As you are doing the push, you can tell your git push to set your branch's upstream name at the same time, by adding -u to the git push options. Setting the upstream name makes your git save the foo_test (or whatever) name, so that a future git push with no arguments, while you're on the foo branch, can try to push to foo_test on the remote (git also saves the remote, origin in this case, so that you don't have to enter that either).

You need only pass -u once: it basically just runs git branch --set-upstream-to for you. (If you pass -u again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to yourself.)

However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default will be set to simple, which will refuse to push because the upstream's name differs from your own local name. If you set push.default to upstream, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)


1More precisely, git consults your remote.remote.push setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.

2This doesn't have to be a branch name. For instance, you can supply HEAD, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch on the right, though (it depends on what names are already on the remote).

How to show the text on a ImageButton?

you can use a regular Button and the android:drawableTop attribute (or left, right, bottom) instead.

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

Adding a module (Specifically pymorph) to Spyder (Python IDE)

just use '!' before the pip command in spyder terminal and it will be fine

Eg:

!pip install imutils

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

docker run <IMAGE> <MULTIPLE COMMANDS>

You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.

Simplest code for array intersection in javascript

My contribution in ES6 terms. In general it finds the intersection of an array with indefinite number of arrays provided as arguments.

_x000D_
_x000D_
Array.prototype.intersect = function(...a) {_x000D_
  return [this,...a].reduce((p,c) => p.filter(e => c.includes(e)));_x000D_
}_x000D_
var arrs = [[0,2,4,6,8],[4,5,6,7],[4,6]],_x000D_
     arr = [0,1,2,3,4,5,6,7,8,9];_x000D_
_x000D_
document.write("<pre>" + JSON.stringify(arr.intersect(...arrs)) + "</pre>");
_x000D_
_x000D_
_x000D_

How to change the DataTable Column Name?

Use:

dt.Columns["Name"].ColumnName = "xyz";
dt.AcceptChanges();

or

dt.Columns[0].ColumnName = "xyz";
dt.AcceptChanges();

Cannot get OpenCV to compile because of undefined references?

If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.

cmake_minimum_required(VERSION 2.8)

SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)

# find_package( OpenCV )

project(edge.cpp)

add_executable(edge edge.cpp)

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

Language Books/Tutorials for popular languages

C++

The first one is good for beginners and the second one requires more advanced level in C++.

How to fix Python Numpy/Pandas installation?

You probably have another Numpy version installed on your system, try to query your numpy version and retrieve it if your distribution does not support it.
aka debian/unbuntu/Mint version can query mostly from dpkg package manger : dpkg --get-selections | egrep -i "numpy", you can see actual Numpy version.

  • Some having apt can either asking to removing it by doing this: apt-get remove numpy.

  • Some having distribution like Fedora, RedHat and any compatible release under RedHat model can use rpm as well to query the installation.

  • This is happening by telling to Numpy installer to install itself in current /usr/local/lib/python[VERSION]/dist-packages over Linux env and c:[...]\python[VERSION]\site-packages for windows. Having probably One version of Numpy installed in /usr/local/python[VERSION]/dist-packages, this one will be instantiated first.

  • .pth file hold information about path location of specific python module, but erasing a component from packages may corrupt it...

Be careful, and you will have to remove the package and all it's dependency... really painful in some case.

Visiting lunchad.net may save you time sometimes they had new versions from some packages.

Histogram using gnuplot?

yes, and its quick and simple though very hidden:

binwidth=5
bin(x,width)=width*floor(x/width)

plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes

check out help smooth freq to see why the above makes a histogram

to deal with ranges just set the xrange variable.

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

Edit a text file on the console using Powershell

Kinesics Text Editor.

It's super fast and handles large text files, though minimal in features. There's a GUI version and console version (k.exe) included. Should work the same on linux.

Example: In my test it took 7 seconds to open a 500mb disk image.

screenshot

jQuery select2 get value of select tag?

Above solutions did not work for me with latest select2 (4.0.13)

With jQuery you can use this solution to retrieve value according to documentation: https://select2.org/programmatic-control/retrieving-selections

$('#first').find(':selected').val();

What is the best algorithm for overriding GetHashCode?

Up until recently my answer would have been very close to Jon Skeet's here. However, I recently started a project which used power-of-two hash tables, that is hash tables where the size of the internal table is 8, 16, 32, etc. There's a good reason for favouring prime-number sizes, but there are some advantages to power-of-two sizes too.

And it pretty much sucked. So after a bit of experimentation and research I started re-hashing my hashes with the following:

public static int ReHash(int source)
{
  unchecked
  {
    ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;
    ulong d = 0xE2ADBEEFDEADBEEF ^ c;
    ulong a = d += c = c << 15 | c >> -15;
    ulong b = a += d = d << 52 | d >> -52;
    c ^= b += a = a << 26 | a >> -26;
    d ^= c += b = b << 51 | b >> -51;
    a ^= d += c = c << 28 | c >> -28;
    b ^= a += d = d << 9 | d >> -9;
    c ^= b += a = a << 47 | a >> -47;
    d ^= c += b << 54 | b >> -54;
    a ^= d += c << 32 | c >> 32;
    a += d << 25 | d >> -25;
    return (int)(a >> 1);
  }
}

And then my power-of-two hash table didn't suck any more.

This disturbed me though, because the above shouldn't work. Or more precisely, it shouldn't work unless the original GetHashCode() was poor in a very particular way.

Re-mixing a hashcode can't improve a great hashcode, because the only possible effect is that we introduce a few more collisions.

Re-mixing a hash code can't improve a terrible hash code, because the only possible effect is we change e.g. a large number of collisions on value 53 to a large number of value 18,3487,291.

Re-mixing a hash code can only improve a hash code that did at least fairly well in avoiding absolute collisions throughout its range (232 possible values) but badly at avoiding collisions when modulo'd down for actual use in a hash table. While the simpler modulo of a power-of-two table made this more apparent, it was also having a negative effect with the more common prime-number tables, that just wasn't as obvious (the extra work in rehashing would outweigh the benefit, but the benefit would still be there).

Edit: I was also using open-addressing, which would also have increased the sensitivity to collision, perhaps more so than the fact it was power-of-two.

And well, it was disturbing how much the string.GetHashCode() implementations in .NET (or study here) could be improved this way (on the order of tests running about 20-30 times faster due to fewer collisions) and more disturbing how much my own hash codes could be improved (much more than that).

All the GetHashCode() implementations I'd coded in the past, and indeed used as the basis of answers on this site, were much worse than I'd throught. Much of the time it was "good enough" for much of the uses, but I wanted something better.

So I put that project to one side (it was a pet project anyway) and started looking at how to produce a good, well-distributed hash code in .NET quickly.

In the end I settled on porting SpookyHash to .NET. Indeed the code above is a fast-path version of using SpookyHash to produce a 32-bit output from a 32-bit input.

Now, SpookyHash is not a nice quick to remember piece of code. My port of it is even less so because I hand-inlined a lot of it for better speed*. But that's what code reuse is for.

Then I put that project to one side, because just as the original project had produced the question of how to produce a better hash code, so that project produced the question of how to produce a better .NET memcpy.

Then I came back, and produced a lot of overloads to easily feed just about all of the native types (except decimal†) into a hash code.

It's fast, for which Bob Jenkins deserves most of the credit because his original code I ported from is faster still, especially on 64-bit machines which the algorithm is optimised for‡.

The full code can be seen at https://bitbucket.org/JonHanna/spookilysharp/src but consider that the code above is a simplified version of it.

However, since it's now already written, one can make use of it more easily:

public override int GetHashCode()
{
  var hash = new SpookyHash();
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

It also takes seed values, so if you need to deal with untrusted input and want to protect against Hash DoS attacks you can set a seed based on uptime or similar, and make the results unpredictable by attackers:

private static long hashSeed0 = Environment.TickCount;
private static long hashSeed1 = DateTime.Now.Ticks;
public override int GetHashCode()
{
  //produce different hashes ever time this application is restarted
  //but remain consistent in each run, so attackers have a harder time
  //DoSing the hash tables.
  var hash = new SpookyHash(hashSeed0, hashSeed1);
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

*A big surprise in this is that hand-inlining a rotation method that returned (x << n) | (x >> -n) improved things. I would have been sure that the jitter would have inlined that for me, but profiling showed otherwise.

decimal isn't native from the .NET perspective though it is from the C#. The problem with it is that its own GetHashCode() treats precision as significant while its own Equals() does not. Both are valid choices, but not mixed like that. In implementing your own version, you need to choose to do one, or the other, but I can't know which you'd want.

‡By way of comparison. If used on a string, the SpookyHash on 64 bits is considerably faster than string.GetHashCode() on 32 bits which is slightly faster than string.GetHashCode() on 64 bits, which is considerably faster than SpookyHash on 32 bits, though still fast enough to be a reasonable choice.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

Changing the tmp folder of mysql

This maybe helpful for MySql with AppArmor

stop mysql :

sudo /etc/init.d/mysql stop

Create directory called /somewhere/tmp

Edit Config:

sudo vim /etc/mysql/my.cnf # or perhaps sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

change

tmpdir = /somewhere/tmp/

Then

sudo vim /etc/apparmor.d/usr.sbin.mysqld

Add

# Allow data dir access
  /somewhere/ r,
  /somewhere/** rwk,

sudo chown -R root:root /somewhere

sudo chmod -R 1777 /somewhere

Restart

 sudo /etc/init.d/apparmor reload

 sudo /etc/init.d/mysql restart

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It is because of CASCADE TYPE

if you put

@OneToOne(cascade=CascadeType.ALL)

You can just save your object like this

user.setCountry(country);
session.save(user)

but if you put

 @OneToOne(cascade={    
            CascadeType.PERSIST,
            CascadeType.REFRESH,
            ...
})

You need to save your object like this

user.setCountry(country);
session.save(country)
session.save(user)

How to get rid of underline for Link component of React Router?

What worked for me is this:

<Link to="/" style={{boxShadow: "none"}}>

How to get current user who's accessing an ASP.NET application?

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

Adding rows dynamically with jQuery

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

TypeError: 'NoneType' object is not iterable in Python

It means the value of data is None.

java.io.IOException: Server returned HTTP response code: 500

This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.

i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled

How do I test if a recordSet is empty? isNull?

A simple way is to write it:

Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
   msgbox "There is no records" 
End if

SQL Error: ORA-01861: literal does not match format string 01861

If you provide proper date format it should work please recheck once if you have given correct date format in insert values

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

Create File If File Does Not Exist

You can simply call

using (StreamWriter w = File.AppendText("log.txt"))

It will create the file if it doesn't exist and open the file for appending.

Edit:

This is sufficient:

string path = txtFilePath.Text;               
using(StreamWriter sw = File.AppendText(path))
{
  foreach (var line in employeeList.Items)                 
  {                    
    Employee e = (Employee)line; // unbox once
    sw.WriteLine(e.FirstName);                     
    sw.WriteLine(e.LastName);                     
    sw.WriteLine(e.JobTitle); 
  }                
}     

But if you insist on checking first, you can do something like this, but I don't see the point.

string path = txtFilePath.Text;               


using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))                 
{                      
    foreach (var line in employeeList.Items)                     
    {                         
      sw.WriteLine(((Employee)line).FirstName);                         
      sw.WriteLine(((Employee)line).LastName);                         
      sw.WriteLine(((Employee)line).JobTitle);                     
    }                  
} 

Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList, then unbox the object once and use the reference.

However, I perfer to use List<> for my collections:

public class EmployeeList : List<Employee>

Not an enclosing class error Android Studio

startActivity(new Intent(this, Katra_home.class));

try this one it will be work

XMLHttpRequest status 0 (responseText is empty)

If the server responds to an OPTIONS method and to GET and POST (whichever of them you're using) with a header like:

Access-Control-Allow-Origin: *

It might work OK. Seems to in FireFox 3.5 and rekonq 0.4.0. Apparently, with that header and the initial response to OPTIONS, the server is saying to the browser, "Go ahead and let this cross-domain request go through."

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

How do I resolve a HTTP 414 "Request URI too long" error?

I got this error after using $.getJSON() from JQuery. I just changed to post:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

Stop Visual Studio from launching a new browser window when starting debug?

If you're using the Web Publish feature in IIS, then the solution I found was to edit the publish configuration and remove the Destination URL from the configuration (leave it blank).

If this is defined, then every time you publish the project it will open the URL specified in the Destination URL (which is a redirect URL).

Reference: https://support.winhost.com/kb/a1604/visual-studio-publish-web-deploy.aspx

How to globally replace a forward slash in a JavaScript string?

You need to wrap the forward slash to avoid cross browser issues or //commenting out.

str = 'this/that and/if';

var newstr = str.replace(/[/]/g, 'ForwardSlash');

How to place a JButton at a desired location in a JFrame using Java

First, remember your JPanel size height and size width, then observe: JButton coordinates is (xo, yo, x length , y length). If your window is 800x600, you just need to write:

JButton.setBounds(0, 500, 100, 100);

You just need to use a coordinate gap to represent the button, and know where the window ends and where the window begins.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Well, it'd still be convenient (syntactically) if we could declare usual values inside the if's condition. So, here's a trick: you can make the compiler think there is an assignment of Optional.some(T) to a value like so:

    if let i = "abc".firstIndex(of: "a"),
        let i_int = .some(i.utf16Offset(in: "abc")),
        i_int < 1 {
        // Code
    }

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

C++ Get name of type in template

I just leave it there. If someone will still need it, then you can use this:

template <class T>
bool isString(T* t) { return false;  } // normal case returns false

template <>
bool isString(char* t) { return true; }  // but for char* or String.c_str() returns true
.
.
.

This will only CHECK type not GET it and only for 1 type or 2.

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Same thing happened to me. Eventually my solution was to navigate to the repository using terminal (on mac) and create a new js file with a slightly different name. It linked immediately so i copied contents of original file to new one. You also might want to lose the first / after src= and use "".

How to remove new line characters from data rows in mysql?

update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));

Above is working for fine.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

How can I initialise a static Map?

I like using the static initializer "technique" when I have a concrete realization of an abstract class that has defined an initializing constructor but no default constructor but I want my subclass to have a default constructor.

For example:

public abstract class Shape {

    public static final String COLOR_KEY = "color_key";
    public static final String OPAQUE_KEY = "opaque_key";

    private final String color;
    private final Boolean opaque;

    /**
     * Initializing constructor - note no default constructor.
     *
     * @param properties a collection of Shape properties
     */
    public Shape(Map<String, Object> properties) {
        color = ((String) properties.getOrDefault(COLOR_KEY, "black"));
        opaque = (Boolean) properties.getOrDefault(OPAQUE_KEY, false);
    }

    /**
     * Color property accessor method.
     *
     * @return the color of this Shape
     */
    public String getColor() {
        return color;
    }

    /**
     * Opaque property accessor method.
     *
     * @return true if this Shape is opaque, false otherwise
     */
    public Boolean isOpaque() {
        return opaque;
    }
}

and my concrete realization of this class -- but it wants/needs a default constructor:

public class SquareShapeImpl extends Shape {

    private static final Map<String, Object> DEFAULT_PROPS = new HashMap<>();

    static {
        DEFAULT_PROPS.put(Shape.COLOR_KEY, "yellow");
        DEFAULT_PROPS.put(Shape.OPAQUE_KEY, false);
    }

    /**
     * Default constructor -- intializes this square to be a translucent yellow
     */
    public SquareShapeImpl() {
        // the static initializer was useful here because the call to 
        // this(...) must be the first statement in this constructor
        // i.e., we can't be mucking around and creating a map here
        this(DEFAULT_PROPS);
    }

    /**
     * Initializing constructor -- create a Square with the given
     * collection of properties.
     *
     * @param props a collection of properties for this SquareShapeImpl
     */
    public SquareShapeImpl(Map<String, Object> props) {
        super(props);
    }
}

then to use this default constructor, we simply do:

public class StaticInitDemo {

    public static void main(String[] args) {

        // create a translucent, yellow square...
        Shape defaultSquare = new SquareShapeImpl();

        // etc...
    }
}

Django - how to create a file and save it to a model's FileField?

Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.

Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).

Django 1.4.1

Python 2.7.3

#Model
class MonthEnd(models.Model):
    report = models.FileField(db_index=True, upload_to='not_used')

import csv
from os.path import join

#build and store the file
def write_csv():
    path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
    f = open(path, "w+b")

    #wipe the existing content
    f.truncate()

    csv_writer = csv.writer(f)
    csv_writer.writerow(('col1'))

    for num in range(3):
        csv_writer.writerow((num, ))

    month_end_file = MonthEnd()
    month_end_file.report.name = path
    month_end_file.save()

from my_app.models import MonthEnd

#serve it up as a download
def get_report(request):
    month_end = MonthEnd.objects.get(file_criteria=criteria)

    response = HttpResponse(month_end.report, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=report.csv'

    return response

Recommendations of Python REST (web services) framework?

We're using Django for RESTful web services.

Note that -- out of the box -- Django did not have fine-grained enough authentication for our needs. We used the Django-REST interface, which helped a lot. [We've since rolled our own because we'd made so many extensions that it had become a maintenance nightmare.]

We have two kinds of URL's: "html" URL's which implement the human-oriented HTML pages, and "json" URL's which implement the web-services oriented processing. Our view functions often look like this.

def someUsefulThing( request, object_id ):
    # do some processing
    return { a dictionary with results }

def htmlView( request, object_id ):
    d = someUsefulThing( request, object_id )
    render_to_response( 'template.html', d, ... )

def jsonView( request, object_id ):
    d = someUsefulThing( request, object_id )
    data = serializers.serialize( 'json', d['object'], fields=EXPOSED_FIELDS )
    response = HttpResponse( data, status=200, content_type='application/json' )
    response['Location']= reverse( 'some.path.to.this.view', kwargs={...} )
    return response

The point being that the useful functionality is factored out of the two presentations. The JSON presentation is usually just one object that was requested. The HTML presentation often includes all kinds of navigation aids and other contextual clues that help people be productive.

The jsonView functions are all very similar, which can be a bit annoying. But it's Python, so make them part of a callable class or write decorators if it helps.

What is the newline character in the C language: \r or \n?

What is the newline character in the C language: \r or \n?

The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

  1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

  2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

  3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
    Note: File I/O in binary mode makes no translation.

The '\r' in source code is the carriage return char.

(*1) A lone 13 and/or 10 may also translate into \n.

Programmatically obtain the phone number of the Android phone

There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

Why do I need to do `--set-upstream` all the time?

For those looking for an alias that works with git pull, this is what I use:

alias up="git branch | awk '/^\\* / { print \$2 }' | xargs -I {} git branch --set-upstream-to=origin/{} {}"

Now whenever you get:

$ git pull
There is no tracking information for the current branch.
...

Just run:

$ up
Branch my_branch set up to track remote branch my_branch from origin.
$ git pull

And you're good to go

Text file in VBA: Open/Find Replace/SaveAs/Close File

Why involve Notepad?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "THIS", "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub

Can I change the name of `nohup.out`?

Above methods will remove your output file data whenever you run above nohup command.

To Append output in user defined file you can use >> in nohup command.

nohup your_command >> filename.out &

This command will append all output in your file without removing old data.

Can regular JavaScript be mixed with jQuery?

Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.

In this case you can just put the code in a document.ready handler, like this:

$(function() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect (10, 10, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
  }
});

How to delete an object by id with entity framework

Raw sql query is fastest way I suppose

public void DeleteCustomer(int id)
{
   using (var context = new Context())
   {
      const string query = "DELETE FROM [dbo].[Customers] WHERE [id]={0}";
      var rows = context.Database.ExecuteSqlCommand(query,id);
      // rows >= 1 - count of deleted rows,
      // rows = 0 - nothing to delete.
   }
}

How to access the contents of a vector from a pointer to the vector in C++?

There are a lot of solutions. For example you can use at() method.

*I assumed that you a looking for equivalent to [] operator.