Programs & Examples On #Casbah

Casbah integrates a Scala toolkit layer on top of the official MongoDB Java driver.

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

This solution is helpful too:

Add validateRequest="false" in the <%@ Page directive.

This is because ASP.net examines input from the browser for dangerous values. More info in this link

throwing an exception in objective-c/cocoa

Use NSError to communicate failures rather than exceptions.

Quick points about NSError:

  • NSError allows for C style error codes (integers) to clearly identify the root cause and hopefully allow the error handler to overcome the error. You can wrap error codes from C libraries like SQLite in NSError instances very easily.

  • NSError also has the benefit of being an object and offers a way to describe the error in more detail with its userInfo dictionary member.

  • But best of all, NSError CANNOT be thrown so it encourages a more proactive approach to error handling, in contrast to other languages which simply throw the hot potato further and further up the call stack at which point it can only be reported to the user and not handled in any meaningful way (not if you believe in following OOP's biggest tenet of information hiding that is).

Reference Link: Reference

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

jQuery's documentation states:

[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

This behavior is in jQuery versions 1.2 and above.

You most likely want this:

$("._statusDDL").val('2');

Getting DOM element value using pure JavaScript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You can either use the prepareStatement method taking an additional int parameter

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

How do I convert a javascript object array to a string array of the object attribute I want?

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

 @Override
    protected void onPostExecute(final Boolean success) {
        mProgressDialog.dismiss();
        mProgressDialog = null;

setting the value null works for me

Questions every good Java/Java EE Developer should be able to answer?

Simple questions such as,

  • What is JRE and JDK?
  • Why does java claim interoperability?

Though these are very basic, many developers do not know the answers. I suggest these be asked before the code-related queries.

Using Python's os.path, how do I go up one directory?

I think the easiest thing to do is just to reuse dirname() So you can call

os.path.dirname(os.path.dirname( __file__ ))

if you file is at /Users/hobbes3/Sites/mysite/templates/method.py

This will return "/Users/hobbes3/Sites/mysite"

Get week of year in JavaScript like in PHP

This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.

/**
 * Get week number in the year.
 * @param  {Integer} [weekStart=0]  First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
 * @return {Integer}                0-based number of week.
 */
Date.prototype.getWeek = function(weekStart) {
    var januaryFirst = new Date(this.getFullYear(), 0, 1);
    if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
      throw new Error('Wrong argument. Must be an integer between 0 and 6.');
    }
    weekStart = weekStart || 0;
    return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};

Align div right in Bootstrap 3

i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right only push the div to the right, but not the content inside the div.

HTML:

<div class="row">
  <div class="container">
    <div class="col-md-4 someclass">
      left content
    </div>
    <div class="col-md-4 col-md-offset-4 someclass">
      <div class="yellow_background totheright">right content</div>
    </div>
  </div>
</div>

CSS:

.someclass{ /*this class for testing purpose only*/
    border:1px solid blue;
    line-height:2em;
}

.totheright{ /*this will align the text to the right*/
  text-align:right;
}

.yellow_background{
    background-color:yellow;
}

Another modification:

...
<div class="yellow_background totheright">
  <span>right content</span>
  <br/>image also align-right<br/>
  <img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...

hope it will clear your problem

How do you define a class of constants in Java?

Just use final class.

If you want to be able to add other values use an abstract class.

It doesn't make much sense using an interface, an interface is supposed to specify a contract. You just want to declare some constant values.

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

isset in jQuery?

function el(id) {
  return document.getElementById(id);
}

if (el('one') || el('two') || el('three')) { 
  alert('yes');

} else if (el('four')) {
  alert('no');
}

Email Address Validation in Android on EditText

This is a sample method i created to validate email addresses, if the string parameter passed is a valid email address , it returns true, else false is returned.

private boolean validateEmailAddress(String emailAddress){
    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
       CharSequence inputStr = emailAddress;  
       Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
       Matcher matcher = pattern.matcher(inputStr);  
       return matcher.matches();
}

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

How to copy part of an array to another array in C#?

int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

Create component to specific module with Angular-CLI

First generate module:

ng g m moduleName --routing

This will create a moduleName folder then Navigate to module folder

cd moduleName

And after that generate component:

ng g c componentName --module=moduleName.module.ts --flat

Use --flat for not creating child folder inside module folder

How do I install Java on Mac OSX allowing version switching?

You can use asdf to install and switch between multiple java versions. It has plugins for other languages as well. You can install asdf with Homebrew

brew install asdf

When asdf is configured, install java plugin

asdf plugin-add java

Pick a version to install

asdf list-all java

For example to install and configure adoptopenjdk8

asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10

And finally if needed, configure JAVA_HOME for your shell. Just add to your shell init script such as ~/.zshrc in case of zsh:

. ~/.asdf/plugins/java/set-java-home.zsh

Usage of sys.stdout.flush() method

import sys
for x in range(10000):
    print "HAPPY >> %s <<\r" % str(x),
    sys.stdout.flush()

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

CORS with POSTMAN

If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).

Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.

Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.

Transition of background-color

To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:

_x000D_
_x000D_
#content #nav a {_x000D_
    background-color: #FF0;_x000D_
    _x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -moz-transition: background-color 1000ms linear;_x000D_
    -o-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
    background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
    <div id="nav">_x000D_
        <a href="#link1">Link 1</a>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

How to format current time using a yyyyMMddHHmmss format?

Use

fmt.Println(t.Format("20060102150405"))

as Go uses following constants to format date,refer here

const (
    stdLongMonth      = "January"
    stdMonth          = "Jan"
    stdNumMonth       = "1"
    stdZeroMonth      = "01"
    stdLongWeekDay    = "Monday"
    stdWeekDay        = "Mon"
    stdDay            = "2"
    stdUnderDay       = "_2"
    stdZeroDay        = "02"
    stdHour           = "15"
    stdHour12         = "3"
    stdZeroHour12     = "03"
    stdMinute         = "4"
    stdZeroMinute     = "04"
    stdSecond         = "5"
    stdZeroSecond     = "05"
    stdLongYear       = "2006"
    stdYear           = "06"
    stdPM             = "PM"
    stdpm             = "pm"
    stdTZ             = "MST"
    stdISO8601TZ      = "Z0700"  // prints Z for UTC
    stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
    stdNumTZ          = "-0700"  // always numeric
    stdNumShortTZ     = "-07"    // always numeric
    stdNumColonTZ     = "-07:00" // always numeric
)

Set date input field's max date to today

A short but may be less readable version of one of the previous answers.

   <script type="text/javascript">
    $(document).ready(DOM_Load);

    function DOM_Load (e) {
        $("#datefield").on("click", dateOfBirth_Click);
    }

    function dateOfBirth_Click(e) {
        let today = new Date();
        $("#datefield").prop("max", `${today.getUTCFullYear()}-${(today.getUTCMonth() + 1).toString().padStart(2, "0")}-${today.getUTCDate().toString().padStart(2, "0")}`);
    }

</script>

Java, Check if integer is multiple of a number

If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:

//j is a multiple of four if
j % 4 == 0

The module operator performs division and gives you the remainder.

What is the most effective way to get the index of an iterator of an std::vector?

I like this one: it - vec.begin(), because to me it clearly says "distance from beginning". With iterators we're used to thinking in terms of arithmetic, so the - sign is the clearest indicator here.

Scroll to the top of the page using JavaScript?

Active all Browser. Good luck

var process;
        var delay = 50; //milisecond scroll top
        var scrollPixel = 20; //pixel U want to change after milisecond
        //Fix Undefine pageofset when using IE 8 below;
        function getPapeYOfSet() {
            var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
            return yOfSet;
        }



        function backToTop() {
            process = setInterval(function () {
                var yOfSet = getPapeYOfSet();
                if (yOfSet === 0) {
                    clearInterval(process);
                } else {
                    window.scrollBy(0, -scrollPixel);
                }
            }, delay);
        }

Using variables inside strings

Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format or an overload of the + operator.

string str = "Hello " + name; // This calls an overload of operator +.

In C#6 (VS2015) string interpolation has been introduced (as described by other answers).

Python "SyntaxError: Non-ASCII character '\xe2' in file"

After about a half hour of looking through stack overflow, It dawned on me that if the use of a single quote " ' " in a comment will through the error:

SyntaxError: Non-ASCII character '\xe2' in file

After looking at the traceback i was able to locate the single quote used in my comment.

Spring @PropertySource using YAML

I was in a particular situation where I couldn't load a @ConfigurationProperties class due to custom file property naming. At the end the only thing that worked is (thanks @Mateusz Balbus):

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyTest.ContextConfiguration.class})
public class MyTest {

    @TestConfiguration
    public static class ContextConfiguration {

        @Autowired
        ApplicationContext applicationContext;

        @Bean
        public ConfigurationPropertiesBean myConfigurationPropertiesBean() throws IOException {
            Resource resource = applicationContext.getResource("classpath:my-properties-file.yml");

            YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
            List<PropertySource<?>> loadedSources = sourceLoader.load("yamlTestProperties", resource);
            PropertySource<?> yamlTestProperties = loadedSources.get(0);
            ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment)applicationContext.getEnvironment();
            configurableEnvironment.getPropertySources().addFirst(yamlTestProperties);

            Binder binder = Binder.get(applicationContext.getEnvironment());
            ConfigurationPropertiesBean configurationPropertiesBean = binder.bind("my-properties-file-prefix", Bindable.of(ConfigurationPropertiesBean.class)).get();
            return configurationPropertiesBean;
        }

    }

    @Autowired
    ConfigurationPropertiesBean configurationPropertiesBean;

    @Test
    public void test() {

        configurationPropertiesBean.getMyProperty();

    }

}

Entityframework Join using join method and lambdas

You can find a few examples here:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });


foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}

Or just google for 'linq join method syntax'.

Seedable JavaScript random number generator

The following is a PRNG that may be fed a custom seed. Calling SeedRandom will return a random generator function. SeedRandom can be called with no arguments in order to seed the returned random function with the current time, or it can be called with either 1 or 2 non-negative inters as arguments in order to seed it with those integers. Due to float point accuracy seeding with only 1 value will only allow the generator to be initiated to one of 2^53 different states.

The returned random generator function takes 1 integer argument named limit, the limit must be in the range 1 to 4294965886, the function will return a number in the range 0 to limit-1.

function SeedRandom(state1,state2){
    var mod1=4294967087
    var mul1=65539
    var mod2=4294965887
    var mul2=65537
    if(typeof state1!="number"){
        state1=+new Date()
    }
    if(typeof state2!="number"){
        state2=state1
    }
    state1=state1%(mod1-1)+1
    state2=state2%(mod2-1)+1
    function random(limit){
        state1=(state1*mul1)%mod1
        state2=(state2*mul2)%mod2
        if(state1<limit && state2<limit && state1<mod1%limit && state2<mod2%limit){
            return random(limit)
        }
        return (state1+state2)%limit
    }
    return random
}

Example use:

var generator1=SeedRandom() //Seed with current time
var randomVariable=generator1(7) //Generate one of the numbers [0,1,2,3,4,5,6]
var generator2=SeedRandom(42) //Seed with a specific seed
var fixedVariable=generator2(7) //First value of this generator will always be
                                //1 because of the specific seed.

This generator exhibit the following properties:

  • It has approximately 2^64 different possible inner states.
  • It has a period of approximately 2^63, plenty more than anyone will ever realistically need in a JavaScript program.
  • Due to the mod values being primes there is no simple pattern in the output, no matter the chosen limit. This is unlike some simpler PRNGs that exhibit some quite systematic patterns.
  • It discards some results in order to get a perfect distribution no matter the limit.
  • It is relatively slow, runs around 10 000 000 times per second on my machine.

CSS disable text selection

Just wanted to summarize everything:

.unselectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

<div class="unselectable" unselectable="yes" onselectstart="return false;"/>

How to get the absolute path to the public_html folder?

You just need to create an offset bypass to how far you want the backwards reading to go. So, we use getcwd() to get the path and explode (split into array) to fetch the data between $root and the ending of the path.

function getRoot($root = "public_html") {
    return explode($root, getcwd())[0].$root."/";
}

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

What's the difference between "&nbsp;" and " "?

&nbsp; should be handled as a whitespace.

&nbsp;&nbsp; should be handled as two whitespaces

' ' can be handled as a non interesting whitespace

' ' + ' ' can be handled as a single ' '

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

Calculating and printing the nth prime number

To calculate the n-th prime, I know two main variants.

The straightforward way

That is to count all the primes starting from 2 as you find them until you have reached the desired nth.

This can be done with different levels of sophistication and efficiency, and there are two conceptually different ways to do it. The first is

Testing the primality of all numbers in sequence

This would be accomplished by a driver function like

public static int nthPrime(int n) {
    int candidate, count;
    for(candidate = 2, count = 0; count < n; ++candidate) {
        if (isPrime(candidate)) {
            ++count;
        }
    }
    // The candidate has been incremented once after the count reached n
    return candidate-1;
}

and the interesting part that determines the efficiency is the isPrime function.

The obvious way for a primality check, given the definition of a prime as a number greater than 1 that is divisible only by 1 and by itself that we learned in school¹, is

Trial division

The direct translation of the definition into code is

private static boolean isPrime(int n) {
    for(int i = 2; i < n; ++i) {
        if (n % i == 0) {
            // We are naive, but not stupid, if
            // the number has a divisor other
            // than 1 or itself, we return immediately.
            return false;
        }
    }
    return true;
}

but, as you will soon discover if you try it, its simplicity is accompanied by slowness. With that primality test, you can find the 1000th prime, 7919, in a few milliseconds (about 20 on my computer), but finding the 10000th prime, 104729, takes seconds (~2.4s), the 100000th prime,1299709, several minutes (about 5), the millionth prime, 15485863, would take about eight and a half hours, the ten-millionth prime, 179424673, weeks, and so on. The runtime complexity is worse than quadratic - T(n² * log n).

So we'd like to speed the primality test up somewhat. A step that many people take is the realisation that a divisor of n (other than n itself) can be at most n/2. If we use that fact and let the trial division loop only run to n/2 instead of n-1, how does the running time of the algorithm change? For composite numbers, the lower loop limit doesn't change anything. For primes, the number of trial divisions is halved, so overall, the running time should be reduced by a factor somewhat smaller than 2. If you try it out, you will find that the running time is almost exactly halved, so almost all the time is spent verifying the primality of primes despite there being many more composites than primes.

Now, that didn't help much if we want to find the one-hundred-millionth prime, so we have to do better. Trying to reduce the loop limit further, let us see for what numbers the upper bound of n/2 is actually needed. If n/2 is a divisor of n, then n/2 is an integer, in other words, n is divisible by 2. But then the loop doesn't go past 2, so it never (except for n = 4) reaches n/2. Jolly good, so what's the next largest possible divisor of n? Why, n/3 of course. But n/3 can only be a divisor of n if it is an integer, in other words, if n is divisible by 3. Then the loop will exit at 3 (or before, at 2) and never reach n/3 (except for n = 9). The next largest possible divisor ...

Hang on a minute! We have 2 <-> n/2 and 3 <-> n/3. The divisors of n come in pairs.

If we consider the pair (d, n/d) of corresponding divisors of n, either d = n/d, i.e. d = vn, or one of them, say d, is smaller than the other. But then d*d < d*(n/d) = n and d < vn. Each pair of corresponding divisors of n contains (at least) one which does not exceed vn.

If n is composite, its smallest nontrivial divisor does not exceed vn.

So we can reduce the loop limit to vn, and that reduces the runtime complexity of the algorithm. It should now be T(n1.5 * v(log n)), but empirically it seems to scale a little bit better - however, there's not enough data to draw reliable conclusions from empirical results.

That finds the millionth prime in about 16 seconds, the ten-millionth in just under nine minutes, and it would find the one-hundred-millionth in about four and a half hours. That's still slow, but a far cry from the ten years or so it would take the naive trial division.

Since there are squares of primes and products of two close primes, like 323 = 17*19, we cannot reduce the limit for the trial division loop below vn. Therefore, while staying with trial division, we must look for other ways to improve the algorithm now.

One easily seen thing is that no prime other than 2 is even, so we need only check odd numbers after we have taken care of 2. That doesn't make much of a difference, though, since the even numbers are the cheapest to find composite - and the bulk of time is still spent verifying the primality of primes. However, if we look at the even numbers as candidate divisors, we see that if n is divisible by an even number, n itself must be even, so (excepting 2) it will have been recognised as composite before division by any even number greater than 2 is attempted. So all divisions by even numbers greater than 2 that occur in the algorithm must necessarily leave a nonzero remainder. We can thus omit these divisions and check for divisibility only by 2 and the odd numbers from 3 to vn. This halves (not quite exactly) the number of divisions required to determine a number as prime or composite and therefore the running time. That's a good start, but can we do better?

Another large family of numbers is the multiples of 3. Every third division we perform is by a multiple of 3, but if n is divisible by one of them, it is also divisible by 3, and hence no division by 9, 15, 21, ... that we perform in our algorithm will ever leave a remainder of 0. So, how can we skip these divisions? Well, the numbers divisible by neither 2 nor 3 are precisely the numbers of the form 6*k ± 1. Starting from 5 (since we're only interested in numbers greater than 1), they are 5, 7, 11, 13, 17, 19, ..., the step from one to the next alternates between 2 and 4, which is easy enough, so we can use

private static boolean isPrime(int n) {
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int step = 4, m = (int)Math.sqrt(n) + 1;
    for(int i = 5; i < m; step = 6-step, i += step) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

This gives us another speedup by a factor of (nearly) 1.5, so we'd need about one and a half hours to the hundred-millionth prime.

If we continue this route, the next step is the elimination of multiples of 5. The numbers coprime to 2, 3 and 5 are the numbers of the form

30*k + 1, 30*k + 7, 30*k + 11, 30*k + 13, 30*k + 17, 30*k + 19, 30*k + 23, 30*k + 29

so we'd need only divide by eight out of every thirty numbers (plus the three smallest primes). The steps from one to the next, starting from 7, cycle through 4, 2, 4, 2, 4, 6, 2, 6. That's still easy enough to implement and yields another speedup by a factor of 1.25 (minus a bit for more complicated code). Going further, the multiples of 7 would be eliminated, leaving 48 out of every 210 numbers to divide by, then 11 (480/2310), 13 (5760/30030) and so on. Each prime p whose multiples are eliminated yields a speedup of (almost) p/(p-1), so the return decreases while the cost (code complexity, space for the lookup table for the steps) increases with each prime.

In general, one would stop soonish, after eliminating the multiples of maybe six or seven primes (or even fewer). Here, however, we can follow through to the very end, when the multiples of all primes have been eliminated and only the primes are left as candidate divisors. Since we are finding all primes in order, each prime is found before it is needed as a candidate divisor and can then be stored for future use. This reduces the algorithmic complexity to - if I haven't miscalculated - O(n1.5 / v(log n)). At the cost of space usage for storing the primes.

With trial division, that is as good as it gets, you have to try and divide by all primes to vn or the first dividing n to determine the primality of n. That finds the hundred-millionth prime in about half an hour here.

So how about

Fast primality tests

Primes have other number-theoretic properties than the absence of nontrivial divisors which composite numbers usually don't have. Such properties, if they are fast to check, can form the basis of probabilistic or deterministic primality tests. The archetypical such property is associated with the name of Pierre de Fermat, who, in the early 17th century, found that

If p is a prime, then p is a divisor of (ap-a) for all a.

This - Fermat's so-called 'little theorem' - is, in the equivalent formulation

Let p be a prime and a not divisible by p. Then p divides ap-1 - 1.

the basis of most of the widespread fast primality tests (for example Miller-Rabin) and variants or analogues of that appear in even more (e.g. Lucas-Selfridge).

So if we want to know if a not too small odd number n is a prime (even and small numbers are efficiently treated by trial division), we can choose any number a (> 1) which is not a multiple of n, for example 2, and check whether n divides an-1 - 1. Since an-1 becomes huge, that is most efficiently done by checking whether a^(n-1) = 1 (mod n), i.e. by modular exponentiation. If that congruence doesn't hold, we know that n is composite. If it holds, however, we cannot conclude that n is prime, for example 2^340 = 1 (mod 341), but 341 = 11 * 31 is composite. Composite numbers n such that a^(n-1) = 1 (mod n) are called Fermat pseudoprimes for the base a.

But such occurrences are rare. Given any base a > 1, although there are an infinite number of Fermat pseudoprimes to base a, they are much rarer than actual primes. For example, there are only 78 base-2 Fermat pseudoprimes and 76 base-3 Fermat pseudoprimes below 100000, but 9592 primes. So if one chooses an arbitrary odd n > 1 and an arbitrary base a > 1 and finds a^(n-1) = 1 (mod n), there's a good chance that n is actually prime.

However, we are in a slightly different situation, we are given n and can only choose a. So, for an odd composite n, for how many a, 1 < a < n-1 can a^(n-1) = 1 (mod n) hold? Unfortunately, there are composite numbers - Carmichael numbers - such that the congruence holds for every a coprime to n. That means that to identify a Carmichael number as composite with the Fermat test, we have to pick a base that is a multiple of one of n's prime divisors - there may not be many such multiples.

But we can strengthen the Fermat test so that composites are more reliably detected. If p is an odd prime, write p-1 = 2*m. Then, if 0 < a < p,

a^(p-1) - 1 = (a^m + 1) * (a^m - 1)

and p divides exactly one of the two factors (the two factors differ by 2, so their greatest common divisor is either 1 or 2). If m is even, we can split a^m - 1 in the same way. Continuing, if p-1 = 2^s * k with k odd, write

a^(p-1) - 1 = (a^(2^(s-1)*k) + 1) * (a^(2^(s-2)*k) + 1) * ... * (a^k + 1) * (a^k - 1)

then p divides exactly one of the factors. This gives rise to the strong Fermat test,

Let n > 2 be an odd number. Write n-1 = 2^s * k with k odd. Given any a with 1 < a < n-1, if

  1. a^k = 1 (mod n) or
  2. a^((2^j)*k) = -1 (mod n) for any j with 0 <= j < s

then n is a strong (Fermat) probable prime for base a. A composite strong base a (Fermat) probable prime is called a strong (Fermat) pseudoprime for the base a. Strong Fermat pseudoprimes are even rarer than ordinary Fermat pseudoprimes, below 1000000, there are 78498 primes, 245 base-2 Fermat pseudoprimes and only 46 base-2 strong Fermat pseudoprimes. More importantly, for any odd composite n, there are at most (n-9)/4 bases 1 < a < n-1 for which n is a strong Fermat pseudoprime.

So if n is an odd composite, the probability that n passes k strong Fermat tests with randomly chosen bases between 1 and n-1 (exclusive bounds) is less than 1/4^k.

A strong Fermat test takes O(log n) steps, each step involves one or two multiplications of numbers with O(log n) bits, so the complexity is O((log n)^3) with naive multiplication [for huge n, more sophisticated multiplication algorithms can be worthwhile].

The Miller-Rabin test is the k-fold strong Fermat test with randomly chosen bases. It is a probabilistic test, but for small enough bounds, short combinations of bases are known which give a deterministic result.

Strong Fermat tests are part of the deterministic APRCL test.

It is advisable to precede such tests with trial division by the first few small primes, since divisions are comparatively cheap and that weeds out most composites.

For the problem of finding the nth prime, in the range where testing all numbers for primality is feasible, there are known combinations of bases that make the multiple strong Fermat test correct, so that would give a faster - O(n*(log n)4) - algorithm.

For n < 2^32, the bases 2, 7, and 61 are sufficient to verify primality. Using that, the hundred-millionth prime is found in about six minutes.

Eliminating composites by prime divisors, the Sieve of Eratosthenes

Instead of investigating the numbers in sequence and checking whether each is prime from scratch, one can also consider the whole set of relevant numbers as one piece and eliminate the multiples of a given prime in one go. This is known as the Sieve of Eratosthenes:

To find the prime numbers not exceeding N

  1. make a list of all numbers from 2 to N
  2. for each k from 2 to N: if k is not yet crossed off, it is prime; cross off all multiples of k as composites

The primes are the numbers in the list which aren't crossed off.

This algorithm is fundamentally different from trial division, although both directly use the divisibility characterisation of primes, in contrast to the Fermat test and similar tests which use other properties of primes.

In trial division, each number n is paired with all primes not exceeding the smaller of vn and the smallest prime divisor of n. Since most composites have a very small prime divisor, detecting composites is cheap here on average. But testing primes is expensive, since there are relatively many primes below vn. Although there are many more composites than primes, the cost of testing primes is so high that it completely dominates the overall running time and renders trial division a relatively slow algorithm. Trial division for all numbers less than N takes O(N1.5 / (log N)²) steps.

In the sieve, each composite n is paired with all of its prime divisors, but only with those. Thus there the primes are the cheap numbers, they are only ever looked at once, while the composites are more expensive, they are crossed off multiple times. One might believe that since a sieve contains many more 'expensive' numbers than 'cheap' ones, it would overall be a bad algorithm. However, a composite number does not have many distinct prime divisors - the number of distinct prime divisors of n is bounded by log n, but usually it is much smaller, the average of the number of distinct prime divisors of the numbers <= n is log log n - so even the 'expensive' numbers in the sieve are on average no more (or hardly more) expensive than the 'cheap' numbers for trial division.

Sieving up to N, for each prime p, there are T(N/p) multiples to cross off, so the total number of crossings-off is T(? (N/p)) = T(N * log (log N)). This yields much faster algorithms for finding the primes up to N than trial division or sequential testing with the faster primality tests.

There is, however, a disadvantage to the sieve, it uses O(N) memory. (But with a segmented sieve, that can be reduced to O(vN) without increasing the time complexity.)

For finding the nth prime, instead of the primes up to N, there is also the problem that it is not known beforehand how far the sieve should reach.

The latter can be solved using the prime number theorem. The PNT says

p(x) ~ x/log x (equivalently: lim p(x)*log x/x = 1),

where p(x) is the number of primes not exceeding x (here and below, log must be the natural logarithm, for the algorithmic complexities it is not important which base is chosen for the logarithms). From that, it follows that p(n) ~ n*log n, where p(n) is the nth prime, and there are good upper bounds for p(n) known from deeper analysis, in particular

n*(log n + log (log n) - 1) < p(n) < n*(log n + log (log n)), for n >= 6.

So one can use that as the sieving limit, it doesn't exceed the target far.

The O(N) space requirement can be overcome by using a segmented sieve. One can then record the primes below vN for O(vN / log N) memory consumption and use segments of increasing length (O(vN) when the sieve is near N).

There are some easy improvements on the algorithm as stated above:

  1. start crossing off multiples of p only at , not at 2*p
  2. eliminate the even numbers from the sieve
  3. eliminate the multiples of further small primes from the sieve

None of these reduce the algorithmic complexity, but they all reduce the constant factors by a significant amount (as with trial division, the elimination of multiples of p yields lesser speedup for larger p while increasing the code complexity more than for smaller p).

Using the first two improvements yields

// Entry k in the array represents the number 2*k+3, so we have to do
// a bit of arithmetic to get the indices right.
public static int nthPrime(int n) {
    if (n < 2) return 2;
    if (n == 2) return 3;
    int limit, root, count = 1;
    limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;
    root = (int)Math.sqrt(limit) + 1;
    limit = (limit-1)/2;
    root = root/2 - 1;
    boolean[] sieve = new boolean[limit];
    for(int i = 0; i < root; ++i) {
        if (!sieve[i]) {
            ++count;
            for(int j = 2*i*(i+3)+3, p = 2*i+3; j < limit; j += p) {
                sieve[j] = true;
            }
        }
    }
    int p;
    for(p = root; count < n; ++p) {
        if (!sieve[p]) {
            ++count;
        }
    }
    return 2*p+1;
}

which finds the hundred-millionth prime, 2038074743, in about 18 seconds. This time can be reduced to about 15 seconds (here, YMMV) by storing the flags packed, one bit per flag, instead of as booleans, since the reduced memory usage gives better cache locality.

Packing the flags, eliminating also multiples of 3 and using bit-twiddling for faster faster counting,

// Count number of set bits in an int
public static int popCount(int n) {
    n -= (n >>> 1) & 0x55555555;
    n = ((n >>> 2) & 0x33333333) + (n & 0x33333333);
    n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F);
    return (n * 0x01010101) >> 24;
}

// Speed up counting by counting the primes per
// array slot and not individually. This yields
// another factor of about 1.24 or so.
public static int nthPrime(int n) {
    if (n < 2) return 2;
    if (n == 2) return 3;
    if (n == 3) return 5;
    int limit, root, count = 2;
    limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;
    root = (int)Math.sqrt(limit);
    switch(limit%6) {
        case 0:
            limit = 2*(limit/6) - 1;
            break;
        case 5:
            limit = 2*(limit/6) + 1;
            break;
        default:
            limit = 2*(limit/6);
    }
    switch(root%6) {
        case 0:
            root = 2*(root/6) - 1;
            break;
        case 5:
            root = 2*(root/6) + 1;
            break;
        default:
            root = 2*(root/6);
    }
    int dim = (limit+31) >> 5;
    int[] sieve = new int[dim];
    for(int i = 0; i < root; ++i) {
        if ((sieve[i >> 5] & (1 << (i&31))) == 0) {
            int start, s1, s2;
            if ((i & 1) == 1) {
                start = i*(3*i+8)+4;
                s1 = 4*i+5;
                s2 = 2*i+3;
            } else {
                start = i*(3*i+10)+7;
                s1 = 2*i+3;
                s2 = 4*i+7;
            }
            for(int j = start; j < limit; j += s2) {
                sieve[j >> 5] |= 1 << (j&31);
                j += s1;
                if (j >= limit) break;
                sieve[j >> 5] |= 1 << (j&31);
            }
        }
    }
    int i;
    for(i = 0; count < n; ++i) {
        count += popCount(~sieve[i]);
    }
    --i;
    int mask = ~sieve[i];
    int p;
    for(p = 31; count >= n; --p) {
        count -= (mask >> p) & 1;
    }
    return 3*(p+(i<<5))+7+(p&1);
}

finds the hundred-millionth prime in about 9 seconds, which is not unbearably long.

There are other types of prime sieves, of particular interest is the Sieve of Atkin, which exploits the fact that certain congruence classes of (rational) primes are composites in the ring of algebraic integers of some quadratic extensions of Q. Here is not the place to expand on the mathematical theory, suffice it to say that the Sieve of Atkin has lower algorithmic complexity than the Sieve of Eratosthenes and hence is preferable for large limits (for small limits, a not overly optimised Atkin sieve has higher overhead and thus can be slower than a comparably optimised Eratosthenes sieve). D. J. Bernstein's primegen library (written in C) is well optimised for numbers below 232 and finds the hundred-millionth prime (here) in about 1.1 seconds.

The fast way

If we only want to find the nth prime, there is no intrinsic value in also finding all the smaller primes. If we can skip most of them, we can save a lot of time and work. Given a good approximation a(n) to the nth prime p(n), if we have a fast way to calculate the number of primes p(a(n)) not exceeding a(n), we can then sieve a small range above or below a(n) to identify the few missing or excess primes between a(n) and p(n).

We have seen an easily computed fairly good approximation to p(n) above, we could take

a(n) = n*(log n + log (log n))

for example.

A good method to compute p(x) is the Meissel-Lehmer method, which computes p(x) in roughly O(x^0.7) time (the exact complexity depends on the implementation, a refinement by Lagarias, Miller, Odlyzko, Deléglise and Rivat lets one compute p(x) in O(x2/3 / log² x) time).

Starting with the simple approximation a(n), we compute e(n) = p(a(n)) - n. By the prime number theorem, the density of primes near a(n) is about 1/log a(n), so we expect p(n) to be near b(n) = a(n) - log a(n)*e(n) and we would sieve a range slightly larger than log a(n)*e(n). For greater confidence that p(n) is in the sieved range, one can increase the range by a factor of 2, say, which almost certainly will be large enough. If the range seems too large, one can iterate with the better approximation b(n) in place of a(n), compute p(b(n)) and f(n) = p((b(n)) - n. Typically, |f(n)| will be much smaller than |e(n)|. If f(n) is approximately -e(n), c(n) = (a(n) + b(n)) / 2 will be a better approximation to p(n). Only in the very unlikely case that f(n) is very close to e(n) (and not very close to 0), finding a sufficiently good approximation to p(n) that the final sieving stage can be done in time comparable to computing p(a(n)) becomes a problem.

In general, after one or two improvements to the initial approximation, the range to be sieved is small enough for the sieving stage to have a complexity of O(n^0.75) or better.

This method finds the hundred-millionth prime in about 40 milliseconds, and the 1012-th prime, 29996224275833, in under eight seconds.


tl;dr: Finding the nth prime can be efficiently done, but the more efficient you want it, the more mathematics is involved.


I have Java code for most of the discussed algorithms prepared here, in case somebody wants to play around with them.


¹ Aside remark for overinterested souls: The definition of primes used in modern mathematics is different, applicable in much more general situations. If we adapt the school definition to include negative numbers - so a number is prime if it's neither 1 nor -1 and divisible only by 1, -1, itself and its negative - that defines (for integers) what is nowadays called an irreducible element of Z, however, for integers, the definitions of prime and irreducible elements coincide.

IIS Express gives Access Denied error when debugging ASP.NET MVC

I had to run Visual Studio in Administrative Mode to get rid of this error.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

How do I pass a variable to the layout using Laravel' Blade templating?

Simplest way to solve:

view()->share('title', 'My Title Here');

Or using view Facade:

use View;

...

View::share('title', 'My Title Here');

jQuery.each - Getting li elements inside an ul

Given an answer as high voted and views. I did find the answer with mixed of here and other links.

I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

So rather than write long code, I found an interesting solution via CSS.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
 var PatientId ; _x000D_
 //var PatientId =1;  //remove to test enable i.e. patient selected_x000D_
 if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
  console.log(PatientId);_x000D_
  $("#dvHeaderSubMenu a").each(function () {   _x000D_
   $(this).addClass('disabled');_x000D_
  });  _x000D_
  return;_x000D_
 }_x000D_
})
_x000D_
.disabled{_x000D_
    pointer-events:none;_x000D_
    opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
     <ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
      <li class="m-nav__item">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
        Overview_x000D_
       </a>_x000D_
      </li>_x000D_
_x000D_
      <li class="m-nav__item active">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-user"></i>_x000D_
        Personal_x000D_
       </a>_x000D_
      </li>_x000D_
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
       <a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
        <i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
        Insurance Claim_x000D_
       </a>_x000D_
       <div class="m-dropdown__wrapper">_x000D_
        <span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
        _x000D_
           <ul class="m-nav">_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
              <i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Primary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-interface"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Secondary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Medical_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
           </ul>_x000D_
          _x000D_
       _x000D_
      </li>_x000D_
     </ul>            _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to limit text width

I think what you are trying to do is to wrap long text without spaces.

look at this :Hyphenator.js and it's demo.

Bind service to activity in Android

This is a biased answer, but I wrote a library that may simplify the usage of Android Services, if they run locally in the same process as the app: https://github.com/germnix/acacia

Basically you define an interface annotated with @Service and its implementing class, and the library creates and binds the service, handles the connection and the background worker thread:

@Service(ServiceImpl.class)
public interface MyService {
    void doProcessing(Foo aComplexParam);
}

public class ServiceImpl implements MyService {
    // your implementation
}

MyService service = Acacia.createService(context, MyService.class);
service.doProcessing(foo);

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    ...
    <service android:name="com.gmr.acacia.AcaciaService"/>
    ...
</application>

You can get an instance of the associated android.app.Service to hide/show persistent notifications, use your own android.app.Service and manually handle threading if you wish.

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

Enter key in textarea

You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup event, as suggested, and use a regular expression to ensure the value is as you require:

<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
    function formatTextArea(textArea) {
        textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
    }

    window.onload = function() {
        var textArea = document.getElementById("t");
        textArea.onkeyup = function(evt) {
            evt = evt || window.event;

            if (evt.keyCode == 13) {
                formatTextArea(this);
            }
        };
    };
</script>

How can I set a css border on one side only?

You can specify border separately for all borders, for example:

#testdiv{
  border-left: 1px solid #000;
  border-right: 2px solid #FF0;
}

You can also specify the look of the border, and use separate style for the top, right, bottom and left borders. for example:

#testdiv{
  border: 1px #000;
  border-style: none solid none solid;
}

How to Select Min and Max date values in Linq Query

If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:

var min = myData.OrderBy( cv => cv.Date1 ).First();

The above will return the entire object. If you just want the date returned:

var min = myData.Min( cv => cv.Date1 );

Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.

From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:

What about the future of LINQ to SQL?

It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

Checkbox value true/false

I'm going to post this answer under the following assumptions. 1) You (un)selected the checkbox on the first page and submitted the form. 2) Your building the second form and you setting the value="" true/false depending on if the previous one was checked. 3) You want the checkbox to reflect if it was checked or not before.

If this is the case then you can do something like:

var $checkbox1 = $('#checkbox1');
$checkbox1.prop('checked', $checkbox1.val() === 'true');

Android - drawable with rounded corners at the top only

You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

and below there is a Note.

Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

How do I load a file from resource folder?

Try Flowing codes on Spring project

ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();

Or on non spring project

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

How to run a PowerShell script without displaying a window?

You can either run it like this (but this shows a windows for a while):

PowerShell.exe -windowstyle hidden { your script.. }

Or you use a helper file I created to avoid the window called PsRun.exe that does exactly that. You can download source and exe file Run scheduled tasks with WinForm GUI in PowerShell. I use it for scheduled tasks.

Edited: as Marco noted this -windowstyle parameter is available only for V2.

MySQL Query to select data from last week?

Probably the most simple way would be:

SELECT id
FROM table
WHERE date >= current_date - 7

For 8 days (i.e. Monday - Monday)

PHP Adding 15 minutes to Time value

Quite easy

$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

How do I execute a stored procedure once for each row returned by query?

use a cursor

ADDENDUM: [MS SQL cursor example]

declare @field1 int
declare @field2 int
declare cur CURSOR LOCAL for
    select field1, field2 from sometable where someotherfield is null

open cur

fetch next from cur into @field1, @field2

while @@FETCH_STATUS = 0 BEGIN

    --execute your sproc on each row
    exec uspYourSproc @field1, @field2

    fetch next from cur into @field1, @field2
END

close cur
deallocate cur

in MS SQL, here's an example article

note that cursors are slower than set-based operations, but faster than manual while-loops; more details in this SO question

ADDENDUM 2: if you will be processing more than just a few records, pull them into a temp table first and run the cursor over the temp table; this will prevent SQL from escalating into table-locks and speed up operation

ADDENDUM 3: and of course, if you can inline whatever your stored procedure is doing to each user ID and run the whole thing as a single SQL update statement, that would be optimal

How do you get/set media volume (not ringtone volume) in Android?

The following code will set the media stream volume to max:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
    audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
    AudioManager.FLAG_SHOW_UI);

How to set default font family for entire Android app

Add this line of code in your res/value/styles.xml

<item name="android:fontFamily">@font/circular_medium</item>

the entire style will look like that

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:fontFamily">@font/circular_medium</item>
</style>

change "circular_medium" to your own font name..

pypi UserWarning: Unknown distribution option: 'install_requires'

It works fine if you follow the official documentation:

import setuptools
setuptools.setup(...)

Source: https://packaging.python.org/tutorials/packaging-projects/#creating-setup-py

Convert JSONArray to String Array

Bit late for an answer, but here's what I came up with using Gson:

for a jsonarray foo: [{"test": "bar"}, {"test": "bar2"}]

JsonArray foo = getJsonFromWherever();
String[] test = new String[foo.size()]
foo.forEach(x -> {test = ArrayUtils.add(test, x.get("test").getAsString());});

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

In Angular, I need to search objects in an array

You can use the existing $filter service. I updated the fiddle above http://jsfiddle.net/gbW8Z/12/

 $scope.showdetails = function(fish_id) {
     var found = $filter('filter')($scope.fish, {id: fish_id}, true);
     if (found.length) {
         $scope.selected = JSON.stringify(found[0]);
     } else {
         $scope.selected = 'Not found';
     }
 }

Angular documentation is here http://docs.angularjs.org/api/ng.filter:filter

How to get row from R data.frame

Logical indexing is very R-ish. Try:

 x[ x$A ==5 & x$B==4.25 & x$C==4.5 , ] 

Or:

subset( x, A ==5 & B==4.25 & C==4.5 )

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

But here's the rub, sometimes you can't or don't want to wait. For example I want to use the new support for RubyMotion which includes RubyMotion project structure support, setup of rake files, setup of configurations that are hooked to iOS Simulator etc.

RubyMine has all of these now, IDEA does not. So I would have to generate a RubyMotion project outside of IDEA, then setup an IDEA project and hook up to that source folder etc and God knows what else.

What JetBrains should do is have a licensing model that would allow me, with the purchase of IDEA to use any of other IDEs, as opposed to just relying on IDEAs plugins.

I would be willing to pay more for that i.e. say 50 bucks more for said flexibility.

The funny thing is, I was originally a RubyMine customer that upgraded to IDEA, because I did want that polyglot setup. Now I'm contemplating paying for the upgrade of RubyMine, just because I need to do RubyMotion now. Also there are other potential areas where this out of sync issue might bite me again . For example torque box workflow / deployment support.

JetBrains has good IDEs but I guess I'm a bit annoyed.

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Displaying the build date

The option not discussed here is to insert your own data into AssemblyInfo.cs, the "AssemblyInformationalVersion" field seems appropriate - we have a couple of projects where we were doing something similar as a build step (however I'm not entirely happy with the way that works so don't really want to reproduce what we've got).

There's an article on the subject on codeproject: http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx

JOptionPane - input dialog box program

After that you have to parse the results. Suppose results are in integers, then

int testint1 = Integer.parse(test1);

Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

Last Run Date on a Stored Procedure in SQL Server

sys.dm_exec_procedure_stats contains the information about the execution functions, constraints and Procedures etc. But the life time of the row has a limit, The moment the execution plan is removed from the cache the entry will disappear.

Use [yourDatabaseName]
GO
SELECT  
        SCHEMA_NAME(sysobject.schema_id),
        OBJECT_NAME(stats.object_id), 
        stats.last_execution_time
    FROM   
        sys.dm_exec_procedure_stats stats
        INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id 
    WHERE  
        sysobject.type = 'P'
    ORDER BY
           stats.last_execution_time DESC  

This will give you the list of the procedures recently executed.

If you want to check if a perticular stored procedure executed recently

SELECT  
    SCHEMA_NAME(sysobject.schema_id),
    OBJECT_NAME(stats.object_id), 
    stats.last_execution_time
FROM   
    sys.dm_exec_procedure_stats stats
    INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id 
WHERE  
    sysobject.type = 'P'
    and (sysobject.object_id = object_id('schemaname.procedurename') 
    OR sysobject.name = 'procedurename')
ORDER BY
       stats.last_execution_time DESC  

Display HTML form values in same page after submit using Ajax

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />

Complete code is:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />

No need to set

return false;

from JavaScript function for neither of those two examples.

How can I add C++11 support to Code::Blocks compiler?

  1. Go to Toolbar -> Settings -> Compiler
  2. In the Selected compiler drop-down menu, make sure GNU GCC Compiler is selected
  3. Below that, select the compiler settings tab and then the compiler flags tab underneath
  4. In the list below, make sure the box for "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is checked
  5. Click OK to save

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

what is difference between success and .done() method of $.ajax

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

Removing body margin in CSS

The right answer for this question is "css reset".

* {
    margin: 0;
    padding: 0;
}

It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.

How to kill a process running on particular port in Linux?

Choose the port number and apply the grep in netstat command as shown below

netstat -ap | grep :7070

Console Output

tcp 0 0 :::7070 :::* LISTEN 3332/java

Kill the service based on PID ( Process Identification Number )

kill -9 3332

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:

TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);

Since you named a variable epoch, do you want the Unix time equivalent of your date?

DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

insert a NOT NULL column to an existing table

ALTER TABLE `MY_TABLE` ADD COLUMN `STAGE` INTEGER UNSIGNED NOT NULL AFTER `PREV_COLUMN`;

Load HTML File Contents to Div [without the use of iframes]

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>

SecurityException: Permission denied (missing INTERNET permission?)

Be sure that the place where you adding

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

is right.

You should write it like that in AndroidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.project"> 
<uses-permission android:name="android.permission.INTERNET"/>

Dont make my mistakes :)

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I move files in node.js?

Using promises for Node versions greater than 8.0.0:

const {promisify} = require('util');
const fs = require('fs');
const {join} = require('path');
const mv = promisify(fs.rename);

const moveThem = async () => {
  // Move file ./bar/foo.js to ./baz/qux.js
  const original = join(__dirname, 'bar/foo.js');
  const target = join(__dirname, 'baz/qux.js'); 
  await mv(original, target);
}

moveThem();

I'm trying to use python in powershell

  1. download Nodejs for windows
  2. install node-vxxx.msi
  3. find "Install Additional Tools for Node.js" script
  4. open and install it
  5. reopen a new shell prompt, type "python" >> press "enter" >> it works!!

How to delete empty folders using windows command prompt?

from the command line: for /R /D %1 in (*) do rd "%1"

in a batch file for /R /D %%1 in (*) do rd "%%1"

I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You could return an XmlDocument for the ToXML method in your class, then when you are going to add the Element with the result document just use something like:

XmlDocument returnedDocument = Your_Class.ToXML();

XmlDocument finalDocument = new XmlDocument();
XmlElement createdElement = finalDocument.CreateElement("Desired_Element_Name");
createdElement.InnerXML = docResult.InnerXML;
finalDocument.AppendChild(createdElement);

That way the entire value for "Desired_Element_Name" on your result XmlDocument will be the entire content of the returned Document.

I hope this helps.

How to getElementByClass instead of GetElementById with JavaScript?

document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';

Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Comprehensive beginner's virtualenv tutorial?

Here's another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

This one shows how to use pip and a pip requirements file with virtualenv; Scobal's two suggested tutorials are both very helpful but are both easy_install-centric.

Note that none of these tutorials explain how to run a different version of Python within a virtualenv - for this, see this SO question: Use different Python version with virtualenv

Check if a given time lies between two times regardless of date

I did it this way:

LocalTime time = LocalTime.now();
if (time.isAfter(LocalTime.of(02, 00)) && (time.isBefore(LocalTime.of(04, 00))))
{
    log.info("Checking after 2AM, before 4AM!");                    
}

Edit:

String time1 = "01:00:00";  
String time2 = "15:00:00";  
LocalTime time = LocalTime.parse(time2);  
if ((time.isAfter(LocalTime.of(20,11,13))) || (time.isBefore(LocalTime.of(14,49,0))))  
{  
    System.out.println("true");  
}  
else  
{  
    System.out.println("false");  
}    

Playing .mp3 and .wav in Java?

I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)

Here is a minimalistic usage example:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Required imports:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

In nodeJs is there a way to loop through an array without using array size?

What you probably want is for...of, a relatively new construct built for the express purpose of enumerating the values of iterable objects:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
  console.log(item);_x000D_
}
_x000D_
_x000D_
_x000D_

... as distinct from for...in, which enumerates property names (presumably1 numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let key in myArray) {_x000D_
  let value =  myArray[key]; // get the value by key_x000D_
  console.log("key: %o, value: %o", key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0 to array.length - 1 rather than using for...in.

So, this is not (as I'd originally thought) an academic question, i.e.:

Without regard for practicality, is it possible to avoid length when iterating over an array?

According to your comment (emphasis mine):

[...] why do I need to calculate the size of an array whereas the interpreter can know it.

You have a misguided aversion to Array.length. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):

loop test

Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.

Loop through each cell in a range of cells when given a Range object

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

Assign output of os.system to a variable and prevent it from being displayed on the screen

I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of from x import x and functions:

from subprocess import PIPE, Popen


def cmdline(command):
    process = Popen(
        args=command,
        stdout=PIPE,
        shell=True
    )
    return process.communicate()[0]

print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')

git clone from another directory

Using the path itself didn't work for me.

Here's what finally worked for me on MacOS:

cd ~/projects
git clone file:///Users/me/projects/myawesomerepo myawesomerepocopy

This also worked:

git clone file://localhost/Users/me/projects/myawesomerepo myawesomerepocopy

The path itself worked if I did this:

git clone --local myawesomerepo myawesomerepocopy

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

Docker-compose: node_modules not present in a volume after npm install succeeds

Due to the way Node.js loads modules, node_modules can be anywhere in the path to your source code. For example, put your source at /worker/src and your package.json in /worker, so /worker/node_modules is where they're installed.

How do I check when a UITextField changes?

The way I've handled it so far: in UITextFieldDelegate

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    // text hasn't changed yet, you have to compute the text AFTER the edit yourself
    let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string)

    // do whatever you need with this updated string (your code)


    // always return true so that changes propagate
    return true
}

Swift4 version

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    return true
}

Ping all addresses in network, windows

An expansion and useful addition to egmackenzie's "arp -a" solution for Windows -

Windows Example searching for my iPhone on the WiFi network

(pre: iPhone WiFi disabled)

  • Open Command Prompt in Admin mode (R.C. Start & look in menu)
  • arp -d <- clear the arp listing!
  • ping 10.1.10.255 <- take your subnet, and ping '255', everyone
  • arp -a
  • iPhone WiFi on
  • ping 10.1.10.255
  • arp -a

See below for example:

enter image description here

Here is a nice writeup on the use of 'arp -d' here if interested -

What does HTTP/1.1 302 mean exactly?

This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:

Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.

The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:

So I aim to provide an answer based in the RFC 7231 which is the current reference for HTTP/1.1 status codes.

The 302 status code

A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:


Redirection example


Web browsers may change from POST to GET in the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

This is how the 302 status code is defined in the RFC 7231:

6.4.3. 302 Found

The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.

The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the different URI(s).

Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

According to MDN web docs from Mozilla, a typical use case for 302 is:

The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don't update their links.

Other status codes for redirection

The RFC 7231 defines the following status codes for redirection:

  • 301 (Moved Permanently)
  • 302 (Found)
  • 307 (Temporary Redirect)

The RFC 7238 was created to define another status code for redirection:

  • 308 (Permanent Redirect)

Refer to this answer for further details.

What is [Serializable] and when should I use it?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.

How serialization works

This illustration shows the overall process of serialization:

enter image description here

The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory.

Details in Microsoft Docs.

Can two Java methods have same name with different return types?

If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.

Get page title with Selenium WebDriver using Java

It could be done by getting the page title by Selenium and do assertion by using TestNG.

  1. Import Assert class in the import section:

    `import org.testng.Assert;`
    
  2. Create a WebDriver object:

    WebDriver driver=new FirefoxDriver();

  3. Apply this to assert the title of the page:

    Assert.assertEquals("Expected page title", driver.getTitle());

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

json_encode sparse PHP array as JSON array, not JSON object

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

What are the differences between LDAP and Active Directory?

Active Directory isn't just an implementation of LDAP by Microsoft, that is only a small part of what AD is. Active Directory is (in an overly simplified way) a service that provides LDAP based authentication with Kerberos based Authorization.

Of course their LDAP and Kerberos implementations in AD are not exactly 100% interoperable with other LDAP/Kerberos implementations...

Fixed header table with horizontal scrollbar and vertical scrollbar on

you can use following CSS code..

body {
    margin:0;
    padding:0;
    height: 100%;
    width: 100%;
}
table {
    border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
    width: 100%;
}

.outer-container {
    background-color: #ccc;    
    top:0;
    left: 0;
    right: 300px;
    bottom:40px;
    overflow:hidden;

}
.inner-container {
    width: 100%;
    height: 100%;
    position: relative;

}
.table-header {
    float:left;
    width: 100%;
}
.table-body {
    float:left;
    height: 100%;
    width: inherit;

}
.header-cell {
    background-color: yellow;
    text-align: left;
    height: 40px;
}
.body-cell {
    background-color: blue;
    text-align: left;
}
.col1, .col3, .col4, .col5 {
    width:120px;
    min-width: 120px;
}
.col2 {
    min-width: 300px;
}

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

In terminal, log into MySQL as root. You may have created a root password when you installed MySQL for the first time or the password could be blank, in which case you can just press ENTER when prompted for a password.

 sudo mysql -p -u root

Now add a new MySQL user with the username of your choice. In this example we are calling it pmauser (for phpmyadmin user). Make sure to replace password_here with your own. You can generate a password here. The % symbol here tells MySQL to allow this user to log in from anywhere remotely. If you wanted heightened security, you could replace this with an IP address.

CREATE USER 'pmauser'@'%' IDENTIFIED BY 'password_here';

Now we will grant superuser privilege to our new user.

GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;

Then go to config.inc.php ( in ubuntu, /etc/phpmyadmin/config.inc.php )

/* User for advanced features */

$cfg['Servers'][$i]['controluser'] = 'pmauser'; 
$cfg['Servers'][$i]['controlpass'] = 'password_here';

How to add class active on specific li on user click with jQuery

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

How to count lines in a document?

As others said wc -l is the best solution, but for future reference you can use Perl:

perl -lne 'END { print $. }'

$. contains line number and END block will execute at the end of script.

Python: Append item to list N times

Itertools repeat combined with list extend.

from itertools import repeat
l = []
l.extend(repeat(x, 100))

How do I use namespaces with TypeScript external modules?

Nothing wrong with Ryan's answer, but for people who came here looking for how to maintain a one-class-per-file structure while still using ES6 namespaces correctly please refer to this helpful resource from Microsoft.

One thing that's unclear to me after reading the doc is: how to import the entire (merged) module with a single import.

Edit Circling back to update this answer. A few approaches to namespacing emerge in TS.

All module classes in one file.

export namespace Shapes {
    export class Triangle {}
    export class Square {}      
}

Import files into namespace, and reassign

import { Triangle as _Triangle } from './triangle';
import { Square as _Square } from './square';

export namespace Shapes {
  export const Triangle = _Triangle;
  export const Square = _Square;
}

Barrels

// ./shapes/index.ts
export { Triangle } from './triangle';
export { Square } from './square';

// in importing file:
import * as Shapes from './shapes/index.ts';
// by node module convention, you can ignore '/index.ts':
import * as Shapes from './shapes';
let myTriangle = new Shapes.Triangle();

A final consideration. You could namespace each file

// triangle.ts
export namespace Shapes {
    export class Triangle {}
}

// square.ts
export namespace Shapes {
    export class Square {}
}

But as one imports two classes from the same namespace, TS will complain there's a duplicate identifier. The only solution as this time is to then alias the namespace.

import { Shapes } from './square';
import { Shapes as _Shapes } from './triangle';

// ugh
let myTriangle = new _Shapes.Shapes.Triangle();

This aliasing is absolutely abhorrent, so don't do it. You're better off with an approach above. Personally, I prefer the 'barrel'.

Bootstrap Modal sitting behind backdrop

I Found that applying ionic framework (ionic.min.cs) after bootstrap coursing this issue for me.

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

The closest legal equivalent to illegal syntax mentioned in question is:

select * from myTable m
where not exists (
  select 1
  from table(sys.ku$_vcnt('Done', 'Finished except', 'In Progress')) patterns
  where m.status like patterns.column_value || '%'
)

Both mine and @Sethionic's answer make possible to list patterns dynamically (just by choosing other source than auxiliar sys.whatever table).

Note, if we had to search pattern inside string (rather than from the beginning) and database contained for example status = 'Done In Progress', then my solution (modified to like '%' || patterns.column_value || '%') would still generate one row for given record, whileas the @Sethionic's solution (modified to another auxiliar join before a) would produce multiple rows for each pattern occurence. Not judging which is better, just be aware of differences and choose which better fits your need.

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

Difference in months between two dates

Simple and fast solution to count total months between 2 dates. If you want to get only different months, not counting the one that is in From date - just remove +1 from code.

public static int GetTotalMonths(DateTime From, DateTime Till)
        {
            int MonthDiff = 0;

            for (int i = 0; i < 12; i++)
            {
                if (From.AddMonths(i).Month == Till.Month)
                {
                    MonthDiff = i + 1;
                    break;
                }
            }

            return MonthDiff;
        }

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

How to POST JSON request using Apache HttpClient?

As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.

To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));

Is there an R function for finding the index of an element in a vector?

The function match works on vectors:

x <- sample(1:10)
x
# [1]  4  5  9  3  8  1  6 10  7  2
match(c(4,8),x)
# [1] 1 5

match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

For multiple matching, %in% is the way to go:

x <- sample(1:4,10,replace=TRUE)
x
# [1] 3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
# [1]  2  5  9 10

%in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise.

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

Java converting Image to BufferedImage

From a Java Game Engine:

/**
 * Converts a given Image into a BufferedImage
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public static BufferedImage toBufferedImage(Image img)
{
    if (img instanceof BufferedImage)
    {
        return (BufferedImage) img;
    }

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

Clear the value of bootstrap-datepicker

I came across this thread while trying to figure out why the dates weren't being cleared in IE7/IE8.
It has to do with the fact that IE8 and older require a second parameter for the Array.prototype.splice() method. Here's the original code in bootstrap.datepicker.js:

clear: function(){
    this.splice(0);
},

Adding the second parameter resolved my issue:

clear: function(){
    this.splice(0,this.length);
},

Creating a chart in Excel that ignores #N/A or blank cells

Best way is use Empty

Dim i as Integer
For i = 1 to 1000
    If CPT_DB.Cells(i, 1) > 100 Then
       CPT_DB.Cells(i, 2) = CPT_DB.Cells(i, 1)
    Else
       CPT_DB.Cells(i, 2) = Empty //**********************
    End If
Next i

Use component from another module

The main rule here is that:

The selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.

So, try to export it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

What should I export?

Export declarable classes that components in other modules should be able to reference in their templates. These are your public classes. If you don't export a class, it stays private, visible only to other component declared in this module.

The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state(as Ward Bell said in https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2)

Angular creates transitive module for each of @NgModules.

This module collects directives that either imported from another module(if transitive module of imported module has exported directives) or declared in current module.

When angular compiles template that belongs to module X it is used those directives that had been collected in X.transitiveModule.directives.

compiledTemplate = new CompiledTemplate(
    false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);

https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251

enter image description here

This way according to the picture above

  • YComponent can't use ZComponent in its template because directives array of Transitive module Y doesn't contain ZComponent because YModule has not imported ZModule whose transitive module contains ZComponent in exportedDirectives array.

  • Within XComponent template we can use ZComponent because Transitive module X has directives array that contains ZComponent because XModule imports module (YModule) that exports module (ZModule) that exports directive ZComponent

  • Within AppComponent template we can't use XComponent because AppModule imports XModule but XModule doesn't exports XComponent.

See also

Clear the cache in JavaScript

Other than caching every hour, or every week, you may cache according to file data.

Example (in PHP):

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

or even use file modification time:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

How to use radio buttons in ReactJS?

import React, { Component } from "react";

class RadionButtons extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // gender : "" , // use this one if you don't wanna any default value for gender
      gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
    };

    this.handleRadioChange = this.handleRadioChange.bind(this);  // we require access to the state of component so we have to bind our function 
  }

  // this function is called whenever you change the radion button 
  handleRadioChange(event) {
      // set the new value of checked radion button to state using setState function which is async funtion
    this.setState({
      gender: event.target.value
    });
  }


  render() {
    return (
      <div>
        <div check>
          <input
            type="radio"
            value="male" // this is te value which will be picked up after radio button change
            checked={this.state.gender === "male"} // when this is true it show the male radio button in checked 
            onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
          />
          <span
           style={{ marginLeft: "5px" }} // inline style in reactjs 
          >Male</span>
        </div>
        <div check>
          <input
            type="radio"
            value="female"
            checked={this.state.gender === "female"}
            onChange={this.handleRadioChange}
          />
          <span style={{ marginLeft: "5px" }}>Female</span>
        </div>
      </div>
    );
  }
}
export default RadionButtons;

How to parse XML using jQuery?

There is the $.parseXML function for this: http://api.jquery.com/jQuery.parseXML/

You can use it like this:

var xml = $.parseXML(yourfile.xml),
  $xml = $( xml ),
  $test = $xml.find('test');

console.log($test.text());

If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON: http://www.fyneworks.com/jquery/xml-to-json/

Getting file names without extensions

Just for the record:

DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
string fileNames = String.Join(", ", smFiles.Select<FileInfo, string>(fi => Path.GetFileNameWithoutExtension(fi.FullName)));

This way you don't use StringBuilder but String.Join(). Also please remark that Path.GetFileNameWithoutExtension() needs a full path (fi.FullName), not fi.Name as I saw in one of the other answers.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

C - freeing structs

Because you defined the struct as consisting of char arrays, the two strings are the structure and freeing the struct is sufficient, nor is there a way to free the struct but keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }, but then you need to allocate memory for the names separately and handle the question of when to free that memory.

Aside: Is there a reason you want to keep the names after the struct has been freed?

Can I make 'git diff' only the line numbers AND changed file names?

git diff master --compact-summary

Output is:

 src/app/components/common/sidebar/toolbar/toolbar.component.html   |  2 +-
 src/app/components/common/sidebar/toolbar/toolbar.component.scss   |  2 --

This is exactly what you need. Same format as when you making commit or pulling new commits from remote.

PS: That's wired that nobody answered this way.

Reset CSS display property to default value

Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.

According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29

I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row

This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.

Creating a JSON response using Django and Python

I use this, it works fine.

from django.utils import simplejson
from django.http import HttpResponse

def some_view(request):
    to_json = {
        "key1": "value1",
        "key2": "value2"
    }
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

Alternative:

from django.utils import simplejson

class JsonResponse(HttpResponse):
    """
        JSON response
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type=None):
        super(JsonResponse, self).__init__(
            content=simplejson.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type,
        )

In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:

from django.http import JsonResponse
def some_view(request):
    return JsonResponse({"key": "value"})

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

Check if all checkboxes are selected

You can use change()

$("input[type='checkbox'].abc").change(function(){
    var a = $("input[type='checkbox'].abc");
    if(a.length == a.filter(":checked").length){
        alert('all checked');
    }
});

All this will do is verify that the total number of .abc checkboxes matches the total number of .abc:checked.

Code example on jsfiddle.

javascript Unable to get property 'value' of undefined or null reference

you have many HTML and java script mistakes includes: tag, using non UTF-8 encoding for form submission, no need,... You must use document.forms.FORMNAME or document.forms[0] for first appear form in page Corrected:

_x000D_
_x000D_
 function validate_frm_new_user_request()_x000D_
{_x000D_
    alert('test');_x000D_
    var valid = true;_x000D_
_x000D_
    if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
    {_x000D_
        alert ( "Please enter your valid ISID Information." );_x000D_
        document.forms.frm_new_user_request.u_userid.focus();_x000D_
        valid = false;_x000D_
  console.log("FALSE::Empty Value ");_x000D_
    }_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
        <tr align="left">_x000D_
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
            </tr>_x000D_
_x000D_
<tr>_x000D_
            <td align="center" colspan="4">_x000D_
                <input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
                </td>_x000D_
        </tr>_x000D_
    </table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Making button go full-width?

The question was raised years ago, with the older version it was a little hard to get...but now this question has a very easy answer.

<div class="btn btn-outline-primary btn-block">Button text here</div>

What is (functional) reactive programming?

If you want to get a feel for FRP, you could start with the old Fran tutorial from 1998, which has animated illustrations. For papers, start with Functional Reactive Animation and then follow up on links on the publications link on my home page and the FRP link on the Haskell wiki.

Personally, I like to think about what FRP means before addressing how it might be implemented. (Code without a specification is an answer without a question and thus "not even wrong".) So I don't describe FRP in representation/implementation terms as Thomas K does in another answer (graphs, nodes, edges, firing, execution, etc). There are many possible implementation styles, but no implementation says what FRP is.

I do resonate with Laurence G's simple description that FRP is about "datatypes that represent a value 'over time' ". Conventional imperative programming captures these dynamic values only indirectly, through state and mutations. The complete history (past, present, future) has no first class representation. Moreover, only discretely evolving values can be (indirectly) captured, since the imperative paradigm is temporally discrete. In contrast, FRP captures these evolving values directly and has no difficulty with continuously evolving values.

FRP is also unusual in that it is concurrent without running afoul of the theoretical & pragmatic rats' nest that plagues imperative concurrency. Semantically, FRP's concurrency is fine-grained, determinate, and continuous. (I'm talking about meaning, not implementation. An implementation may or may not involve concurrency or parallelism.) Semantic determinacy is very important for reasoning, both rigorous and informal. While concurrency adds enormous complexity to imperative programming (due to nondeterministic interleaving), it is effortless in FRP.

So, what is FRP? You could have invented it yourself. Start with these ideas:

  • Dynamic/evolving values (i.e., values "over time") are first class values in themselves. You can define them and combine them, pass them into & out of functions. I called these things "behaviors".

  • Behaviors are built up out of a few primitives, like constant (static) behaviors and time (like a clock), and then with sequential and parallel combination. n behaviors are combined by applying an n-ary function (on static values), "point-wise", i.e., continuously over time.

  • To account for discrete phenomena, have another type (family) of "events", each of which has a stream (finite or infinite) of occurrences. Each occurrence has an associated time and value.

  • To come up with the compositional vocabulary out of which all behaviors and events can be built, play with some examples. Keep deconstructing into pieces that are more general/simple.

  • So that you know you're on solid ground, give the whole model a compositional foundation, using the technique of denotational semantics, which just means that (a) each type has a corresponding simple & precise mathematical type of "meanings", and (b) each primitive and operator has a simple & precise meaning as a function of the meanings of the constituents. Never, ever mix implementation considerations into your exploration process. If this description is gibberish to you, consult (a) Denotational design with type class morphisms, (b) Push-pull functional reactive programming (ignoring the implementation bits), and (c) the Denotational Semantics Haskell wikibooks page. Beware that denotational semantics has two parts, from its two founders Christopher Strachey and Dana Scott: the easier & more useful Strachey part and the harder and less useful (for software design) Scott part.

If you stick with these principles, I expect you'll get something more-or-less in the spirit of FRP.

Where did I get these principles? In software design, I always ask the same question: "what does it mean?". Denotational semantics gave me a precise framework for this question, and one that fits my aesthetics (unlike operational or axiomatic semantics, both of which leave me unsatisfied). So I asked myself what is behavior? I soon realized that the temporally discrete nature of imperative computation is an accommodation to a particular style of machine, rather than a natural description of behavior itself. The simplest precise description of behavior I can think of is simply "function of (continuous) time", so that's my model. Delightfully, this model handles continuous, deterministic concurrency with ease and grace.

It's been quite a challenge to implement this model correctly and efficiently, but that's another story.

Generate unique random numbers between 1 and 100

You can also do it with a one liner like this:

[...((add, set) => add(set, add))((set, add) => set.size < 8 ? add(set.add(Math.floor(Math.random()*100) + 1), add) : set, new Set())]

How do I make the method return type generic?

Not possible. How is the Map supposed to know which subclass of Animal it's going to get, given only a String key?

The only way this would be possible is if each Animal accepted only one type of friend (then it could be a parameter of the Animal class), or of the callFriend() method got a type parameter. But it really looks like you're missing the point of inheritance: it's that you can only treat subclasses uniformly when using exclusively the superclass methods.

What does EntityManager.flush do and why do I need to use it?

The EntityManager.flush() operation can be used the write all changes to the database before the transaction is committed. By default JPA does not normally write changes to the database until the transaction is committed. This is normally desirable as it avoids database access, resources and locks until required. It also allows database writes to be ordered, and batched for optimal database access, and to maintain integrity constraints and avoid deadlocks. This means that when you call persist, merge, or remove the database DML INSERT, UPDATE, DELETE is not executed, until commit, or until a flush is triggered.

Naming convention - underscore in C++ and C# variables

It's just a convention some programmers use to make it clear when you're manipulating a member of the class or some other kind of variable (parameters, local to the function, etc). Another convention that's also in wide use for member variables is prefixing the name with 'm_'.

Anyway, these are only conventions and you will not find a single source for all of them. They're a matter of style and each programming team, project or company has their own (or even don't have any).

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

How to provide animation when calling another activity in Android?

Wrote a tutorial so that you can animate your activity's in and out,

Enjoy:

http://blog.blundellapps.com/animate-an-activity/

How to copy an object in Objective-C

There is also the use of the -> operator for copying. For Example:

-(id)copyWithZone:(NSZone*)zone
{
    MYClass* copy = [MYClass new];
    copy->_property1 = self->_property1;
    ...
    copy->_propertyN = self->_propertyN;
    return copy;
}

The reasoning here is the resulting copied object should reflect the state of the original object. The "." operator could introduce side effects as this one calls getters which in turn may contain logic.

Project vs Repository in GitHub

In general, on GitHub, 1 repository = 1 project. For example: https://github.com/spring-projects/spring-boot . But it isn't a hard rule.

1 repository = many projects. For example: https://github.com/donhuvy/java_examples

1 projects = many repositories. For example: https://github.com/zendframework/zendframework (1 project named Zend Framework 3 has 61 + 1 = 62 repositories, don't believe? let count Zend Frameworks' modules + main repository)

I totally agree with @Brandon Ibbotson's comment:

A GitHub repository is just a "directory" where folders and files can exist.

Append an object to a list in R in amortized constant time, O(1)?

mylist<-list(1,2,3) mylist<-c(mylist,list(5))

So we can easily append the element/object using the above code

Convert Data URI to File then append to FormData

After playing around with a few things, I managed to figure this out myself.

First of all, this will convert a dataURI to a Blob:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

From there, appending the data to a form such that it will be uploaded as a file is easy:

var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);

catching stdout in realtime from subprocess

if you run something like this in a thread and save the ffmpeg_time property in a property of a method so you can access it, it would work very nice I get outputs like this: output be like if you use threading in tkinter

input = 'path/input_file.mp4'
output = 'path/input_file.mp4'
command = "ffmpeg -y -v quiet -stats -i \"" + str(input) + "\" -metadata title=\"@alaa_sanatisharif\" -preset ultrafast -vcodec copy -r 50 -vsync 1 -async 1 \"" + output + "\""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
for line in self.process.stdout:
    reg = re.search('\d\d:\d\d:\d\d', line)
    ffmpeg_time = reg.group(0) if reg else ''
    print(ffmpeg_time)

Check if an HTML input element is empty or has no value entered by user

You want:

if (document.getElementById('customx').value === ""){
    //do something
}

The value property will give you a string value and you need to compare that against an empty string.

An attempt was made to access a socket in a way forbidden by its access permissions

Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;

/**
 *
 * @author Manindar
 */
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
            v.download();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Add the below Dependency in your POM.XML file

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>vget</artifactId>
            <version>1.1.33</version>
        </dependency>

Hope this will be useful.

What does %s mean in a python format string?

%sand %d are Format Specifiers or placeholders for formatting strings/decimals/floats etc.

MOST common used Format specifier:

%s : string

%d : decimals

%f : float

Self explanatory code:

name = "Gandalf"
extendedName = "the Grey"
age = 84
IQ = 149.9
print('type(name):', type(name)) #type(name): <class 'str'>
print('type(age):', type(age))   #type(age): <class 'int'>   
print('type(IQ):', type(IQ))     #type(IQ): <class 'float'>   

print('%s %s\'s age is %d with incredible IQ of %f ' %(name, extendedName, age, IQ)) #Gandalf the Grey's age is 84 with incredible IQ of 149.900000 

#Same output can be printed in following ways:


print ('{0} {1}\'s age is {2} with incredible IQ of {3} '.format(name, extendedName, age, IQ))          # with help of older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ))          # with help of older method

print("Multiplication of %d and %f is %f" %(age, IQ, age*IQ)) #Multiplication of 84 and 149.900000 is 12591.600000          

#storing formattings in string

sub1 = "python string!"
sub2 = "an arg"

a = "i am a %s" % sub1
b = "i am a {0}".format(sub1)

c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)

print(a)    # "i am a python string!"
print(b)   # "i am a python string!"
print(c)    # "with an arg!"
print(d)   # "with an arg!"

What is the difference between YAML and JSON?

GIT and YAML

The other answers are good. Read those first. But I'll add one other reason to use YAML sometimes: git.

Increasingly, many programming projects use git repositories for distribution and archival. And, while a git repo's history can equally store JSON and YAML files, the "diff" method used for tracking and displaying changes to a file is line-oriented. Since YAML is forced to be line-oriented, any small changes in a YAML file are easier to see by a human.

It is true, of course, that JSON files can be "made pretty" by sorting the strings/keys and adding indentation. But this is not the default and I'm lazy.

Personally, I generally use JSON for system-to-system interaction. I often use YAML for config files, static files, and tracked files. (I also generally avoid adding YAML relational anchors. Life is too short to hunt down loops.)

Also, if speed and space are really a concern, I don't use either. You might want to look at BSON.

How to Resize a Bitmap in Android?

Scale a bitmap with a target maximum size and width, while maintaining aspect ratio:

int maxHeight = 2000;
int maxWidth = 2000;    
float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight()));

Matrix matrix = new Matrix();
matrix.postScale(scale, scale);

bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

HintPath vs ReferencePath in Visual Studio

According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/

There is a search order for assemblies when building. The search order is as follows:

  • Files from the current project – indicated by ${CandidateAssemblyFiles}.
  • $(ReferencePath) property that comes from .user/targets file.
  • %(HintPath) metadata indicated by reference item.
  • Target framework directory.
  • Directories found in registry that uses AssemblyFoldersEx Registration.
  • Registered assembly folders, indicated by ${AssemblyFolders}.
  • $(OutputPath) or $(OutDir)
  • GAC

So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.

Knockout validation

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

Select single item from a list

SingleOrDefault() is what you need

cheers

Cut Corners using CSS

by small modification of Joshep's code...You can use this code which seems like right corner folded down as per your requirement.

div {
    height: 300px;
    background: red;
    position: relative;
}

div:before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    border-top: 80px solid white;
    border-left: 80px solid blue;
    width: 0;
}

How to remove duplicate values from an array in PHP

Use array_unique().

Example:

$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)

Meaning of @classmethod and @staticmethod for beginner?

A slightly different way to think about it that might be useful for someone... A class method is used in a superclass to define how that method should behave when it's called by different child classes. A static method is used when we want to return the same thing regardless of the child class that we are calling.

.autocomplete is not a function Error

Check the Sources-> Scripts in browser Inspect tool. Sometimes multiple jQuery files can be referring. In ASP.NET MVC, this usually happens when the layout page already has a jQuery reference.

REST, HTTP DELETE and parameters

No, it is not RESTful. The only reason why you should be putting a verb (force_delete) into the URI is if you would need to overload GET/POST methods in an environment where PUT/DELETE methods are not available. Judging from your use of the DELETE method, this is not the case.

HTTP error code 409/Conflict should be used for situations where there is a conflict which prevents the RESTful service to perform the operation, but there is still a chance that the user might be able to resolve the conflict himself. A pre-deletion confirmation (where there are no real conflicts which would prevent deletion) is not a conflict per se, as nothing prevents the API from performing the requested operation.

As Alex said (I don't know who downvoted him, he is correct), this should be handled in the UI, because a RESTful service as such just processes requests and should be therefore stateless (i.e. it must not rely on confirmations by holding any server-side information about of a request).

Two examples how to do this in UI would be to:

  • pre-HTML5:* show a JS confirmation dialog to the user, and send the request only if the user confirms it
  • HTML5:* use a form with action DELETE where the form would contain only "Confirm" and "Cancel" buttons ("Confirm" would be the submit button)

(*) Please note that HTML versions prior to 5 do not support PUT and DELETE HTTP methods natively, however most modern browsers can do these two methods via AJAX calls. See this thread for details about cross-browser support.


Update (based on additional investigation and discussions):

The scenario where the service would require the force_delete=true flag to be present violates the uniform interface as defined in Roy Fielding's dissertation. Also, as per HTTP RFC, the DELETE method may be overridden on the origin server (client), implying that this is not done on the target server (service).

So once the service receives a DELETE request, it should process it without needing any additional confirmation (regardless if the service actually performs the operation).

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

How to get the contents of a webpage in a shell variable?

You can use curl or wget to retrieve the raw data, or you can use w3m -dump to have a nice text representation of a web page.

$ foo=$(w3m -dump http://www.example.com/); echo $foo
You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.

How do I get the full path to a Perl script that is executing?

#!/usr/bin/perl -w
use strict;


my $path = $0;
$path =~ s/\.\///g;
if ($path =~ /\//){
  if ($path =~ /^\//){
    $path =~ /^((\/[^\/]+){1,}\/)[^\/]+$/;
    $path = $1;
    }
  else {
    $path =~ /^(([^\/]+\/){1,})[^\/]+$/;
    my $path_b = $1;
    my $path_a = `pwd`;
    chop($path_a);
    $path = $path_a."/".$path_b;
    }
  }
else{
  $path = `pwd`;
  chop($path);
  $path.="/";
  }
$path =~ s/\/\//\//g;



print "\n$path\n";

:DD

Why has it failed to load main-class manifest attribute from a JAR file?

I got this error, and it was because I had the arguments in the wrong order:

CORRECT

java maui.main.Examples tagging -jar maui-1.0.jar 

WRONG

java -jar maui-1.0.jar maui.main.Examples tagging 

What languages are Windows, Mac OS X and Linux written in?

  • Windows: C++, kernel is in C
  • Mac: Objective C, kernel is in C (IO PnP subsystem is Embedded C++)
  • Linux: Most things are in C, many userland apps are in Python, KDE is all C++

All kernels will use some assembly code as well.

How to capture the android device screen content?

if you want to do screen capture from Java code in Android app AFAIK you must have Root provileges.

MVC Razor @foreach

What is the best practice on where the logic for the @foreach should be at?

Nowhere, just get rid of it. You could use editor or display templates.

So for example:

@foreach (var item in Model.Foos)
{
    <div>@item.Bar</div>
}

could perfectly fine be replaced by a display template:

@Html.DisplayFor(x => x.Foos)

and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }):

@model Foo
<div>@Model.Bar</div>

Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.

How to pass boolean parameter value in pipeline to downstream jobs?

Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).

How do I check if the mouse is over an element in jQuery?

Extending on what 'Happytime harry' said, be sure to use the .data() jquery function to store the timeout id. This is so that you can retrieve the timeout id very easily when the 'mouseenter' is triggered on that same element later, allowing you to eliminate the trigger for your tooltip to disappear.

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Plotting images side by side using matplotlib

You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)

For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html

How do I display the value of a Django form field in a template?

On Django 1.2, {{ form.data.field }} and {{ form.field.data }} are all OK, but not {{ form.field.value }}.
As others said, {{ form.field.value }} is Django 1.3+ only, but there's no specification in https://docs.djangoproject.com/en/1.3/topics/forms/. It can be found in https://docs.djangoproject.com/en/1.4/topics/forms/.

What is the right way to check for a null string in Objective-C?

If that kind of thing does not already exist, you can make an NSString category:

@interface NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty;

@end

@implementation NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty {
    return self == nil || [@"" isEqualToString:self];
}

@end

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/