Programs & Examples On #Candidate

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

Vertical (rotated) text in HTML table

There is a quote in the original answer and my previous answer on the IE8 line that throws this off, right near the semi-colon. Yikes and BAAAAD! The code below has the rotation set correctly and works. You have to float in IE for the filter to be applied.

<div style="
    float: left; 
    position: relative;
    -moz-transform: rotate(270deg);  /* FF3.5+ */        
    -o-transform: rotate(270deg);  /* Opera 10.5 */   
    -webkit-transform: rotate(270deg);  /* Saf3.1+, Chrome */              
    filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=3);  /* IE6,IE7 */          
    -ms-filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); /* IE8 */           
"
>Count & Value</div>;

How do I center text horizontally and vertically in a TextView?

Use android:gravity="center" to resolve your issue.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

What is the difference between synchronous and asynchronous programming (in node.js)

In the synchronous case, the console.log command is not executed until the SQL query has finished executing.

In the asynchronous case, the console.log command will be directly executed. The result of the query will then be stored by the "callback" function sometime afterwards.

Loading .sql files from within PHP

Some PHP libraries can parse a SQL file made of multiple SQL statements, explode it properly (not using a simple ";" explode, naturally), and the execute them.

For instance, check Phing's PDOSQLExecTask

Best Practice: Software Versioning

You know you can always check to see what others are doing. Open source software tend to allow access to their repositories. For example you could point your SVN browser to http://svn.doctrine-project.org and take a look at the versioning system used by a real project.

Version numbers, tags, it's all there.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Declaring and using MySQL varchar variables

try this:

declare @foo    varchar(7),
        @oldFoo varchar(7)

set @foo = '138'
set @oldFoo = '0' + @foo

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I got this error when I tried to access a bucket that didn't exist.

I mistakenly switched a path variable with the bucket name variable and so the bucket name had the file path value. So maybe double-check, if the bucket name that you set on your request is correct.

Uninstall all installed gems, in OSX?

The only command helped me to cleanup all gems and ignores default gems, which can't be uninstalled

for x in `gem list --no-versions`; do gem uninstall $x -a -x -I; done

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

nodejs get file name from absolute path?

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();

What is the difference between Builder Design pattern and Factory Design pattern?

  • Constructing a complex object step by step : builder pattern

  • A simple object is created by using a single method : factory method pattern

  • Creating Object by using multiple factory method : Abstract factory pattern

What's the meaning of System.out.println in Java?

System is a class, that has a public static field out. So it's more like

class System 
{
    public static PrintStream out;
}

class PrintStream
{
    public void println ...
}

This is a slight oversimplification, as the PrintStream class is actually in the java.io package, but it's good enough to show the relationship of stuff.

Solve Cross Origin Resource Sharing with Flask

You can get the results with a simple:

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

What is %timeit in python?

IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html

You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html

Your timeit is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit

Contains method for a slice

It might be considered a bit 'hacky' but depending the size and contents of the slice, you can join the slice together and do a string search.

For example you have a slice containing single word values (e.g. "yes", "no", "maybe"). These results are appended to a slice. If you want to check if this slice contains any "maybe" results, you may use

exSlice := ["yes", "no", "yes", "maybe"]
if strings.Contains(strings.Join(exSlice, ","), "maybe") {
  fmt.Println("We have a maybe!")
}

How suitable this is really depends on the size of the slice and length of its members. There may be performance or suitability issues for large slices or long values, but for smaller slices of finite size and simple values it is a valid one-liner to achieve the desired result.

Rails 3 check if attribute changed

Above answers are better but yet for knowledge we have another approch as well, Lets 'catagory' column value changed for an object (@design),

@design.changes.has_key?('catagory')

The .changes will return a hash with key as column's name and values as a array with two values [old_value, new_value] for each columns. For example catagory for above is changed from 'ABC' to 'XYZ' of @design,

@design.changes   # => {} 
@design.catagory = 'XYZ'
@design.changes # => { 'catagory' => ['ABC', 'XYZ'] }

For references change in ROR

How do I make a text input non-editable?

Just to complete the answers available:

An input element can be either readonly or disabled (none of them is editable, but there are a couple of differences: focus,...)

Good explanation can be found here:
What's the difference between disabled=“disabled” and readonly=“readonly” for HTML form input fields?

How to use:

<input type="text" value="Example" disabled /> 
<input type="text" value="Example" readonly />

There are also some solutions to make it through CSS or JavaScript as explained here.

Convert date to another timezone in JavaScript

I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.

The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

UTC is currently 6 hours ahead of 'America/Chicago'. Output is:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15

This action could not be completed. Try Again (-22421)

When above problem exists and you have Two Factor Authentication enabled, just do the following:

  1. go to http://appleid.apple.com and then create your App-Specific Password

enter image description here

  1. Inside Application Loader login with your apple id and App Specific Password you just created.

  2. Upload your ipa to itunesconnect.

How to pass a JSON array as a parameter in URL

Send Json data string to a web address and get a result with method post

in C#

public string SendJsonToUrl(string Url, string StrJsonData)
{
    if (Url == "" || StrJsonData == "") return "";
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = StrJsonData.Length;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(StrJsonData);
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    catch (Exception exp)
    {
        throw new Exception("SendJsonToUrl", exp);
    }
}

in PHP

<?php

$input = file_get_contents('php://input');
$json = json_decode($input ,true);

?>

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

How do I fix the multiple-step OLE DB operation errors in SSIS?

This error will also occur when trying to do an insert and a field is coded not null and nulls are trying to be inserted.

Java - How to create a custom dialog box?

i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.

Sample Error Dialog from CUstomDialog API: CustomDialog Error Message

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

URL to load resources from the classpath in Java

From Java 9+ and up, you can define a new URLStreamHandlerProvider. The URL class uses the service loader framework to load it at run time.

Create a provider:

package org.example;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;

public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if ("classpath".equals(protocol)) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) throws IOException {
                    return ClassLoader.getSystemClassLoader().getResource(u.getPath()).openConnection();
                }
            };
        }
        return null;
    }

}

Create a file called java.net.spi.URLStreamHandlerProvider in the META-INF/services directory with the contents:

org.example.ClasspathURLStreamHandlerProvider

Now the URL class will use the provider when it sees something like:

URL url = new URL("classpath:myfile.txt");

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

How to put a text beside the image?

Use floats to float the image, the text should wrap beside

http://www.w3schools.com/css/css_float.asp

Properly embedding Youtube video into bootstrap 3.0 page

I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.

What is the best way to seed a database in Rails?

Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.

Sync data between Android App and webserver

@Grantismo gives a great overview of Android sync components.

SyncManagerAndroid library provides a simple 2-way sync implementation to plug into the Android Sync framework (AbstractThreadedSyncAdapter.OnPerformSync).

https://github.com/sschendel/SyncManagerAndroid

What is Bootstrap?

Bootstrap, as I know it, is a well defined CSS. Although using Bootstrap you could also use JavaScript, jQuery etc. But the main difference is that, using Bootstrap you can just call the class name and then you get the output on the HTML form. for eg. coloring of buttons shaping of text, using layouts. For all this you do not have to write a CSS file rather you just have to use the correct class name for shaping your HTML form.

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

Print number of keys in Redis

After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.

How to handle onchange event on input type=file in jQuery?

Or could be:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

How does the getView() method work when creating your own custom adapter?

What is exactly the function of the LayoutInflater?

When you design using XML, all your UI elements are just tags and parameters. Before you can use these UI elements, (eg a TextView or LinearLayout), you need to create the actual objects corresponding to these xml elements. That is what the inflater is for. The inflater, uses these tags and their corresponding parameters to create the actual objects and set all the parameters. After this you can get a reference to the UI element using findViewById().

Why do all the articles that I've read check if convertview is null or not first? What does it mean when it is null and what does it mean when it isn't?

This is an interesting one. You see, getView() is called everytime an item in the list is drawn. Now, before the item can be drawn, it has to be created. Now convertView basically is the last used view to draw an item. In getView() you inflate the xml first and then use findByViewID() to get the various UI elements of the listitem. When we check for (convertView == null) what we do is check that if a view is null(for the first item) then create it, else, if it already exists, reuse it, no need to go through the inflate process again. Makes it a lot more efficient.

You must also have come across a concept of ViewHolder in getView(). This makes the list more efficient. What we do is create a viewholder and store the reference to all the UI elements that we got after inflating. This way, we can avoid calling the numerous findByViewId() and save on a lot of time. This ViewHolder is created in the (convertView == null) condition and is stored in the convertView using setTag(). In the else loop we just obtain it back using getView() and reuse it.

What is the parent parameter that this method accepts?

The parent is a ViewGroup to which your view created by getView() is finally attached. Now in your case this would be the ListView.

Hope this helps :)

Simulator or Emulator? What is the difference?

In computer science both a simulation and emulation produce the same outputs, from the same inputs, that the original system does; However, an emulation also uses the same processes to achieve it and is made out of the same materials. A simulation uses different processes from the original system. Also worth noting is the term replication, which is the intermediate of the two - using the same processes but being made out of a different material.

So if I want to run my old Super Mario Bros game on my PC I use an SNES emulator, because it is using the same or similar computer code (processes) to run the game, and uses the same or similar materials (silicon chip). However, if I want to fly a Boeing 747 jet on my PC I use a flight simulator because it uses completely different processes from the original (there are no actual wings, lift or aerodynamics involved!).

Here are the exact definitions taken from a computer science glossary:

A simulation is a model of a system that captures the functional connections between inputs and outputs of the system, but without necessarily being based on processes that are the same as, or similar to, those of the system itself.

A replication is a model of a system that captures the functional connections between inputs and outputs of the system and is based on processes that are the same as, or similar to, those of the system itself.

An emulation is a model of some system that captures the functional connections between inputs and outputs of the system, based on processes that are the same as, or similar to, those of that system, and that is built of the same materials as that system.

Reference: The Open University, M366 Glossary 1.1, 2007

How to clear a chart from a canvas so that hover events cannot be triggered?

We can update the chart data in Chart.js V2.0 as follows:

var myChart = new Chart(ctx, data);
myChart.config.data = new_data;
myChart.update();

Full width image with fixed height

This can done several ways. I usually do it from my class.

From class

.image
{
    width:100%;


}

and for this your html would be:

<img class="image" src="images/image_name">

or if you want to style it using inline styling then you would just have:

<img style="width:100%; height:60px" id="image" src="images/image_name">

I however recommend doing it from your external style-sheet because as your project grows you will realize that the entire thing is easier managed with separate files for your html and your css.

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

Assigning out/ref parameters in Moq

For 'out', the following seems to work for me.

public interface IService
{
    void DoSomething(out string a);
}

[TestMethod]
public void Test()
{
    var service = new Mock<IService>();
    var expectedValue = "value";
    service.Setup(s => s.DoSomething(out expectedValue));

    string actualValue;
    service.Object.DoSomething(out actualValue);
    Assert.AreEqual(expectedValue, actualValue);
}

I'm guessing that Moq looks at the value of 'expectedValue' when you call Setup and remembers it.

For ref, I'm looking for an answer also.

I found the following QuickStart guide useful: https://github.com/Moq/moq4/wiki/Quickstart

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

Rebasing a Git merge commit

Ok, that's an old question and it already have accepted answer by @siride, but that answer wasn't enough in my case, as --preserve-merges forces you to resolve all conflicts second time. My solution based on the idea by @Tobi B but with exact step-by-step commands

So we'll start on such state based on example in the question:

*   8101fe3 Merge branch 'topic'  [HEAD -> master]
|\  
| * b62cae6 2                     [topic]
| |
| | * f5a7ca8 5                   [origin/master]
| | * e7affba 4
| |/  
|/|   
* | eb3b733 3
|/  
* 38abeae 1

Note that we have 2 commits ahead master, so cherry-pick wouldn't work.

  1. First of all, let's create correct history that we want:

    git checkout -b correct-history # create new branch to save master for future
    git rebase --strategy=ours --preserve-merges origin/master
    

    We use --preserve-merges to save our merge commit in history. We use --strategy=ours to ignore all merge conflicts as we don't care about what contents will be in that merge commit, we only need nice history now.

    History will looks like that (ignoring master):

    *   51984c7 Merge branch 'topic'  [HEAD -> correct-history]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    
  2. Let's get correct index now.

    git checkout master # return to our master branch
    git merge origin/master # merge origin/master on top of our master
    

    We may get some additional merge conflicts here, but that's would only be conflicts from files changed between 8101fe3 and f5a7ca8, but not includes already resolved conflicts from topic

    History will looks like this (ignoring correct-history):

    *   94f1484 Merge branch 'origin/master'  [HEAD -> master]
    |\  
    * | f5a7ca8 5                   [origin/master]
    * | e7affba 4
    | *   8101fe3 Merge branch 'topic'
    | |\  
    | | * b62cae6 2                     [topic]
    |/ /
    * / eb3b733 3
    |/  
    * 38abeae 1
    
  3. The last stage is to combine our branch with correct history and branch with correct index

    git reset --soft correct-history
    git commit --amend
    

    We use reset --soft to reset our branch (and history) to correct-history, but leave index and working tree as is. Then we use commit --amend to rewrite our merge commit, that used to have incorrect index, with our good index from master.

    In the end we will have such state (note another id of top commit):

    *   13e6d03 Merge branch 'topic'  [HEAD -> master]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    

Raising a number to a power in Java

Your calculation is likely the culprit. Try using:

bmi = weight / Math.pow(height / 100.0, 2.0);

Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.

Reading and displaying data from a .txt file

I love this piece of code, use it to load a file into one String:

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

deleted object would be re-saved by cascade (remove deleted object from associations)

Kind of Inception going on here.

for (PlaylistadMap playlistadMap : playlistadMaps) {
        PlayList innerPlayList = playlistadMap.getPlayList();
        for (Iterator<PlaylistadMap> iterator = innerPlayList.getPlaylistadMaps().iterator(); iterator.hasNext();) {
            PlaylistadMap innerPlaylistadMap = iterator.next();
            if (innerPlaylistadMap.equals(PlaylistadMap)) {
                iterator.remove();
                session.delete(innerPlaylistadMap);
            }
        }
    }

How can I use break or continue within for loop in Twig template?

From @NHG comment — works perfectly

{% for post in posts|slice(0,10) %}

how to count the total number of lines in a text file using python

count=0
with open ('filename.txt','rb') as f:
    for line in f:
        count+=1

print count

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Async HTTP client loopj vs. Volley

The specifics of my project are small HTTP REST requests, every 1-5 minutes.

I using an async HTTP client (1.4.1) for a long time. The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. Anyway, the new version of the library is not working for me: library inter exception cut chain of callbacks.

Reading all answers motivated me to try something new. I have chosen the Volley HTTP library.

After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley.

Maybe Retrofit is better than an async HTTP client? I need to try it. But I'm sure that Volley is not for me.

Changing the interval of SetInterval while it's running

Here is yet another way to create a decelerating/accelerating interval timer. The interval gets multiplied by a factor until a total time is exceeded.

function setChangingInterval(callback, startInterval, factor, totalTime) {
    let remainingTime = totalTime;
    let interval = startInterval;

    const internalTimer = () => {
        remainingTime -= interval ;
        interval *= factor;
        if (remainingTime >= 0) {
            setTimeout(internalTimer, interval);
            callback();
        }
    };
    internalTimer();
}

Extracting text OpenCV

This is a C# version of the answer from dhanushka using OpenCVSharp

        Mat large = new Mat(INPUT_FILE);
        Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();

        // downsample and use it for processing
        Cv2.PyrDown(large, rgb);
        Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);

        // morphological gradient
        var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
        Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);

        // binarize
        Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);

        // connect horizontally oriented regions
        morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
        Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);

        // find contours
        var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
        Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));

        // filter contours
        var idx = 0;
        foreach (var hierarchyItem in hierarchy)
        {
            idx = hierarchyItem.Next;
            if (idx < 0)
                break;
            OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
            var maskROI = new Mat(mask, rect);
            maskROI.SetTo(new Scalar(0, 0, 0));

            // fill the contour
            Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);

            // ratio of non-zero pixels in the filled region
            double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
            if (r > .45 /* assume at least 45% of the area is filled if it contains text */
                 &&
            (rect.Height > 8 && rect.Width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
            {
                Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
            }
        }

        rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Generate random array of floats between a range

Why not to combine random.uniform with a list comprehension?

>>> def random_floats(low, high, size):
...    return [random.uniform(low, high) for _ in xrange(size)]
... 
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]

Why I cannot cout a string?

If you are using linux system then you need to add

using namespace std;

Below headers

If windows then make sure you put headers correctly #include<iostream.h>

#include<string.h>

Refer this it work perfectly.

#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";
                                       // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

   std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     
// get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

How to count no of lines in text file and store the value into a variable using batch script?

You can also mark with a wildcard symbol * to facilitate group files to count.

Z:\SQLData>find /c /v "" FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_*.txt

Result

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS01_V1.TXT: 2041

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIOST00_V1.TXT: 315938

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS00_V1.TXT: 0

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_CNTPTF00_V1.TXT: 277

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try like this...

select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]

For more info : http://www.sql-server-helper.com/tips/date-formats.aspx

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

I think it is worth considering that you can get the requested info with just a single API call to the standard library...

new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );

// produces "2019-10-30 15:33:47 GMT-4"

You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.

But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.

Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.

You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()" but you have to tell it to include the time via the options or it will just give date.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Add CultureInfo.InvariantCulture as an argument:

using System.Globalization;

...

var dateTime = new DateTime(2016,8,16);
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Will return:

"16/08/2016"

Android Studio doesn't recognize my device

On Windows 7 , the only thing that worked for me is this. Go to Device Manager -> Under Android Phone -> Right Click and select 'enable'

enter image description here

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

htaccess redirect all pages to single page

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]

Initialize array of strings

This example program illustrates initialization of an array of C strings.

#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }
    return 0;
}

It prints out the following:

0: First entry
1: Second entry
2: Third entry

How to show matplotlib plots in python

plt.plot(X,y) function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show() after plt.plot(X,y). So,

import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

if you use routing in your application

make sure Add new components into the routing path

for example :

    const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'home', component: HomeComponent },
  { path: 'fundList',      component: FundListComponent },
];

Find UNC path of a network drive?

The answer is a simple PowerShell one-liner:

Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A

If you only want to pull the UNC for one particular drive, add a where statement:

Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:'  | ft "RemoteName","LocalName" -A

Split a string into an array of strings based on a delimiter

Using the SysUtils.TStringHelper.Split function, introduced in Delphi XE3:

var
  MyString: String;
  Splitted: TArray<String>;
begin
  MyString := 'word:doc,txt,docx';
  Splitted := MyString.Split([':']);
end.

This will split a string with a given delimiter into an array of strings.

PHP code to remove everything but numbers

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

How to implement onBackPressed() in Fragments?

This worked for me: https://stackoverflow.com/a/27145007/3934111

@Override
public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });
}

Docker - Container is not running

docker run -it --entrypoint /bin/bash <imageid>

This was posted by L0j1k in the below post and worked for me.

How do I get into a Docker container's shell?

android get real path by Uri.getPath()

Hii here is my complete code for taking image from camera or galeery

//My variable declaration

protected static final int CAMERA_REQUEST = 0;
    protected static final int GALLERY_REQUEST = 1;
    Bitmap bitmap;
    Uri uri;
    Intent picIntent = null;

//Onclick

if (v.getId()==R.id.image_id){
            startDilog();
        }

//method body

private void startDilog() {
    AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(yourActivity.this);
    myAlertDilog.setTitle("Upload picture option..");
    myAlertDilog.setMessage("Where to upload picture????");
    myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
            picIntent.setType("image/*");
            picIntent.putExtra("return_data",true);
            startActivityForResult(picIntent,GALLERY_REQUEST);
        }
    });
    myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(picIntent,CAMERA_REQUEST);
        }
    });
    myAlertDilog.show();
}

//And rest of things

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==GALLERY_REQUEST){
        if (resultCode==RESULT_OK){
            if (data!=null) {
                uri = data.getData();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                try {
                    BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    options.inSampleSize = calculateInSampleSize(options, 100, 100);
                    options.inJustDecodeBounds = false;
                    Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    imageofpic.setImageBitmap(image);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }else {
                Toast.makeText(getApplicationContext(), "Cancelled",
                        Toast.LENGTH_SHORT).show();
            }
        }else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    }else if (requestCode == CAMERA_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data.hasExtra("data")) {
                bitmap = (Bitmap) data.getExtras().get("data");
                uri = getImageUri(YourActivity.this,bitmap);
                File finalFile = new File(getRealPathFromUri(uri));
                imageofpic.setImageBitmap(bitmap);
            } else if (data.getExtras() == null) {

                Toast.makeText(getApplicationContext(),
                        "No extras to retrieve!", Toast.LENGTH_SHORT)
                        .show();

                BitmapDrawable thumbnail = new BitmapDrawable(
                        getResources(), data.getData().getPath());
                pet_pic.setImageDrawable(thumbnail);

            }

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

private String getRealPathFromUri(Uri tempUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = this.getContentResolver().query(tempUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
    return Uri.parse(path);
}

Find all tables containing column with specified name - MS SQL Server

Like oracle you can find tables and columns with this:

select table_name, column_name
from user_tab_columns 
where column_name 
like '%myname%';

How to mount a single file in a volume

You can mount files or directories/folders it all depends on Source file or directory. And also you need to provide full path or if you are not sure you can use PWD. Here is a simple working example.

In this example, I am mounting env-commands file which already exists in my working directory

$ docker run  --rm -it -v ${PWD}/env-commands:/env-commands aravindgv/eosdt:1.0.5 /bin/bash -c "cat /env-commands"

Get file from project folder java

This sounds like the file is embedded within your application.

You should be using getClass().getResource("/path/to/your/resource.txt"), which returns an URL or getClass().getResourceAsStream("/path/to/your/resource.txt");

If it's not an embedded resource, then you need to know the relative path from your application's execution context to where your file exists

How do I build an import library (.lib) AND a DLL in Visual C++?

you also should specify def name in the project settings here:

Configuration > Properties/Input/Advanced/Module > Definition File

break/exit script

Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with

if (n >= 500) {

.... long running code here

}

If breaking out of a function, you'll probably just want return(), either explicitly or implicitly.

For example, an explicit double return

foo <- function(x) {
  if(x < 10) {
    return(NA)
  } else {
    xx <- seq_len(x)
    xx <- cumsum(xx)
  }
  xx ## return(xx) is implied here
}

> foo(5)
[1] 0
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

By return() being implied, I mean that the last line is as if you'd done return(xx), but it is slightly more efficient to leave off the call to return().

Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else () clause. Such a modification to foo() would be

foo <- function(x) {
  ## out is NA or cumsum(xx) depending on x
  out <- if(x < 10) {
    NA
  } else {
    xx <- seq_len(x)
    cumsum(xx)
  }
  out ## return(out) is implied here
}

> foo(5)
[1] NA
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

sudo: port: command not found

If you have just installed macports just run and it should work

source ~/.bash_profile

Can I hide/show asp:Menu items based on role?

To remove a MenuItem from an ASP.net NavigationMenu by Value:

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

and helper extension:

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

and sample usage:

navigationMenu.RemoveMenuItemByValue("UnitTests");

Note: Any code is released into the public domain. No attribution required.

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

Date query with ISODate in mongodb doesn't seem to work

Try this:

{ "dt" : { "$gte" : ISODate("2013-10-01") } }

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Python executable not finding libpython shared library

Putting on my gravedigger hat...

The best way I've found to address this is at compile time. Since you're the one setting prefix anyway might as well tell the executable explicitly where to find its shared libraries. Unlike OpenSSL and other software packages, Python doesn't give you nice configure directives to handle alternate library paths (not everyone is root you know...) In the simplest case all you need is the following:

./configure --enable-shared \
            --prefix=/usr/local \
            LDFLAGS="-Wl,--rpath=/usr/local/lib"

Or if you prefer the non-linux version:

./configure --enable-shared \
            --prefix=/usr/local \
            LDFLAGS="-R/usr/local/lib"

The "rpath" flag tells python it has runtime libraries it needs in that particular path. You can take this idea further to handle dependencies installed to a different location than the standard system locations. For example, on my systems since I don't have root access and need to make almost completely self-contained Python installs, my configure line looks like this:

./configure --enable-shared \
            --with-system-ffi \
            --with-system-expat \
            --enable-unicode=ucs4 \
            --prefix=/apps/python-${PYTHON_VERSION} \
            LDFLAGS="-L/apps/python-${PYTHON_VERSION}/extlib/lib -Wl,--rpath=/apps/python-${PYTHON_VERSION}/lib -Wl,--rpath=/apps/python-${PYTHON_VERSION}/extlib/lib" \
            CPPFLAGS="-I/apps/python-${PYTHON_VERSION}/extlib/include"

In this case I am compiling the libraries that python uses (like ffi, readline, etc) into an extlib directory within the python directory tree itself. This way I can tar the python-${PYTHON_VERSION} directory and land it anywhere and it will "work" (provided you don't run into libc or libm conflicts). This also helps when trying to run multiple versions of Python on the same box, as you don't need to keep changing your LD_LIBRARY_PATH or worry about picking up the wrong version of the Python library.

Edit: Forgot to mention, the compile will complain if you don't set the PYTHONPATH environment variable to what you use as your prefix and fail to compile some modules, e.g., to extend the above example, set the PYTHONPATH to the prefix used in the above example with export PYTHONPATH=/apps/python-${PYTHON_VERSION}...

Selected value for JSP drop down using JSTL

Maybe I don't completely understand the accepted answer so it didn't work for me.

What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
    </c:forEach>
</select>

because none of the options are selected, thus item = null

<%
    if(item == null){
        item = "selectedDept"; //known value from your database
    }
%>

This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me

':app:lintVitalRelease' error when generating signed apk

Make sure you defined all the translations in all the string.xml files

Using the "animated circle" in an ImageView while loading stuff

For the ones developing in Kotlin, there is a sweet method provided by the Anko library that makes the process of displaying a ProgressDialog a breeze!

Based on that link:

val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
dialog.show()
//....
dialog.dismiss()

This will show a Progress Dialog with the progress % displayed (for which you have to pass the init parameter also to calculate the progress).

There is also the indeterminateProgressDialog() method, which provides the Spinning Circle animation indefinitely until dismissed:

indeterminateProgressDialog("Loading...").show()

Shout out to this blog which led me to this solution.

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

String "true" and "false" to boolean

There isn't any built-in way to handle this (although actionpack might have a helper for that). I would advise something like this

def to_boolean(s)
  s and !!s.match(/^(true|t|yes|y|1)$/i)
end

# or (as Pavling pointed out)

def to_boolean(s)
  !!(s =~ /^(true|t|yes|y|1)$/i)
end

What works as well is to use 0 and non-0 instead of false/true literals:

def to_boolean(s)
  !s.to_i.zero?
end

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

What is the best alternative IDE to Visual Studio

I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.

Should I initialize variable within constructor or outside constructor

I think both are correct programming wise,

But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.

I think it is the "by the book" convention, but it is open for discussion.

Wikipedia

parent & child with position fixed, parent overflow:hidden bug

As an alternative to using clip you could also use {border-radius: 0.0001px} on a parent element. It works not only with absolute/fixed positioned elements.

How to change UIPickerView height

I have found that you can edit the size of the UIPickerView - just not with interface builder. open the .xib file with a text editor and set the size of the picker view to whatever you want. Interface builder does not reset the size and it seems to work. I'm sure apple locked the size for a reason so you'll have to experiment with different sizes to see what works.

Git command to show which specific files are ignored by .gitignore

It should be sufficient to use

git ls-files --others -i --exclude-standard

as that covers everything covered by

git ls-files --others -i --exclude-from=.git/info/exclude

therefore the latter is redundant.


You can make this easier by adding an alias to your ~/.gitconfig file:

git config --global alias.ignored "ls-files --others -i --exclude-standard"

Now you can just type git ignored to see the list. Much easier to remember, and faster to type.

If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:

git config --global alias.ignored "status --ignored -s"

However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.

git ignored | grep some-file-that-isnt-being-ignored-properly

Then, when you just want to see a short display, it's easy enough to remember and type

git status --ignored

(The -s can normally be left off.)

VS 2017 Metadata file '.dll could not be found

The problem was that I had some other normal error messages in my project, and apparently after I fixed those and when I cleaned and built my project AGAIN, then all .dlls succeeded.

Make sure you don't have any other error messages in your project and if you do, fix those first!

How to add hyperlink in JLabel?

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

So just try it :

I think that's exactly what you're searching for.

Here's the complete code example :

/**
 * Example of a jLabel Hyperlink and a jLabel Mailto
 */

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author ibrabelware
 */
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
    /**
     * Creates new form JLabelLink
     */
    public JLabelLink() {
        this.setTitle("jLabelLinkExample");
        this.setSize(300, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));

    pan.add(contact);
    pan.add(website);
        this.setContentPane(pan);
        this.setVisible(true);
        sendMail(contact);
        goWebsite(website);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JLabelLink().setVisible(true);
            }
        });
    }

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }
}

Shell command to tar directory excluding certain files/folders

tar -cvzf destination_folder source_folder -X /home/folder/excludes.txt

-X indicates a file which contains a list of filenames which must be excluded from the backup. For Instance, you can specify *~ in this file to not include any filenames ending with ~ in the backup.

Numpy how to iterate over columns of array?

This should give you a start

>>> for col in range(arr.shape[1]):
    some_function(arr[:,col])


[1 2 3 4]
[99 14 12 43]
[2 5 7 1]

TypeError: $(...).modal is not a function with bootstrap Modal

I have resolved this issue in react by using it like this.

window.$('#modal-id').modal();

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

Use a.any() or a.all()

If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False

Finding median of list in Python

Here's a cleaner solution:

def median(lst):
    quotient, remainder = divmod(len(lst), 2)
    if remainder:
        return sorted(lst)[quotient]
    return sum(sorted(lst)[quotient - 1:quotient + 1]) / 2.

Note: Answer changed to incorporate suggestion in comments.

How to create range in Swift?

I find it surprising that, even in Swift 4, there's still no simple native way to express a String range using Int. The only String methods that let you supply an Int as a way of obtaining a substring by range are prefix and suffix.

It is useful to have on hand some conversion utilities, so that we can talk like NSRange when speaking to a String. Here's a utility that takes a location and length, just like NSRange, and returns a Range<String.Index>:

func range(_ start:Int, _ length:Int) -> Range<String.Index> {
    let i = self.index(start >= 0 ? self.startIndex : self.endIndex,
        offsetBy: start)
    let j = self.index(i, offsetBy: length)
    return i..<j
}

For example, "hello".range(0,1)" is the Range<String.Index> embracing the first character of "hello". As a bonus, I've allowed negative locations: "hello".range(-1,1)" is the Range<String.Index> embracing the last character of "hello".

It is useful also to convert a Range<String.Index> to an NSRange, for those moments when you have to talk to Cocoa (for example, in dealing with NSAttributedString attribute ranges). Swift 4 provides a native way to do that:

let nsrange = NSRange(range, in:s) // where s is the string

We can thus write another utility where we go directly from a String location and length to an NSRange:

extension String {
    func nsRange(_ start:Int, _ length:Int) -> NSRange {
        return NSRange(self.range(start,length), in:self)
    }
}

How to draw circle by canvas in Android?

    private Paint green = new Paint();

    private int greenx , greeny;


 green.setColor(Color.GREEN);

        green.setAntiAlias(false);

        canvas.drawCircle(greenx,greeny,20,green);

An efficient way to Base64 encode a byte array?

Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):

    static public void testBase64EncodeToBuffer()
    {
        for (int i = 1; i < 200; ++i)
        {
            // prep test data
            byte[] testData = new byte[i];
            for (int j = 0; j < i; ++j)
                testData[j] = (byte)(j ^ i);

            // test
            testBase64(testData);
        }
    }

    static void testBase64(byte[] data)
    {
        if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
    }

    static public byte[] appendBase64(byte[] data
                              , int offset
                              , int size
                              , bool addLineBreaks = false)
    {
        byte[] buffer;
        int bufferPos = 0;
        int requiredSize = (4 * ((size + 2) / 3));
        // size/76*2 for 2 line break characters    
        if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);

        buffer = new byte[requiredSize];

        UInt32 octet_a;
        UInt32 octet_b;
        UInt32 octet_c;
        UInt32 triple;
        int lineCount = 0;
        int sizeMod = size - (size % 3);
        // adding all data triplets
        for (; offset < sizeMod;)
        {
            octet_a = data[offset++];
            octet_b = data[offset++];
            octet_c = data[offset++];

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
            if (addLineBreaks)
            {
                if (++lineCount == 19)
                {
                    buffer[bufferPos++] = 13;
                    buffer[bufferPos++] = 10;
                    lineCount = 0;
                }
            }
        }

        // last bytes
        if (sizeMod < size)
        {
            octet_a = offset < size ? data[offset++] : (UInt32)0;
            octet_b = offset < size ? data[offset++] : (UInt32)0;
            octet_c = (UInt32)0; // last character is definitely padded

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];

            // add padding '='
            sizeMod = size % 3;
            // last character is definitely padded
            buffer[bufferPos - 1] = (byte)'=';
            if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
        }
        return buffer;
    }

error: command 'gcc' failed with exit status 1 on CentOS

How i solved

# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv

I hope it will help Someone to resolve "gcc" issue.

Vim: insert the same characters across multiple lines

Updated January 2016

Whilst the accepted answer is a great solution, this is actually slightly fewer keystrokes, and scales better - based in principle on the accepted answer.

  1. Move the cursor to the n in name.
  2. Enter visual block mode (ctrlv).
  3. Press 3j
  4. Press I.
  5. Type in vendor_.
  6. Press esc.

visual illustration

Note, this has fewer keystrokes than the accepted answer provided (compare Step 3). We just count the number of j actions to perform.

If you have line numbers enabled (as illustrated above), and know the line number you wish to move to, then step 3 can be changed to #G where # is the wanted line number.

In our example above, this would be 4G. However when dealing with just a few line numbers an explicit count works well.

Reverse Contents in Array

for(i=0;i<((s3)/2);i++)
{         
    z=s2[i];
    s2[i]=s2[(s3-1)-i];
    s2[(s3-1)-i]=z;
}

How to download a file via FTP with Python ftplib

handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)

Ternary operators in JavaScript without an "else"

To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Original source

How to implement a Keyword Search in MySQL?

Ideally, have a keyword table containing the fields:

Keyword
Id
Count (possibly)

with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.

You'll also need a table of words to not count as keywords (if, and, so, but, ...).

In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".

"LIKE" queries will work but they won't scale as well.

Change the selected value of a drop-down list with jQuery

Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:

<asp:DropDownList id="MyDropDown" runat="server" />

$("[id* = 'MyDropDown']").append("<option value='-1'>&nbsp;</option>"); //etc

Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"

What's the difference between "static" and "static inline" function?

By default, an inline definition is only valid in the current translation unit.

If the storage class is extern, the identifier has external linkage and the inline definition also provides the external definition.

If the storage class is static, the identifier has internal linkage and the inline definition is invisible in other translation units.

If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.

As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static and static inline function definitions.

The inline specifier (like the register storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.

inline and register are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register-qualified variables.

Personally, I use the convention to mark static function definitions within headers also inline, as the main reason for putting function definitions in header files is to make them inlinable.

In general, I only use static inline function and static const object definitions in addition to extern declarations within headers.

I've never written an inline function with a storage class different from static.

Arrow operator (->) usage in C

foo->bar is only shorthand for (*foo).bar. That's all there is to it.

Zero an array in C code

int arr[20] = {0} would be easiest if it only needs to be done once.

Change background color of selected item on a ListView

It's very simple. In the constructor of the "OnItemClick" use the parameter "view" which is the second one that represents the listView or GridView's items's view and it becomes the new item's view made by the adapterView it self. So to set new color ONLY to the SELECTED ITEM itself do as the following:

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){ //view is instead of the view like textView , ImageView, or whatever view.setBackgroundColor(Color.green); }

If you do any different codes to set new color, you will face awkward behaviours like the green color will be applied to the unclicked item.

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

nvm is not compatible with the npm config "prefix" option:

I had the same problem and executing npm config delete prefix did not help me.

But this did:

After installing nvm using brew, create ~/.nvm directory:
$ mkdir ~/.nvm

and add following lines into ~/.bash_profile:

export NVM_DIR=~/.nvm
. $(brew --prefix nvm)/nvm.sh

(Check that you have no other nvm related command in any ~/.bashrc or ~/.profile or ~/.bash_profile)

Open a new terminal and this time it should not print any warning message.
Check that nvm is working by executing nvm --version command.
After that, install/reinstall NodeJS using nvm install node && nvm alias default node.

More Info

I installed nvm using homebrew and after that I got this notification:

Please note that upstream has asked us to make explicit managing nvm via Homebrew is unsupported by them and you should check any problems against the standard nvm install method prior to reporting.

You should create NVM's working directory if it doesn't exist:

 mkdir ~/.nvm

Add the following to ~/.bash_profile or your desired shell configuration file:

 export NVM_DIR=~/.nvm
 . $(brew --prefix nvm)/nvm.sh

You can set $NVM_DIR to any location, but leaving it unchanged from /usr/local/Cellar/nvm/0.31.0 will destroy any nvm-installed Node installations upon upgrade/reinstall.

Ignoring it brought me to this error message:

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local/Cellar/nvm/0.31.0/versions/node/v5.7.1"
Run nvm use --delete-prefix v5.7.1 --silent to unset it.

I followed an earlier guide (from homebrew/nvm) and after that I found that I needed to reinstall NodeJS. So I did:

nvm install node && nvm alias default node

and it was fixed.

Update: Using brew to install NVM causes slow startup of the Terminal. You can follow this instruction to resolve it.

Where does MAMP keep its php.ini?

Just run the following command from your terminal, it will show you your Loaded Configuration File easiest way I have ever found.

php --ini

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. Set these variables:

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and have fun :)

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

How to create global variables accessible in all views using Express / Node.JS?

What I do in order to avoid having a polluted global scope is to create a script that I can include anywhere.

// my-script.js
const ActionsOverTime = require('@bigteam/node-aot').ActionsOverTime;
const config = require('../../config/config').actionsOverTime;
let aotInstance;

(function () {
  if (!aotInstance) {
    console.log('Create new aot instance');
    aotInstance = ActionsOverTime.createActionOverTimeEmitter(config);
  }
})();

exports = aotInstance;

Doing this will only create a new instance once and share that everywhere where the file is included. I am not sure if it is because the variable is cached or of it because of an internal reference mechanism for the application (that might include caching). Any comments on how node resolves this would be great.

Maybe also read this to get the gist on how require works: http://fredkschott.com/post/2014/06/require-and-the-module-system/

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

How to start a Process as administrator mode in C#

var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");

Works also with ProcessStartInfo:

var psi = new ProcessStartInfo
{
    FileName = "notepad",
    UserName = "admin",
    Domain = "",
    Password = pass,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
Process.Start(psi);

Plotting in a non-blocking way with Matplotlib


A simple trick that works for me is the following:

  1. Use the block = False argument inside show: plt.show(block = False)
  2. Use another plt.show() at the end of the .py script.

Example:

import matplotlib.pyplot as plt

plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")

plt.show(block=False)

#more code here (e.g. do calculations and use print to see them on the screen

plt.show()

Note: plt.show() is the last line of my script.

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

Setting up Vim for Python

For those arriving around summer 2013, I believe some of this thread is outdated.

I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.

The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.

I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119

Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...

All the above '{}/{}' are found on github you can find them easily with Google.

How to set up subdomains on IIS 7

Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.

*.example.com IN A 1.2.3.4

http://www.webmasterworld.com/microsoft_asp_net/3194877.htm

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.

In this case, moving the inner class to its own .java file fixed the problem.

Pointer to incomplete class type is not allowed

Check out if you are missing some import.

ImportError: No module named 'bottle' - PyCharm

The settings are changed for PyCharm 5+.

  • Go to File > Default Settings
  • In left sidebar, click Default Project > Project Interpreter
  • At bottom of window, click + to install or - to uninstall.
  • If we click +, a new window opens where we can decrease the results by entering the package name/keyword.
  • Install the package.
  • Go to File > Invalidate caches/restart and click Invalidate and Restart to apply changes and restart PyCharm.

    Settings

    Install package

spacing between form fields

  <form>     
            <div class="form-group">
                <label for="nameLabel">Name</label>
                <input id="name" name="name" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="PhoneLabel">Phone</label>
                <input id="phone" name="phone" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="yearLabel">Year</label>
                <input id="year" name="year" class="form-control" type="text" />
            </div>
        </form>

How do I set the eclipse.ini -vm option?

You have to edit the eclipse.ini file to have an entry similar to this:

C:\Java\JDK\1.5\bin\javaw.exe (your location of java executable)
-vmargs
-Xms64m   (based on you memory requirements)
-Xmx1028m

Also remember that in eclipse.ini, anything meant for Eclipse should be before the -vmargs line and anything for JVM should be after the -vmargs line.

RESTful Authentication via Spring

Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.

I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home

There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

Jquery: Find Text and replace

You can try

$('#id1 p').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('dog', 'doll')); 
});

http://jsfiddle.net/2EvGF/

You could use instead .html() and/or further sophisticate the .replace() call according to your needs

Add a UIView above all, even the navigation bar

You can do that by adding your view directly to the keyWindow:

UIView *myView = /* <- Your custom view */;
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:myView];

UPDATE -- For Swift 4.1 and above

let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(myView)

UPDATE for iOS13 and above

keyWindow is deprecated. You should use the following:

UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.addSubview(myView)

How to go to a URL using jQuery?

//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";

Presenting a UIAlertController properly on an iPad using iOS 8

You can present a UIAlertController from a popover by using UIPopoverPresentationController.

In Obj-C:

UIViewController *self; // code assumes you're in a view controller
UIButton *button; // the button you want to show the popup sheet from

UIAlertController *alertController;
UIAlertAction *destroyAction;
UIAlertAction *otherAction;

alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
destroyAction = [UIAlertAction actionWithTitle:@"Remove All Data"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
otherAction = [UIAlertAction actionWithTitle:@"Blah"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
// note: you can control the order buttons are shown, unlike UIActionSheet
[alertController addAction:destroyAction];
[alertController addAction:otherAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];

UIPopoverPresentationController *popPresenter = [alertController 
                                              popoverPresentationController];
popPresenter.sourceView = button;
popPresenter.sourceRect = button.bounds;
[self presentViewController:alertController animated:YES completion:nil];

Editing for Swift 4.2, though there are many blogs available for the same but it may save your time to go and search for them.

if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = self.view //to set the source of your alert
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement.
    popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction
}

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

Could not find an implementation of the query pattern

You are missing an equality:

var query = (from p in tblPersoon where p.id == 5 select p).Single();

where clause must result in a boolean.

OR you should not be using where at all:

var query = (from p in tblPersoon select p).Single();

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

Appending to an object

You should really go with the array of alerts suggestions, but otherwise adding to the object you mentioned would look like this:

alerts[3]={"app":"goodbyeworld","message":"cya"};

But since you shouldn't use literal numbers as names quote everything and go with

alerts['3']={"app":"goodbyeworld","message":"cya"};

or you can make it an array of objects.

Accessing it looks like

alerts['1'].app
=> "helloworld"

How do I ignore a directory with SVN?

Here's an example directory structure:

\project
    \source
    \cache
    \other

When in project you see that your cache directory is not added and shows up as such.

> svn st
M  source
?  cache

To set the ignore property, do

svn propset svn:ignore cache .

where svn:ignore is the name of the property you're setting, cache is the value of the property, and . is the directory you're setting this property on. It should be the parent directory of the cache directory that needs the property.

To check what properties are set:

> svn proplist
Properties on '.':
  svn:ignore

To see the value of svn:ignore:

> svn propget svn:ignore
cache

To delete properties previously set:

svn propdel svn:ignore

Android: Reverse geocoding - getFromLocation

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

How to check whether a variable is a class or not?

This check is compatible with both Python 2.x and Python 3.x.

import six
isinstance(obj, six.class_types)

This is basically a wrapper function that performs the same check as in andrea_crotti answer.

Example:

>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

jQuery: more than one handler for same event

Both handlers get called.

You may be thinking of inline event binding (eg "onclick=..."), where a big drawback is only one handler may be set for an event.

jQuery conforms to the DOM Level 2 event registration model:

The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

clear data inside text file in c++

If you simply open the file for writing with the truncate-option, you'll delete the content.

std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();

http://www.cplusplus.com/reference/fstream/ofstream/open/

Bootstrap Alert Auto Close

Why all the other answers use slideUp is just beyond me. As I'm using the fade and in classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.

Besides the slideUp method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:

$(document).ready(function() {
    // show the alert
    setTimeout(function() {
        $(".alert").alert('close');
    }, 2000);
});

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Workaround:

Window -> Preferences -> Java -> Installed JREs, select a different JRE

maybe this JDK edition is not suitable:

enter image description here


So try this one instead:

enter image description here

Problem solved!

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

RecyclerView vs. ListView

ListView is the ancestor to RecyclerView. There were many things that ListView either didn't do, or didn't do well. If you were to gather the shortcomings of the ListView and solved the problem by abstracting the problems into different domains you'd end up with something like the recycler view. Here are the main problem points with ListViews:

  • Didn't enforce View Reuse for same item types (look at one of the adapters that are used in a ListView, if you study the getView method you will see that nothing prevents a programmer from creating a new view for every row even if one is passed in via the convertView variable)

  • Didn't prevent costly findViewById uses(Even if you were recycling views as noted above it was possible for devs to be calling findViewById to update the displayed contents of child views. The main purpose of the ViewHolder pattern in ListViews was to cache the findViewById calls. However this was only available if you knew about it as it wasn't part of the platform at all)

  • Only supported Vertical Scrolling with Row displayed Views (Recycler view doesn't care about where views are placed and how they are moved, it's abstracted into a LayoutManager. A Recycler can therefore support the traditional ListView as shown above, as well as things like the GridView, but it isn't limited to that, it can do more, but you have to do the programming foot work to make it happen).

  • Animations to added/removed was not a use case that was considered. It was completely up to you to figure out how go about this (compare the RecyclerView. Adapter classes notify* method offerings v. ListViews to get an idea).

In short RecyclerView is a more flexible take on the ListView, albeit more coding may need to be done on your part.

Passing parameters to a JDBC PreparedStatement

There is a problem in your query..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = "+"''"+userID);
   ResultSet rs = statement.executeQuery();

You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId

Replace it with: -

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = :userId");
   statement.setString(userId, userID);
   ResultSet rs = statement.executeQuery();

Or, you can use ? in place of named value - :userId..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
   statement.setString(1, userID);

ImportError: No module named scipy

My problem was that I spelt one of the libraries wrongly when installing with pip3, which ended up all the other downloaded libaries in the same command not being installed. Just run pip3 install on them again and they should be installed from their cache.

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Bootstrap 3 - How to load content in modal body via AJAX?

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

How can I render repeating React elements?

To expand on Ross Allen's answer, here is a slightly cleaner variant using ES6 arrow syntax.

{this.props.titles.map(title =>
  <th key={title}>{title}</th>
)}

It has the advantage that the JSX part is isolated (no return or ;), making it easier to put a loop around it.

ASP.NET 4.5 has not been registered on the Web server

Some IIS features to be enabled: Reference

DISM /Online /FeatureName:IIS-ApplicationDevelopment 
/FeatureName:IIS-ASPNET /FeatureName:IIS-ASP 
/FeatureName:IIS-NetFxExtensibility 
/FeatureName:IIS-ISAPIExtensions /FeatureName:IIS-ISAPIFilter

Then fix IIS mappings for ASP.NET, run the Aspnet_regiis.exe utility. Reference

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

It’s a name for the :: operator in PHP. It literally means "double colon". For some reason they named it in Hebrew. Check your code syntax, and put a :: where appropriate :-)

Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

.box {
    background: url( 'img/box-bg.png' ) no-repeat top left;
    width: 200px;
    height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
       only screen and (    min--moz-device-pixel-ratio: 1.3 ),
       only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
       only screen and (         min-device-pixel-ratio: 1.3 ),
       only screen and ( min-resolution: 124.8dpi ),
       only screen and ( min-resolution: 1.3dppx ) {

       .box {
           background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
       }

}

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

convert strtotime to date time format in php

Here is exp.

$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);

How to delete a folder in C++?

Try use system "rmdir -s -q file_to_delte".
This will delete the folder and all files in it.

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Is Eclipse the best IDE for Java?

This is subjective... I find it to be a good tool.

It depends what kind of development you're doing - for EJB stuff, many folk would favour Netbeans. It also depends how much you want to spend - I assume you're talking about free IDEs?

How to update parent's state in React?

<Footer 
  action={()=>this.setState({showChart: true})}
/>

<footer className="row">
    <button type="button" onClick={this.props.action}>Edit</button>
  {console.log(this.props)}
</footer>

Try this example to write inline setState, it avoids creating another function.

What is the default lifetime of a session?

Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.

I believe the default is 1440 seconds (24 mins)

http://www.php.net/manual/en/session.configuration.php

Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:

How do I expire a PHP session after 30 minutes?

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Add the below line in your app.gradle file before depencencies block.

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:26.1.0'
    }
}

There's also screenshot below for a better understanding.

Configurations.all block

  1. the configurations.all block will only be helpful if you want your target sdk to be 26. If you can change it to 27 the error will be gone without adding the configuration block in app.gradle file.

  2. There is one more way if you would remove all the test implementation from app.gradle file it would resolve the error and in this also you dont need to add the configuration block nor you need to change the targetsdk version.

Hope that helps.

How can I add an item to a IEnumerable<T> collection?

To add second message you need to -

IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})

What is a typedef enum in Objective-C?

The Typedef is a Keyword in C and C++. It is used to create new names for basic data types (char, int, float, double, struct & enum).

typedef enum {
    kCircle,
    kRectangle,
    kOblateSpheroid
} ShapeType;

Here it creates enumerated data type ShapeType & we can write new names for enum type ShapeType as given below

ShapeType shape1; 
ShapeType shape2; 
ShapeType shape3;

How do I lowercase a string in C?

It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

Calculating days between two dates with Java

Simplest way:

public static long getDifferenceDays(Date d1, Date d2) {
    long diff = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

How to get current moment in ISO 8601 format with date, hour, and minute?

Still, joda-time does only support the extended format: "2015-12-09T00:22:42.930Z" not the basic: "20151209T002242.930Z" ...we might be better off testing a list of formats with java SimpleDateFormat.

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

The flush() method causes Hibernate to flush the session. You can configure Hibernate to use flushing mode for the session by using setFlushMode() method. To get the flush mode for the current session, you can use getFlushMode() method. To check, whether session is dirty, you can use isDirty() method. By default, Hibernate manages flushing of the sessions.

As stated in the documentation:

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/flushing/Flushing.html

Flushing

Flushing is the process of synchronizing the state of the persistence context with the underlying database. The EntityManager and the Hibernate Session expose a set of methods, through which the application developer can change the persistent state of an entity.

The persistence context acts as a transactional write-behind cache, queuing any entity state change. Like any write-behind cache, changes are first applied in-memory and synchronized with the database during flush time. The flush operation takes every entity state change and translates it to an INSERT, UPDATE or DELETE statement.

The flushing strategy is given by the flushMode of the current running Hibernate Session. Although JPA defines only two flushing strategies (AUTO and COMMIT), Hibernate has a much broader spectrum of flush types:

  • ALWAYS: Flushes the Session before every query;
  • AUTO: This is the default mode and it flushes the Session only if necessary;
  • COMMIT: The Session tries to delay the flush until the current Transaction is committed, although it might flush prematurely too;
  • MANUAL: The Session flushing is delegated to the application, which must call Session.flush() explicitly in order to apply the persistence context changes.

By default, Hibernate uses the AUTO flush mode which triggers a flush in the following circumstances:

  • prior to committing a Transaction;
  • prior to executing a JPQL/HQL query that overlaps with the queued entity actions;
  • before executing any native SQL query that has no registered synchronization.

How to wait for the 'end' of 'resize' event and only then perform an action?

There is a much simpler method to execute a function at the end of the resize than calculate the delta time between two calls, simply do it like this :

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(resizedEnded, 500);
});

function resizedEnded(){
    ...
}

And the equivalent for Angular2 :

private resizeId;
@HostListener('window:resize', ['$event'])
onResized(event: Event) {
  clearTimeout(this.resizeId);
  this.resizeId = setTimeout(() => {
    // Your callback method here.
  }, 500);
}

For the angular method, use the () => { } notation in the setTimeout to preserve the scope, otherwise you will not be able to make any function calls or use this.

What is stability in sorting algorithms and why is it important?

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

Background: a "stable" sorting algorithm keeps the items with the same sorting key in order. Suppose we have a list of 5-letter words:

peach
straw
apple
spork

If we sort the list by just the first letter of each word then a stable-sort would produce:

apple
peach
straw
spork

In an unstable sort algorithm, straw or spork may be interchanged, but in a stable one, they stay in the same relative positions (that is, since straw appears before spork in the input, it also appears before spork in the output).

We could sort the list of words using this algorithm: stable sorting by column 5, then 4, then 3, then 2, then 1. In the end, it will be correctly sorted. Convince yourself of that. (by the way, that algorithm is called radix sort)

Now to answer your question, suppose we have a list of first and last names. We are asked to sort "by last name, then by first". We could first sort (stable or unstable) by the first name, then stable sort by the last name. After these sorts, the list is primarily sorted by the last name. However, where last names are the same, the first names are sorted.

You can't stack unstable sorts in the same fashion.

Cast IList to List

How about this:

List<SubProduct> subProducts = Model.subproduct.ToList();

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

Disable future dates in jQuery UI Datepicker

you can use the following.

$("#selector").datepicker({
    maxDate: 0
});

Use SELECT inside an UPDATE query

I had a similar problem. I wanted to find a string in one column and put that value in another column in the same table. The select statement below finds the text inside the parens.

When I created the query in Access I selected all fields. On the SQL view for that query, I replaced the mytable.myfield for the field I wanted to have the value from inside the parens with

SELECT Left(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")), 
            Len(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")))-1) 

I ran a make table query. The make table query has all the fields with the above substitution and ends with INTO NameofNewTable FROM mytable

MySQL: how to get the difference between two timestamps in seconds

How about "TIMESTAMPDIFF":

SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff

How to add 'libs' folder in Android Studio?

also, to get the right arrow, right click and "Add as Library".enter image description here

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Write it as below

<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';

var myNewString = myOldString.replace('username', visitorName);

document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);
</script>

http://jsfiddle.net/h6xc4/23/

Laravel Eloquent: Ordering results of all()

One interesting thing is multiple order by:

according to laravel docs:

DB::table('users')
   ->orderBy('priority', 'desc')
   ->orderBy('email', 'asc')
   ->get();

this means laravel will sort result based on priority attribute. when it's done, it will order result with same priority based on email internally.

How can I verify if one list is a subset of another?

Assuming the items are hashable

>>> from collections import Counter
>>> not Counter([1, 2]) - Counter([1])
False
>>> not Counter([1, 2]) - Counter([1, 2])
True
>>> not Counter([1, 2, 2]) - Counter([1, 2])
False

If you don't care about duplicate items eg. [1, 2, 2] and [1, 2] then just use:

>>> set([1, 2, 2]).issubset([1, 2])
True

Is testing equality on the smaller list after an intersection the fastest way to do this?

.issubset will be the fastest way to do it. Checking the length before testing issubset will not improve speed because you still have O(N + M) items to iterate through and check.

Javascript to convert UTC to local time

var offset = new Date().getTimezoneOffset();

offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.

utc_date.setMinutes(utc_date.getMinutes() - offset);