Programs & Examples On #Oracle aq

Oracle Advanced Queuing (OracleAQ) provides database-integrated message queuing functionality.

Best way to check if a Data Table has a null value in it

DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
    if (dr["Column_Name"] == DBNull.Value)
    {
        //Do something
    }
    else
    {
        //Do something
    }
}

window.print() not working in IE

Just to add some additional information. In IE 11, using merely

window.open() 

causes

window.document

to be undefined. To resolve this, use

window.open( null, '_blank' )

This will also work correctly in Chrome, Firefox and Safari.

I don't have enough reputation to comment, so had to create an answer.

.NET 4.0 has a new GAC, why?

It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.

My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.

Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.

How to convert an array to a string in PHP?

Using implode(), you can turn the array into a string.

$str = implode(',', $array); // 33160,33280,33180,...

How to identify numpy types in python?

The solution I've come up with is:

isinstance(y, (np.ndarray, np.generic) )

However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray or np.generic, and this probably isn't version robust.

How to plot a histogram using Matplotlib in Python with a list of data?

This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint function to generate the correct number of values within the range of each bin for the hist function to graph, for example:

import numpy as np
import matplotlib.pyplot as plt

data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])

as for labels you can align x ticks with bins to get something like this:

#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])

HashMaps and Null values?

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

Map<String, String> codes = new HashMap<String, String>();

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

Map<String, String> codes = new HashMap<String, String>();

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How to fix C++ error: expected unqualified-id

There should be no semicolon here:

class WordGame;

...but there should be one at the end of your class definition:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

Numpy: find index of the elements within range

Wanted to add numexpr into the mix:

import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)

Would only make sense for larger arrays with millions... or if you hitting a memory limits.

psql: server closed the connection unexepectedly

Solved by setting a password for the user first.

In terminal

sudo -u <username> psql

ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE

\q

In pgAdmin

**Connection**

Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX

Java ElasticSearch None of the configured nodes are available

You should check logs If you see like below "stacktrace": ["java.lang.IllegalStateException: Received message from unsupported version: [6.4.3] minimal compatible version is: [6.8.0]"

You can check this link https://discuss.elastic.co/t/java-client-or-spring-boot-for-elasticsearch-7-3-1/199778 You have to explicit declare es version.

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

How to plot two histograms together in R?

Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.

generate the data

carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)

You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.

## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
     main = 'Distribution of carrots and cucumbers', 
     panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = c(carrotCol, cukeCol), bty = 'n',
       border = NA)

enter image description here

Object of class stdClass could not be converted to string

Most likely, the userdata() function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Exporting results of a Mysql query to excel?

Good Example can be when incase of writing it after the end of your query if you have joins or where close :

 select 'idPago','fecha','lead','idAlumno','idTipoPago','idGpo'
 union all
(select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_Gpo,id_Taller,
id_docente, Pagoimporte, NoFactura, FacturaImporte, Mensualidad_No, FormaPago,
Observaciones from control_pagos
into outfile 'c:\\data.csv' 
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n');

Android appcompat v7:23

Original answer:

I too tried to change the support library to "23". When I changed the targetSdkVersion to 23, Android Studio reported the following error:

This support library should not use a lower version (22) than the targetSdkVersion (23)

I simply changed:

compile 'com.android.support:appcompat-v7:23.0.0'

to

compile 'com.android.support:appcompat-v7:+'

Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1.


Pro tip:

You can use double quotes and create a ${supportLibVersion} variable for simplicity. Example:

ext {
    supportLibVersion = '23.1.1'
}

compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"

source: https://twitter.com/manidesto/status/669195097947377664

How does #include <bits/stdc++.h> work in C++?

It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.

Se e.g. GCC 4.8.0 /bits/stdc++.h source.

Using it would include a lot of unnecessary stuff and increases compilation time.

Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)

I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

keyCode values for numeric keypad?

You can simply run

$(document).keyup(function(e) {
    console.log(e.keyCode);
});

to see the codes of pressed keys in the browser console.

Or you can find key codes here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Numpad_keys

How to edit data in result grid in SQL Server Management Studio

  1. To be clear: The option "Value for Edit Top Rows command" has nothing to do with the fact if a result set is editable or not. It is just a way to limit the result set.

  2. Editing the result set of a query based on one and only one table is obviously always possible.

  3. The result set of a query based on more than one table is under following condition possible: You can edit the fields in the result set at once if they belong to one and only one based table in the query! If the fields are Primary Key, then you have to fulfill refresh/"Execute SQL" (Ctrl+R) after each row update, in order to be able to edit a row next time. If the fields are not Primary Key, then you do not need to fulfill refresh/"Execute SQL" (Ctrl+R).

I have tested it on SQL Server 2008 - 2016!

Fill an array with random numbers

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

  • Think about a construct that can help you iterate over the array. Is there some sort of construct (a loop perhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill() to the current location of the array.

Note: Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

Converting time stamps in excel to dates

i got result from this in LibreOffice Calc :

=DATE(1970,1,1)+Column_id_here/60/60/24

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

How to obtain Certificate Signing Request

Follow these steps to create CSR (Code Signing Identity):

  1. On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'

    enter image description here

  2. Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?

    enter image description here

  3. Fill out the information in the Certificate Information window as specified below and click "Continue."
    • In the User Email Address field, enter the email address to identify with this certificate
    • In the Common Name field, enter your name
    • In the Request group, click the "Saved to disk" option ?

    enter image description here

  4. Save the file to your hard drive.

    enter image description here


Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

How to use particular CSS styles based on screen size / device

Why not use @media-queries? These are designed for that exact purpose. You can also do this with jQuery, but that's a last resort in my book.

var s = document.createElement("script");

//Check if viewport is smaller than 768 pixels
if(window.innerWidth < 768) {
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css1";
}else { //Else we have a larger screen
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css2";
}

$(function(){
    $("head").append(s); //Inject stylesheet
})

Target WSGI script cannot be loaded as Python module

Sometimes when I get stuck on this I hard code a path to project in the wsgi file like:

import os
import sys


sys.path.append("/var/www/html/myproject")
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

application = get_wsgi_application()

Make a phone call programmatically

Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://

Your code should look like this:

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Converting XML to JSON using Python?

While the built-in libs for XML parsing are quite good I am partial to lxml.

But for parsing RSS feeds, I'd recommend Universal Feed Parser, which can also parse Atom. Its main advantage is that it can digest even most malformed feeds.

Python 2.6 already includes a JSON parser, but a newer version with improved speed is available as simplejson.

With these tools building your app shouldn't be that difficult.

Convert Java Date to UTC String

The following simplified code, based on the accepted answer above, worked for me:

public class GetSync {
    public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
    private static final TimeZone utc = TimeZone.getTimeZone("UTC");
    private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
    static {
        isoFormatter.setTimeZone(utc);
    }

    public static String now() {
        return isoFormatter.format(new Date()).toString();
    }
}

I hope this helps somebody.

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

Active Menu Highlight CSS

First, give all your links a unique id and make a css class called active:

<ul>
    <li><a id="link1" href="#/...">link 1</a></li>
    <li><a id="link2" href="#/...">link 2</a></li>
</ul>

CSS:

.active {
    font-weight: bold;
}

Jquery version:

function setActiveLink(setActive){
    if ($("a").hasClass('active'))
        $("a").removeClass('active');
    if (setActive)
        $("#"+setActive).addClass('active');
}

$(function() {
    $("a").click(function() {
        setActiveLink(this.id);
    });
});

Vanilla javascript version:

In order to prevent selecting too many links with document.querySelectorAll, give the parent element an id called menuLinks. Add an onClick handler on the links.

<ul id="menuLinks">
    <li><a id="link1" href="#/..." onClick="setActiveLink(this.id);">link 1</a></li>
    <li><a id="link2" href="#/..." onClick="setActiveLink(this.id);">link 2</a></li>
</ul>

Code:

function setActiveLink(setActive){
    var links = document.querySelectorAll("#menuLinks a");
    Array.prototype.map.call(links, function(e) {
        e.className = "";
        if (e.id == setActive)
            e.className = "active";
    })
}

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

Spark - repartition() vs coalesce()

I would like to add to Justin and Power's answer that -

repartition will ignore existing partitions and create new ones. So you can use it to fix data skew. You can mention partition keys to define the distribution. Data skew is one of the biggest problems in the 'big data' problem space.

coalesce will work with existing partitions and shuffle a subset of them. It can't fix the data skew as much as repartition does. Therefore even if it is less expensive it might not be the thing you need.

Download history stock prices automatically from yahoo finance in python

There is already a library in Python called yahoo_finance so you'll need to download the library first using the following command line:

sudo pip install yahoo_finance

Then once you've installed the yahoo_finance library, here's a sample code that will download the data you need from Yahoo Finance:

#!/usr/bin/python
import yahoo_finance
import pandas as pd

symbol = yahoo_finance.Share("GOOG")
google_data = symbol.get_historical("1999-01-01", "2016-06-30")
google_df = pd.DataFrame(google_data)

# Output data into CSV
google_df.to_csv("/home/username/google_stock_data.csv")

This should do it. Let me know if it works.

UPDATE: The yahoo_finance library is no longer supported.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.

Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository". I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.

After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.

1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear

2) Followed github's instructions here to generate a new key pair and upload the public key to git

3) using git bash- heroku keys:add to upload the same key to heroku.

Now git push heroku master works.

what a nightmare, hope this helped somebody.

Bryan

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

Is it possible to write data to file using only JavaScript?

Try

_x000D_
_x000D_
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
_x000D_
_x000D_
_x000D_

If you want to download binary data look here

Update

2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

How to change the port number for Asp.Net core app?

In visual studio 2017 we can change the port number from LaunchSetting.json

In Properties-> LaunchSettings.json.

Open LaunchSettings.json and change the Port Number.

Launch

Change the port Number in json file

enter image description here

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How do I find the PublicKeyToken for a particular dll?

I use Windows Explorer, navigate to C:\Windows\assembly , find the one I need. From the Properties you can copy the PublicKeyToken.

This doesn't rely on Visual Studio or any other utilities being installed.

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Final Solution for this problem is below :

  1. First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"

  2. In your database connection string add below attribute : Integrated Security = SSPI

How to use SVN, Branch? Tag? Trunk?

I asked myself the same questions when we came to implement Subversion here -- about 20 developers spread across 4 - 6 projects. I didn't find any one good source with ''the answer''. Here are some parts of how our answer has developed over the last 3 years:

-- commit as often as is useful; our rule of thumb is commit whenever you have done sufficient work that it would be a problem having to re-do it if the modifications got lost; sometimes I commit every 15 minutes or so, other times it might be days (yes, sometimes it takes me a day to write 1 line of code)

-- we use branches, as one of your earlier answers suggested, for different development paths; right now for one of our programs we have 3 active branches: 1 for the main development, 1 for the as-yet-unfinished effort to parallelise the program, and 1 for the effort to revise it to use XML input and output files;

-- we scarcely use tags, though we think we ought to use them to identify releases to production;

Think of development proceeding along a single path. At some time or state of development marketing decide to release the first version of the product, so you plant a flag in the path labelled '1' (or '1.0' or what have you). At some other time some bright spark decides to parallelise the program, but decides that that will take weeks and that people want to keep going down the main path in the meantime. So you build a fork in the path and different people wander off down the different forks.

The flags in the road are called 'tags' ,and the forks in the road are where 'branches' divide. Occasionally, also, branches come back together.

-- we put all material necessary to build an executable (or system) into the repository; That means at least source code and make file (or project files for Visual Studio). But when we have icons and config files and all that other stuff, that goes into the repository. Some documentation finds its way into the repo; certainly any documentation such as help files which might be integral to the program does, and it's a useful place to put developer documentation.

We even put Windows executables for our production releases in there, to provide a single location for people looking for software -- our Linux releases go to a server so don't need to be stored.

-- we don't require that the repository at all times be capable of delivering a latest version which builds and executes; some projects work that way, some don't; the decision rests with the project manager and depends on many factors but I think it breaks down when making major changes to a program.

Autowiring fails: Not an managed Type

If anyone is strugling with the same problem I solved it by adding @EntityScan in my main class. Just add your model package to the basePackages property.

Set UILabel line spacing

This guy created a class to get line-height (without using CoreText, as MTLabel library) : https://github.com/LemonCake/MSLabel

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

Find a value anywhere in a database

You might need to build an inverted index for your database. It is assured to be pretty fast.

How to use a App.config file in WPF applications?

You can change configuration file schema back to DotNetConfig.xsd via properties of the app.config file. To find destination of needed schema, you can search it by name or create a WinForms application, add to project the configuration file and in it's properties, you'll find full path to file.

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

Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.

The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Datetime BETWEEN statement not working in SQL Server

You don't have any error in either of your queries. My guess is the following:

  • No records exists between 2013-10-17' and '2013-10-18'
  • the records the second query returns you exist after '2013-10-18'

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

Error installing mysql2: Failed to build gem native extension

This solved my problem once in Windows:

subst X: "C:\Program files\MySQL\MySQL Server 5.5" 
gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt 
subst X: /D

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

This one seems to imply that 030 and 031 are up and down triangles.

(As bobince pointed out, this doesn't seem to be an ASCII standard)

S3 - Access-Control-Allow-Origin Header

S3 now expects the rules to be in Array Json format.

You can find this in s3 bucket -> Permissions then -> scroll below -> () Cross-origin resource sharing (CORS)

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

How to ignore deprecation warnings in Python

When you want to ignore warnings only in functions you can do the following.

import warnings
from functools import wraps


def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...

Just add the @ignore_warnings decorator on the function you want to ignore all warnings

What is a NullPointerException, and how do I fix it?

Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.

String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.

All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.

You must initialize the elements in the array before accessing or dereferencing them.

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

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

Exec can be messy on windows. There is a more "nodie" solution. Fundamentally, you have a recursive call to see if a directory exists and dive into the child (if it does exist) or create it. Here is a function that will create the children and call a function when finished:

fs = require('fs');
makedirs = function(path, func) {
 var pth = path.replace(/['\\]+/g, '/');
 var els = pth.split('/');
 var all = "";
 (function insertOne() {
   var el = els.splice(0, 1)[0];
   if (!fs.existsSync(all + el)) {
    fs.mkdirSync(all + el);
   }
   all += el + "/";
   if (els.length == 0) {
    func();
   } else {
     insertOne();
   }
   })();

}

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

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

Maybe you can try this

var str = "'SELECT___100E___7',24";
    var res = str.split(',').pop();

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Get refresh token google api

If I may expand on user987361's answer:

From the offline access portion of the OAuth2.0 docs:

When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.

So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in the query string of the consent page.

As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.

Cheers,

PS This change was announced in a blog post as well.

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

How to count number of files in each directory?

Slightly modified version of Sebastian's answer using find instead of du (to exclude file-size-related overhead that du has to perform and that is never used):

 find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr

-mindepth 2 parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:

  234 dir1
  123 dir2
    1 file1
    1 file2
    1 file3
      ...
    1 fileN

(much like the du-based variant does)

If you do need to count the files in current directory as well, use this enhanced version:

{ find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr

The output will be like the following:

  234 dir1
  123 dir2
   42 .

error: This is probably not a problem with npm. There is likely additional logging output above

Deleting the package-lock.json did it for me. I'd suggest you not push package-lock.json to your repo as I wasted hours trying to npm install with the package-lock.json in the folder which gave me helluva errors.

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

What is the most efficient/quickest way to loop through rows in VBA (excel)?

For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,


once with for each Dkey in dDict,


and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)

=>You will notice a huge difference, even though you are going through the same construct.

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

How to check if command line tools is installed

Yosemite

Below are a few extra steps on a fresh Mac that some people might need. This adds a little to @jnovack's excellent answer.

Update: A few other notes when setting this up:

Make sure your admin user has a password. A blank password won't work when trying to enable a root user.

System Preferences > Users and Groups > (select user) > Change password

Then to enable root, run dsenableroot in a terminal:

$ dsenableroot
username = mac_admin_user
user password:
root password:
verify root password:

dsenableroot:: ***Successfully enabled root user.

Type in the admin user's password, then the new enabled root password twice.

Next type:

sudo gcc

or

sudo make

It will respond with something like the following:

WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.

To proceed, enter your password, or type Ctrl-C to abort.

Password:


You have not agreed to the Xcode license agreements. You must agree to 
both license agreements below in order to use Xcode.

Press enter when it prompts to show you the license agreement.

Hit the Enter key to view the license agreements at 
'/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'

IMPORTANT: BY USING THIS SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE 
FOLLOWING APPLE TERMS:

//...

Press q to exit the license agreement view.

By typing 'agree' you are agreeing to the terms of the software license 
agreements. Type 'print' to print them or anything else to cancel, 
[agree, print, cancel]

Type agree. And then it will end with:

clang: error: no input files 

Which basically means that you didn't give make or gcc any input files.

Here is what the check looked like:

$ xcode-select -p
/Applications/Xcode.app/Contents/Developer

Mavericks

With Mavericks, it is a little different now.

When the tools were NOT found, this is what the command pkgutil command returned:

$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

To install the command line tools, this works nicely from the Terminal, with a nice gui and everything.

$ xcode-select --install

http://macops.ca/installing-command-line-tools-automatically-on-mavericks/

When they were found, this is what the pkgutil command returned:

$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
package-id: com.apple.pkg.CLTools_Executables
version: 5.0.1.0.1.1382131676
volume: /
location: /
install-time: 1384149984
groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group 

This command returned the same before and after the install.

$ pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

Also I had the component for the CLT selected and installed in xcode's downloads section before, but it seems like it didn't make it to the terminal...

Hope that helps.

How do I find duplicates across multiple columns?

Given a staging table with 70 columns and only 4 representing duplicates, this code will return the offending columns:

SELECT 
    COUNT(*)
    ,LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
FROM Staging.dbo.Stage S
GROUP BY 
    LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
HAVING COUNT(*) > 1

.

adding 1 day to a DATETIME format value

You can use

$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');

How do I increase modal width in Angular UI Bootstrap?

I use a css class like so to target the modal-dialog class:

.app-modal-window .modal-dialog {
  width: 500px;
}

Then in the controller calling the modal window, set the windowClass:

    $scope.modalButtonClick = function () {
        var modalInstance = $modal.open({
            templateUrl: 'App/Views/modalView.html',
            controller: 'modalController',
            windowClass: 'app-modal-window'
        });
        modalInstance.result.then(
            //close
            function (result) {
                var a = result;
            },
            //dismiss
            function (result) {
                var a = result;
            });
    };

How to set a reminder in Android?

Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.

You've got a couple of choices;

  1. Calling the intent to add an event on the calendar
    This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", false);
    intent.putExtra("rrule", "FREQ=DAILY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    startActivity(intent);
    

    Or the more complicated one:

  2. Get a reference to the calendar with this method
    (It is highly recommended not to use this method, because it could break on newer Android versions):

    private String getCalendarUriBase(Activity act) {
    
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = act.managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
        }
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = act.managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
            }
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
        }
        return calendarUriBase;
    }
    

    and add an event and a reminder this way:

    // get calendar
    Calendar cal = Calendar.getInstance();     
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
    ContentResolver cr = getContentResolver();
    
    // event insert
    ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", "Reminder Title");
    values.put("allDay", 0);
    values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
    values.put("description", "Reminder description");
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    Uri event = cr.insert(EVENTS_URI, values);
    
    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
    values.put( "method", 1 );
    values.put( "minutes", 10 );
    cr.insert( REMINDERS_URI, values );
    

    You'll also need to add these permissions to your manifest for this method:

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

Update: ICS Issues

The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.

More infos about this can be found at this blog post.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

How do I implement __getattribute__ without an infinite recursion error?

Are you sure you want to use __getattribute__? What are you actually trying to achieve?

The easiest way to do what you ask is:

class D(object):
    def __init__(self):
        self.test = 20
        self.test2 = 21

    test = 0

or:

class D(object):
    def __init__(self):
        self.test = 20
        self.test2 = 21

    @property
    def test(self):
        return 0

Edit: Note that an instance of D would have different values of test in each case. In the first case d.test would be 20, in the second it would be 0. I'll leave it to you to work out why.

Edit2: Greg pointed out that example 2 will fail because the property is read only and the __init__ method tried to set it to 20. A more complete example for that would be:

class D(object):
    def __init__(self):
        self.test = 20
        self.test2 = 21

    _test = 0

    def get_test(self):
        return self._test

    def set_test(self, value):
        self._test = value

    test = property(get_test, set_test)

Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.

How do I get the type of a variable?

I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.

It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:

Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.

Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.

switch ((typeid(T)) {
  case typeid(myClassA):
    // handle that case
    break;
  case typeid(myClassB):
    // handle that case
    break;
  case typeid(uint32_t):
    // handle that case
    break;
  default:
    // handle that case
}

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Check file size before upload

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Simple timeout in java

    @Singleton
    @AccessTimeout(value=120000)
    public class StatusSingletonBean {
      private String status;
    
      @Lock(LockType.WRITE)
      public void setStatus(String new Status) {
        status = newStatus;
      }
      @Lock(LockType.WRITE)
      @AccessTimeout(value=360000)
      public void doTediousOperation {
        //...
      }
    }
    //The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
    @Singleton
    @AccessTimeout(value=60, timeUnit=SECONDS) 
    public class StatusSingletonBean { 
    //... 
    }  
    //The Java EE 6 Tutorial

//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

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

If you uninstalled then re-installed, and running 'python' in CLI, make sure to open a new CMD after your installation for 'python' to be recognized. 'py' will probably be recognized with an old CLI because its not tied to any version.

Change content of div - jQuery

Try this to Change content of div using jQuery.

See more @ Change content of div using jQuery

$(document).ready(function(){
    $("#Textarea").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();

        // Setting the Div content
        $(".output").text(currentText);
    });
});

Picking a random element from a set

Unfortunately, this cannot be done efficiently (better than O(n)) in any of the Standard Library set containers.

This is odd, since it is very easy to add a randomized pick function to hash sets as well as binary sets. In a not to sparse hash set, you can try random entries, until you get a hit. For a binary tree, you can choose randomly between the left or right subtree, with a maximum of O(log2) steps. I've implemented a demo of the later below:

import random

class Node:
    def __init__(self, object):
        self.object = object
        self.value = hash(object)
        self.size = 1
        self.a = self.b = None

class RandomSet:
    def __init__(self):
        self.top = None

    def add(self, object):
        """ Add any hashable object to the set.
            Notice: In this simple implementation you shouldn't add two
                    identical items. """
        new = Node(object)
        if not self.top: self.top = new
        else: self._recursiveAdd(self.top, new)
    def _recursiveAdd(self, top, new):
        top.size += 1
        if new.value < top.value:
            if not top.a: top.a = new
            else: self._recursiveAdd(top.a, new)
        else:
            if not top.b: top.b = new
            else: self._recursiveAdd(top.b, new)

    def pickRandom(self):
        """ Pick a random item in O(log2) time.
            Does a maximum of O(log2) calls to random as well. """
        return self._recursivePickRandom(self.top)
    def _recursivePickRandom(self, top):
        r = random.randrange(top.size)
        if r == 0: return top.object
        elif top.a and r <= top.a.size: return self._recursivePickRandom(top.a)
        return self._recursivePickRandom(top.b)

if __name__ == '__main__':
    s = RandomSet()
    for i in [5,3,7,1,4,6,9,2,8,0]:
        s.add(i)

    dists = [0]*10
    for i in xrange(10000):
        dists[s.pickRandom()] += 1
    print dists

I got [995, 975, 971, 995, 1057, 1004, 966, 1052, 984, 1001] as output, so the distribution seams good.

I've struggled with the same problem for myself, and I haven't yet decided weather the performance gain of this more efficient pick is worth the overhead of using a python based collection. I could of course refine it and translate it to C, but that is too much work for me today :)

MySQL JOIN the most recent row only?

If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.

SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
   cch.cchid = (
      SELECT MAX(cchid)
      FROM client_calling_history
      WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
   )

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Parsing GET request parameters in a URL that contains another URL

The correct php way is to use parse_url()

http://php.net/manual/en/function.parse-url.php

(from php manual)

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Polymorphism vs Overriding vs Overloading

import java.io.IOException;

class Super {

    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName() + " - I'm parent");
        return null;
    }

}

class SubOne extends Super {

    @Override
    protected Super getClassName(Super s)  {
        System.out.println(this.getClass().getSimpleName() + " - I'm Perfect Overriding");
        return null;
    }

}

class SubTwo extends Super {

    @Override
    protected Super getClassName(Super s) throws NullPointerException {
        System.out.println(this.getClass().getSimpleName() + " - I'm Overriding and Throwing Runtime Exception");
        return null;
    }

}

class SubThree extends Super {

    @Override
    protected SubThree getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Returning SubClass Type");
        return null;
    }

}

class SubFour extends Super {

    @Override
    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Throwing Narrower Exception ");
        return null;
    }

}

class SubFive extends Super {

    @Override
    public Super getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and have broader Access ");
        return null;
    }

}

class SubSix extends Super {

    public Super getClassName(Super s, String ol) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading ");
        return null;
    }

}

class SubSeven extends Super {

    public Super getClassName(SubSeven s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading because Method signature (Argument) changed.");
        return null;
    }

}

public class Test{

    public static void main(String[] args) throws Exception {

        System.out.println("Overriding\n");

        Super s1 = new SubOne(); s1.getClassName(null);

        Super s2 = new SubTwo(); s2.getClassName(null);

        Super s3 = new SubThree(); s3.getClassName(null);

        Super s4 = new SubFour(); s4.getClassName(null);

        Super s5 = new SubFive(); s5.getClassName(null);

        System.out.println("Overloading\n");

        SubSix s6 = new SubSix(); s6.getClassName(null, null);

        s6 = new SubSix(); s6.getClassName(null);

        SubSeven s7 = new SubSeven(); s7.getClassName(s7);

        s7 = new SubSeven(); s7.getClassName(new Super());

    }
}

Service vs IntentService in the Android platform

The Major Difference between a Service and an IntentService is described as follows:

Service :

1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.

2.Allows Multiple requests at a time.(Multi Threading)

IntentService :

1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.

2.But it allows only one request at a time.

Git credential helper - update password

For Windows 10 it is:

Control Panel > User Accounts > Manage your Credentials > Windows Credentials, search for the git credentials and edit

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

Can my enums have friendly names?

I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name.

Here's my suggestion:

Use an enum type pattern. Although it takes some effort to implement, it is really worth it.

public class MyEnum
{  
    public static readonly MyEnum Enum1=new MyEnum("This will work",1);
    public static readonly MyEnum Enum2=new MyEnum("This.will.work.either",2);
    public static readonly MyEnum[] All=new []{Enum1,Enum2};
    private MyEnum(string name,int value)
    {
        Name=name;
        Value=value;
    }

    public string Name{get;set;}
    public int Value{get;set;}

    public override string ToString()
    {
        return Name;    
    }
}

Listing only directories using ls in Bash?

file * | grep directory

Output (on my machine) --

[root@rhel6 ~]# file * | grep directory
mongo-example-master:    directory
nostarch:                directory
scriptzz:                directory
splunk:                  directory
testdir:                 directory

The above output can be refined more by using cut:

file * | grep directory | cut -d':' -f1
mongo-example-master
nostarch
scriptzz
splunk
testdir

* could be replaced with any path that's permitted
 file - determine file type
 grep - searches for string named directory
 -d - to specify a field delimiter
 -f1 - denotes field 1

Convert array values from string to int?

<?php
    
$string = "1,2,3";
$ids = explode(',', $string );

array_walk( $ids, function ( &$id )
{
    $id = (int) $id;
});
var_dump( $ids );

HAProxy redirecting http to https (ssl)

Can be done like this -

  frontend http-in
   bind *:80
   mode http
   redirect scheme https code 301

Any traffic hitting http will redirect to https

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.

>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>

You can find more information in PEP 3141.

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

How to delete an item in a list if it exists?

Eek, don't do anything that complicated : )

Just filter() your tags. bool() returns False for empty strings, so instead of

new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

you should write

new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))

or better yet, put this logic inside striplist() so that it doesn't return empty strings in the first place.

Describe table structure

For SQL Server use exec sp_help

USE db_name;
exec sp_help 'dbo.table_name'

For MySQL, use describe

DESCRIBE table_name;

Are PDO prepared statements sufficient to prevent SQL injection?

Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).

Parameterised queries work by sending the code and the data separately, so it would never be possible to find a hole in that.

You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

How to read a text file in project's root directory?

You have to use absolute path in this case. But if you set the CopyToOutputDirectory = CopyAlways, it will work as you are doing it.

How to name and retrieve a stash by name in git?

in my fish shell

function gsap
  git stash list | grep ": $argv" | tr -dc '0-9' | xargs git stash apply
end

use

gsap name_of_stash

ASP.NET strange compilation error

I resolved this by deleting the contents of the bin and obj folders for the project, and the contents of the bin folder on the remote server, then redeploying.

How to add leading zeros?

Here's a generalizable base R function:

pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){

    unlist(lapply(x, function(x) {
        paste0(
            paste(rep(char, len - nchar(x)), collapse = ''),
            x
        )
    }))
}

pad_left(1:100)

I like sprintf but it comes with caveats like:

however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

Custom alert and confirm box in jquery

I made custom messagebox using jquery UI component. Here is demo http://jsfiddle.net/eraj2587/Pm5Fr/14/

You have to pass just the parameters like caption name, message, button's text. You can specify trigger function on any button click. This will helpful for you.

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

How to correctly implement custom iterators and const_iterators?

  • Choose type of iterator which fits your container: input, output, forward etc.
  • Use base iterator classes from standard library. For example, std::iterator with random_access_iterator_tag.These base classes define all type definitions required by STL and do other work.
  • To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:

    // iterator class is parametrized by pointer type
    template <typename PointerType> class MyIterator {
        // iterator class definition goes here
    };
    
    typedef MyIterator<int*> iterator_type;
    typedef MyIterator<const int*> const_iterator_type;
    

    Notice iterator_type and const_iterator_type type definitions: they are types for your non-const and const iterators.

See Also: standard library reference

EDIT: std::iterator is deprecated since C++17. See a relating discussion here.

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

jQuery on window resize

Move your javascript into a function and then bind that function to window resize.

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

Changing directory in Google colab (breaking out of the python interpreter)

Use os.chdir. Here's a full example: https://colab.research.google.com/notebook#fileId=1CSPBdmY0TxU038aKscL8YJ3ELgCiGGju

Compactly:

!mkdir abc
!echo "file" > abc/123.txt

import os
os.chdir('abc')

# Now the directory 'abc' is the current working directory.
# and will show 123.txt.
!ls

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

Download a file from NodeJS Server using Express

Here's how I do it:

  1. create file
  2. send file to client
  3. remove file

Code:

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

let myController = (req, res) => {
  let filename = 'myFile.ext';
  let absPath = path.join(__dirname, '/my_files/', filename);
  let relPath = path.join('./my_files', filename); // path relative to server root

  fs.writeFile(relPath, 'File content', (err) => {
    if (err) {
      console.log(err);
    }
    res.download(absPath, (err) => {
      if (err) {
        console.log(err);
      }
      fs.unlink(relPath, (err) => {
        if (err) {
          console.log(err);
        }
        console.log('FILE [' + filename + '] REMOVED!');
      });
    });
  });
};

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

CHECK YOUR PROJECT PATH. It should have no irregular character like comma and space

for example this is incorrect path: d:\my applications\Project1

and this is true path d:\my_applications\Project1

The visual studio cannot build the project when there is a non alphabetic and numeric character in its path in disk and it show no message for this fault!

Also some installation tools have same problem when they start installation and can not be extracted.

href overrides ng-click in Angular.js

This worked for me in IE 9 and AngularJS v1.0.7:

<a href="javascript:void(0)" ng-click="logout()">Logout</a>

Thanks to duckeggs' comment for the working solution!

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

how to convert string into time format and add two hours

This example is a Sum for Date time and Time Zone(String Values)

String DateVal = "2015-03-26 12:00:00";
String TimeVal = "02:00:00";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

Date reslt = sdf.parse( DateVal );
Date timeZ = sdf2.parse( TimeVal );
//Increase Date Time
reslt.setHours( reslt.getHours() + timeZ.getHours());
reslt.setMinutes( reslt.getMinutes() + timeZ.getMinutes());
reslt.setSeconds( reslt.getSeconds() + timeZ.getSeconds());

System.printLn.out( sdf.format(reslt) );//Result(+2 Hours):  2015-03-26 14:00:00 

Thanks :)

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

How to copy files across computers using SSH and MAC OS X Terminal

You may also want to look at rsync if you're doing a lot of files.

If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion

Unable to Resolve Module in React Native App

It looks like your error is coming from the outer index.js file, not this one. Are you importing this one as './app/containers'? because it should just be './containers'.

How do I prevent CSS inheritance?

Short answer is: No, it's not possible to prevent CSS inheritance. You can only override the styles that are set on the parents. See the spec:

Every element in an HTML document will inherit all inheritable properties from its parent except the root element (html), which doesn’t have a parent. -W3C

Apart from overriding every single inherited property. You can also use initial keyword, e.g. color: initial;. It also can be used together with all, e.g. all: initial;, that will reset all properties at once. Example:

_x000D_
_x000D_
.container {_x000D_
  color: blue;_x000D_
  font-style: italic;_x000D_
}_x000D_
.initial {_x000D_
  all: initial;_x000D_
}
_x000D_
<div class="container">_x000D_
  The quick brown <span class="initial">fox</span> jumps over the lazy dog_x000D_
</div>
_x000D_
_x000D_
_x000D_

Browser support tables according to Can I use...

  • all (Currently no support in both IE and Edge, others are good)
  • initial (Currently no support in IE, others are good)

You may find it useful by using direct children selector > in some cases. Example:

_x000D_
_x000D_
.list > li {_x000D_
  border: 1px solid red;_x000D_
  color: blue;_x000D_
}
_x000D_
<ul class="list">_x000D_
  <li>_x000D_
    <span>HEADING 1</span>_x000D_
    <ul>_x000D_
      <li>sub-heading A</li>_x000D_
      <li>sub-heading B</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>_x000D_
    <span>HEADING 2</span>_x000D_
    <ul>_x000D_
      <li>sub-heading A</li>_x000D_
      <li>sub-heading B</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The border style has been applied only to the direct children <li>s, as border is an non-inherited property. But text color has been applied to all the children, as color is an inherited property.

Therefore, > selector would be only useful with non-inherited properties, when it comes to preventing inheritance.

How to exit an application properly

The following code is used in Visual Basic when prompting a user to exit the application:

Dim D As String

D = MsgBox("Are you sure you want to exit?", vbYesNo+vbQuestion,"Thanking You")

If D =  vbYes Then 
Unload Me
Else
Exit Sub
End If
End
End Sub

How to clear browsing history using JavaScript?

It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.

For information refer to How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?

Click event doesn't work on dynamically generated elements

Change

 $(".test").click(function(){

To

 $(".test").live('click', function(){

LIVE DEMO

jQuery .live()

How do I remove the file suffix and path portion from a path string in Bash?

If you can't use basename as suggested in other posts, you can always use sed. Here is an (ugly) example. It isn't the greatest, but it works by extracting the wanted string and replacing the input with the wanted string.

echo '/foo/fizzbuzz.bar' | sed 's|.*\/\([^\.]*\)\(\..*\)$|\1|g'

Which will get you the output

fizzbuzz

How to make program go back to the top of the code instead of closing

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

https://wiki.python.org/moin/ForLoop

HTML table with fixed headers and a fixed column?

The first column has a scrollbar on the cell right below the headers

<table>
    <thead>
        <th> Header 1</th>
        <th> Header 2</th>
        <th> Header 3</th>
    </thead>
    <tbody>
        <tr>
            <td>
                <div style="width: 50; height:30; overflow-y: scroll"> 
                    Tklasdjf alksjf asjdfk jsadfl kajsdl fjasdk fljsaldk 
                    fjlksa djflkasjdflkjsadlkf jsakldjfasdjfklasjdflkjasdlkfjaslkdfjasdf
                </div>
            </td>
            <td>
                Hello world
            </td>
            <td> Hello world2
        </tr>
    </tbody>
</table>

Two's Complement in Python

Two's complement subtracts off (1<<bits) if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.

A function for two's complement of an int...

def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits)        # compute negative value
    return val                         # return positive value as is

Going from a binary string is particularly easy...

binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))

A bit more useful to me is going from hex values (32 bits in this example)...

hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.

To the point:

Is this going to put people off coming to Scala?

Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.

If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I would not be worried.

How many bytes is unsigned long long?

It must be at least 64 bits. Other than that it's implementation defined.

Strictly speaking, unsigned long long isn't standard in C++ until the C++0x standard. unsigned long long is a 'simple-type-specifier' for the type unsigned long long int (so they're synonyms).

The long long set of types is also in C99 and was a common extension to C++ compilers even before being standardized.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

How to correctly dismiss a DialogFragment?

Consider the below sample code snippet which demonstrates how to dismiss a dialog fragment safely:

DialogFragment dialogFragment = new DialogFragment();

/** 
 * do something
 */

// Now you want to dismiss the dialog fragment
if (dialogFragment.getDialog() != null && dialogFragment.getDialog().isShowing())
{
    // Dismiss the dialog
    dialogFragment.dismiss();
}

Happy Coding!

Android LinearLayout : Add border with shadow around a LinearLayout

I get the best looking results by using a 9 patch graphic.

You can simply create an individual 9 patch graphic by using the following editor: http://inloop.github.io/shadow4android/

Example:

The 9 patch graphic:

The 9 patch graphic:

The result:

enter image description here

The source:

<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:background="@drawable/my_nine_patch"

How should I call 3 functions in order to execute them one after the other?

You could also use promises in this way:

    some_3secs_function(this.some_value).then(function(){
       some_5secs_function(this.some_other_value).then(function(){
          some_8secs_function(this.some_other_other_value);
       });
    });

You would have to make some_value global in order to access it from inside the .then

Alternatively, from the outer function you could return the value the inner function would use, like so:

    one(some_value).then(function(return_of_one){
       two(return_of_one).then(function(return_of_two){
          three(return_of_two);
       });
    });

ES6 Update

Since async/await is widely available now, this is the way to accomplish the same:

async function run(){    
    await $('#art1').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art2').animate({'width':'1000px'},1000,'linear').promise()
    await $('#art3').animate({'width':'1000px'},1000,'linear').promise()
}

Which is basically "promisifying" your functions (if they're not already asynchronous), and then awaiting them

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

There are two differences between == and === in PHP arrays and objects that I think didn't mention here; two arrays with different key sorts, and objects.

Two arrays with different key sorts

If you have an array with a key sort and another array with a different key sort, they are strictly different (i.e. using ===). That may cause if you key-sort an array, and try to compare the sorted array with the original one.

For instance, consider an empty array. First, we try to push some new indexes to the array without any special sort. A good example would be an array with strings as keys. Now deep into an example:

// Define an array
$arr = [];

// Adding unsorted keys
$arr["I"] = "we";
$arr["you"] = "you";
$arr["he"] = "they";

Now, we have a not-sorted-keys array (e.g., 'he' came after 'you'). Consider the same array, but we sorted its keys alphabetically:

// Declare array
$alphabetArr = [];

// Adding alphabetical-sorted keys
$alphabetArr["I"] = "we";
$alphabetArr["he"] = "they";
$alphabetArr["you"] = "you";

Tip: You can sort an array by key using ksort() function.

Now you have another array with a different key sort from the first one. So, we're going to compare them:

$arr == $alphabetArr; // true
$arr === $alphabetArr; // false

Note: It may be obvious, but comparing two different arrays using strict comparison always results false. However, two arbitrary arrays may be equal using === or not.

You would say: "This difference is negligible". Then I say it's a difference and should be considered and may happen anytime. As mentioned above, sorting keys in an array is a good example of that.

Objects

Keep in mind, two different objects are never strict-equal. These examples would help:

$stdClass1 = new stdClass();
$stdClass2 = new stdClass();
$clonedStdClass1 = clone $stdClass1;

// Comparing
$stdClass1 == $stdClass2; // true
$stdClass1 === $stdClass2; // false
$stdClass1 == $clonedStdClass1; // true
$stdClass1 === $clonedStdClass1; // false

Note: Assigning an object to another variable does not create a copy - rather, it creates a reference to the same memory location as the object. See here.

Note: As of PHP7, anonymous classes was added. From the results, there is no difference between new class {} and new stdClass() in the tests above.

pull/push from multiple remote locations

I added two separate pushurl to the remote "origin" in the .git congfig file. When I run git push origin "branchName" Then it will run through and push to each url. Not sure if there is an easier way to accomplish this but this works for myself to push to Github source code and to push to My.visualStudio source code at the same time.

[remote "origin"]
  url = "Main Repo URL"
  fetch = +refs/heads/*:refs/remotes/origin/*
  pushurl = "repo1 URL"
  pushurl = "reop2 URl"

Bash script to run php script

If you don't do anything in your bash script than run the php one, you could simply run the php script from cron with a command like /usr/bin/php /path/to/your/file.php.

How to update std::map after using the find method?

std::map::find returns an iterator to the found element (or to the end() if the element was not found). So long as the map is not const, you can modify the element pointed to by the iterator:

std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie

std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

Java - Getting Data from MySQL database

Something like this would do:

public static void main(String[] args) {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost/t";
    String user = "";
    String password = "";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");

        if (rs.next()) {//get first result
            System.out.println(rs.getString(1));//coloumn 1
        }

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

you can iterate over the results with a while like this:

while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}

There are many other great tutorial out there like these to list a few:

As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself

References:

How do you sort a dictionary by value?

Sort and print:

var items = from pair in players_Dic
                orderby pair.Value descending
                select pair;

// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
    Debug.Log(pair.Key + " - " + pair.Value);
}

Change descending to acending to change sort order

How to export JavaScript array info to csv (on client side)?

Simply try this, some of the answers here are not handling unicode data and data that has comma for example date.

function downloadUnicodeCSV(filename, datasource) {
    var content = '', newLine = '\r\n';
    for (var _i = 0, datasource_1 = datasource; _i < datasource_1.length; _i++) {
        var line = datasource_1[_i];
        var i = 0;
        for (var _a = 0, line_1 = line; _a < line_1.length; _a++) {
            var item = line_1[_a];
            var it = item.replace(/"/g, '""');
            if (it.search(/("|,|\n)/g) >= 0) {
                it = '"' + it + '"';
            }
            content += (i > 0 ? ',' : '') + it;
            ++i;
        }
        content += newLine;
    }
    var link = document.createElement('a');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(content));
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};

'tuple' object does not support item assignment

PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:

pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)

Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel[0] + 20, 255) or int(255 * (pixel[0] / 255.) ** 0.9) instead of pixel[0] + 20.

And, to be able to handle images in lots of different formats, do image = image.convert("RGB") after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also write it like this:

let elem: any;
elem = $("div.printArea");
elem.printArea();

How do I sort a dictionary by value?

If values are numeric you may also use Counter from collections.

from collections import Counter

x = {'hello': 1, 'python': 5, 'world': 3}
c = Counter(x)
print(c.most_common())

>> [('python', 5), ('world', 3), ('hello', 1)]    

CSS Transition doesn't work with top, bottom, left, right

In my case div position was fixed , adding left position was not enough it started working only after adding display block

left:0; display:block;

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

Storing integer values as constants in Enum manner in java

if you want to be able to convert integer back to corresponding enum with selected value see Constants.forValue(...) in below auto generated code but if not the answer of BlairHippo is best way to do it.

public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);

    public static final int SIZE = java.lang.Integer.SIZE;

    private int intValue;
    private static java.util.HashMap<Integer, Constants> mappings;
    private static java.util.HashMap<Integer, Constants> getMappings()
    {
        if (mappings == null)
        {
            synchronized (Constants.class)
            {
                if (mappings == null)
                {
                    mappings = new java.util.HashMap<Integer, Constants>();
                }
            }
        }
        return mappings;
    }

    private Constants(int value)
    {
        intValue = value;
        getMappings().put(value, this);
    }

    public int getValue()
    {
        return intValue;
    }

    public static Constants forValue(int value)
    {
        return getMappings().get(value);
    }
}

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

Pycharm and sys.argv arguments

In PyCharm the parameters are added in the Script Parameters as you did but, they are enclosed in double quotes "" and without specifying the Interpreter flags like -s. Those flags are specified in the Interpreter options box.

Script Parameters box contents:

"file1.txt" "file2.txt"

Interpeter flags:

-s

Or, visually:

enter image description here

Then, with a simple test file to evaluate:

if __name__ == "__main__":
    import sys
    print(sys.argv)

We get the parameters we provided (with sys.argv[0] holding the script name of course):

['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']

Setting the correct encoding when piping stdout in Python

Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.

A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.

import sys
for line in sys.stdin:
    # Decode what you receive:
    line = line.decode('iso8859-1')

    # Work with Unicode internally:
    line = line.upper()

    # Encode what you send:
    line = line.encode('utf-8')
    sys.stdout.write(line)

Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.

Recursive sub folder search and return files in a list python

You can use the "recursive" setting within glob module to search through subdirectories

For example:

import glob
glob.glob('//Mypath/folder/**/*',recursive = True)

The second line would return all files within subdirectories for that folder location (Note, you need the '**/*' string at the end of your folder string to do this.)

If you specifically wanted to find text files deep within your subdirectories, you can use

glob.glob('//Mypath/folder/**/*.txt',recursive = True)

Creating an array of objects in Java

This is correct.

A[] a = new A[4];

...creates 4 A references, similar to doing this:

A a1;
A a2;
A a3;
A a4;

Now you couldn't do a1.someMethod() without allocating a1 like this:

a1 = new A();

Similarly, with the array you need to do this:

a[0] = new A();

...before using it.

Excel data validation with suggestions/autocomplete

None of the above mentioned solution worked. The one that seemed to work only provide the functionality for just one cell

Recently I had to enter a lot of names and without suggestions, it was a huge pain. I was fortunate enough to have this excel autocomplete add-in to enable the autocompletion. The down side is that you need to enable macro (but you can always turn it off later)

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

Make sure the hamcrest jar is higher on the import order than your JUnit jar.

JUnit comes with its own org.hamcrest.Matcher class that is probably being used instead.

You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes.

mockito also has the hamcrest classes in it as well, so you may need to move\reorder it as well

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How to convert current date into string in java?

Use a DateFormat implementation; e.g. SimpleDateFormat.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());

How to deploy a React App on Apache web server

Ultimately was able to figure it out , i just hope it will help someone like me.
Following is how the web pack config file should look like check the dist dir and output file specified. I was missing the way to specify the path of dist directory

const webpack = require('webpack');
const path = require('path');
var config = {
    entry: './main.js',

    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index.js',
    },

    devServer: {
        inline: true,
        port: 8080
    },
    resolveLoader: {
        modules: [path.join(__dirname, 'node_modules')]
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
}

module.exports = config;

Then the package json file

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --progress",
    "production": "webpack -p --progress"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack": "^2.2.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.20",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "express": "^4.13.3",
    "webpack": "^1.9.6",
    "webpack-devserver": "0.0.6"
  }
}

Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )

Rest fot the things will depend upon your code and components

Execute following sequence of commands

npm install

this should get you all the dependency (node modules)

then

npm run production

this should get you the final index.js file which will contain all the code bundled

Once done place index.html and index.js files under www/html or the web app root directory and that's all.

How to pass variable number of arguments to printf/sprintf

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.

How to use a variable for the database name in T-SQL?

You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.

Try something like this:

declare @query varchar(max);
set @query = 'create database TEST...';

exec (@query);

Use YAML with variables

After some search, I've found a cleaner solution wich use the % operator.

In your YAML file :

key : 'This is the foobar var : %{foobar}'

In your ruby code :

require 'yaml'

file = YAML.load_file('your_file.yml')

foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }

puts modified_content

And the output is :

This is the foobar var : Hello World !

As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :

Yaml :

key : 'The foo var is %{foo} and the bar var is %{bar} !'

Ruby :

# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }

Output :

The foo var is FOO and the bar var is BAR !

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

How to switch databases in psql?

Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.

Another option is to directly connect to the schema. Example:

sudo -u postgres psql -d my_database_name

Source from man psql:

-d dbname
--dbname=dbname
   Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.

   If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
   documentation for more information.

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

Set the default value in dropdownlist using jQuery

val() should handle both cases

  <option value="1">it's me</option>      


$('select').val('1'); // selects "it's me"

$('select').val("it's me"); // also selects "it's me"

Gaussian filter in MATLAB

In MATLAB R2015a or newer, it is no longer necessary (or advisable from a performance standpoint) to use fspecial followed by imfilter since there is a new function called imgaussfilt that performs this operation in one step and more efficiently.

The basic syntax:

B = imgaussfilt(A,sigma) filters image A with a 2-D Gaussian smoothing kernel with standard deviation specified by sigma.

The size of the filter for a given Gaussian standard deviation (sigam) is chosen automatically, but can also be specified manually:

B = imgaussfilt(A,sigma,'FilterSize',[3 3]);

The default is 2*ceil(2*sigma)+1.

Additional features of imgaussfilter are ability to operate on gpuArrays, filtering in frequency or spacial domain, and advanced image padding options. It looks a lot like IPP... hmmm. Plus, there's a 3D version called imgaussfilt3.

What's the difference between VARCHAR and CHAR?

CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

Command prompt won't change directory to another drive

you should use a /d before path as below :

cd /d e:\

C read file line by line

I want a code from ground 0 so i did this to read the content of dictionary's word line by line.

char temp_str[20]; // you can change the buffer size according to your requirements And A single line's length in a File.

Note I've initialized the buffer With Null character each time I read line.This function can be Automated But Since I need A proof of Concept and want to design a programme Byte By Byte

#include<stdio.h>

int main()
{
int i;
char temp_ch;
FILE *fp=fopen("data.txt","r");
while(temp_ch!=EOF)
{
 i=0;
  char temp_str[20]={'\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
while(temp_ch!='\n')
{
  temp_ch=fgetc(fp);
  temp_str[i]=temp_ch;
  i++;
}
if(temp_ch=='\n')
{
temp_ch=fgetc(fp);
temp_str[i]=temp_ch;
}
printf("%s",temp_str);
}
return 0;
}

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:

myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)

And that DNS name can only be resolved by pods and services inside the cluster.

NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:

mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)

For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster. Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.

A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.

LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)

If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.


You also asked: Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*

Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.


In that diagram you showed, the Client would be a pod inside the cluster.

Efficient way to return a std::vector in c++

If the compiler supports Named Return Value Optimization (http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx), you can directly return the vector provide that there is no:

  1. Different paths returning different named objects
  2. Multiple return paths (even if the same named object is returned on all paths) with EH states introduced.
  3. The named object returned is referenced in an inline asm block.

NRVO optimizes out the redundant copy constructor and destructor calls and thus improves overall performance.

There should be no real diff in your example.

How to dynamically remove items from ListView on a button click?

As for your last question, here's the problem illustrated with a simple example:

Let's say that your list contains 5 elements: list = [1, 2, 3, 4, 5] and your list of items to remove (i.e. the indices) is indices_to_remove = [0, 2, 4]. In the first iteration of the loop you remove the item at index 0, so your list becomes list = [2, 3, 4, 5]. In the second iteration, you remove the item at index 2, so your list becomes list = [2, 3, 5] (as you can see, this removes the wrong element). Finally, in the third iteration, you try to remove the element at index 4, but the list only contains three elements, so you get an out of bounds exception.

Now that you see what the problem is, hopefully you will be able to come up with a solution. Good luck!

Hidden features of Python

__getattr__()

getattr is a really nice way to make generic classes, which is especially useful if you're writing an API. For example, in the FogBugz Python API, getattr is used to pass method calls on to the web service seamlessly:

class FogBugz:
    ...

    def __getattr__(self, name):
        # Let's leave the private stuff to Python
        if name.startswith("__"):
            raise AttributeError("No such attribute '%s'" % name)

        if not self.__handlerCache.has_key(name):
            def handler(**kwargs):
                return self.__makerequest(name, **kwargs)
            self.__handlerCache[name] = handler
        return self.__handlerCache[name]
    ...

When someone calls FogBugz.search(q='bug'), they don't get actually call a search method. Instead, getattr handles the call by creating a new function that wraps the makerequest method, which crafts the appropriate HTTP request to the web API. Any errors will be dispatched by the web service and passed back to the user.

Server is already running in Rails

Remove the file: C:/Sites/folder/Pids/Server.pids

Explanation In UNIX land at least we usually track the process id (pid) in a file like server.pid. I think this is doing the same thing here. That file was probably left over from a crash.