Programs & Examples On #Selectedvalue

Difference between SelectedItem, SelectedValue and SelectedValuePath

Their names can be a bit confusing :). Here's a summary:

  • The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).

  • Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID', and then bind the SelectedValue property to the property on the DataContext (ie. the Product).

The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

<ComboBox ItemsSource="{Binding Categories}" 
          SelectedValue="{Binding CategoryID, Mode=TwoWay}" 
          SelectedValuePath="ID" 
          DisplayMemberPath="Name" />
public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Product
{
    public int CategoryID { get; set; }
}

It's a little confusing initially, but hopefully this makes it a bit clearer... :)

Chris

Getting selected value of a combobox

I had a similar error, My Class is

public class ServerInfo
{
    public string Text { get; set; }
    public string Value { get; set; }
    public string PortNo { get; set; }

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

But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.

// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;

I hope this helps someone! Cheers!

Removing duplicate objects with Underscore for Javascript

Here is a simple solution, which uses a deep object comparison to check for duplicates (without resorting to converting to JSON, which is inefficient and hacky)

var newArr = _.filter(oldArr, function (element, index) {
    // tests if the element has a duplicate in the rest of the array
    for(index += 1; index < oldArr.length; index += 1) {
        if (_.isEqual(element, oldArr[index])) {
            return false;
        }
    }
    return true;
});

It filters out all elements if they have a duplicate later in the array - such that the last duplicate element is kept.

The testing for a duplicate uses _.isEqual which performs an optimised deep comparison between the two objects see the underscore isEqual documentation for more info.

edit: updated to use _.filter which is a cleaner approach

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

Can not deserialize instance of java.lang.String out of START_OBJECT token

If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :

{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}

@JsonProperty("data")
    private JsonNode data;

How to get the cursor to change to the hand when hovering a <button> tag

 #more {
    background:none;
    border:none;
    color:#FFF;
    font-family:Verdana, Geneva, sans-serif;
    cursor: pointer;
}

Pretty printing XML with javascript

From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.

If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/> instruction:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applying this transformation on the provided XML document:

<root><node/></root>

most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:

<root>
  <node />
</root>

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

How to output HTML from JSP <%! ... %> block?

I suppose this would help:

<%! 
   String someOutput() {
     return "Some Output";
  }
%>
...
<%= someOutput() %>

Anyway, it isn't a good idea to have code in a view.

Pass props in Link react-router

For v5

 <Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

React Router Official Site

Count number of records returned by group by

Try this query:

select top 1 TotalRows = count(*) over () 
from yourTable
group by column1, column2

How can I check for "undefined" in JavaScript?

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

NSOperation vs Grand Central Dispatch

GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.

The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).

Javascript logical "!==" operator?

It's != without type coercion. See the MDN documentation for comparison operators.

Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with == and !=. (null == undefined, false == "0", etc.)

Short answer: always use === and !== unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)

Reset select value to default

If using Spring forms, you may need to reset the selected to your options label. You would set your form:select id value to an empty string resets your selection to the label as the default.

<form:select path="myBeanAttribute" id="my_select">
    <form:option value="" label="--Select One--"/>
    <form:options items="${mySelectionValueList}"/>
</form:select>

 $("#reset").on("click", function () {
        $("#my_select").val("");
 });

in the case where there's a reset button. Otherwise

$("#my_select").val("");

Python 3.1.1 string to hex

The easiest way to do it in Python 3.5 and higher is:

>>> 'halo'.encode().hex()
'68616c6f'

If you manually enter a string into a Python Interpreter using the utf-8 characters, you can do it even faster by typing b before the string:

>>> b'halo'.hex()
'68616c6f'

Equivalent in Python 2.x:

>>> 'halo'.encode('hex')
'68616c6f'

Node.js Mongoose.js string to ObjectId function

var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");

Hash string in c#

If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2" with "X2".)

public static string SHA256ToString(string s) 
{
    using (var alg = SHA256.Create())
        return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}

or:

public static string SHA256ToString(string s)
{            
    using (var alg = SHA256.Create())
        return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}

How to cast List<Object> to List<MyClass>

With Java 8 Streams:

Sometimes brute force casting is fine:

List<MyClass> mythings = (List<MyClass>) (Object) objects

But here's a more versatile solution:

List<Object> objects = Arrays.asList("String1", "String2");

List<String> strings = objects.stream()
                       .map(element->(String) element)
                       .collect(Collectors.toList());

There's a ton of benefits, but one is that you can cast your list more elegantly if you can't be sure what it contains:

objects.stream()
    .filter(element->element instanceof String)
    .map(element->(String)element)
    .collect(Collectors.toList());

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )

btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs

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

The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.

I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):

Syntax pitfalls of a function call

Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.

For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.

Text in HTML Field to disappear when clicked?

Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">

Printing image with PrintDocument. how to adjust the image to fit paper size

The solution provided by BBoy works fine. But in my case I had to use

e.Graphics.DrawImage(memoryImage, e.PageBounds);

This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!

Recursively find files with a specific extension

This q/a shows how to use find with regular expression: How to use regex with find command?

Pattern could be something like

'^Robert\\.\\(h|cgg\\)$'

Enum ToString with user friendly strings

You can use Humanizer package with Humanize Enums possiblity. An eaxample:

enum PublishStatusses
{
    [Description("Custom description")]
    NotCompleted,
    AlmostCompleted,
    Error
};

then you can use Humanize extension method on enum directly:

var st1 = PublishStatusses.NotCompleted;
var str1 = st1.Humanize(); // will result in Custom description

var st2 = PublishStatusses.AlmostCompleted;
var str2 = st2.Humanize(); // will result in Almost completed (calculated automaticaly)

Getting Index of an item in an arraylist;

.indexOf() works well. If you want an example here is one:

  ArrayList<String> example = new ArrayList<String>();
  example.add("AB");
  example.add("CD");
  example.add("EF");
  example.add("GH");
  example.add("IJ");
  example.add("KL");
  example.add("MN");

  System.out.println("Index of 'AB': "+example.indexOf("AB"));
  System.out.println("Index of 'KL': "+example.indexOf("KL"));
  System.out.println("Index of 'AA': "+example.indexOf("AA"));
  System.out.println("Index of 'EF': "+example.indexOf("EF"));

will give you an output of

Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

Note: This method returns -1 if the specified element is not present in the list.

Invoke-customs are only supported starting with android 0 --min-api 26

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

https://github.com/mapbox/mapbox-gl-native/issues/11378

Numpy Resize/Rescale Image

If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:

#simple image scaling to (nR x nC) size
def scale(im, nR, nC):
  nR0 = len(im)     # source number of rows 
  nC0 = len(im[0])  # source number of columns 
  return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]  
             for c in range(nC)] for r in range(nR)]

Example usage: resizing a (30 x 30) image to (100 x 200):

import matplotlib.pyplot as plt

def sqr(x):
  return x*x

def f(r, c, nR, nC):
  return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0

# a red circle on a canvas of size (nR x nC)
def circ(nR, nC):
  return [[ [f(r, c, nR, nC), 0, 0] 
             for c in range(nC)] for r in range(nR)]

plt.imshow(scale(circ(30, 30), 100, 200))

Output: scaled image

This works to shrink/scale images, and works fine with numpy arrays.

Npm Please try using this command again as root/administrator

I solve it running as administrator cmd. Cleaning the cache npm cache clean -f And then try to install the package again

How are software license keys generated?

Check tis article on Partial Key Verification which covers the following requirements:

  • License keys must be easy enough to type in.

  • We must be able to blacklist (revoke) a license key in the case of chargebacks or purchases with stolen credit cards.

  • No “phoning home” to test keys. Although this practice is becoming more and more prevalent, I still do not appreciate it as a user, so will not ask my users to put up with it.

  • It should not be possible for a cracker to disassemble our released application and produce a working “keygen” from it. This means that our application will not fully test a key for verification. Only some of the key is to be tested. Further, each release of the application should test a different portion of the key, so that a phony key based on an earlier release will not work on a later release of our software.

  • Important: it should not be possible for a legitimate user to accidentally type in an invalid key that will appear to work but fail on a future version due to a typographical error.

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

How to make layout with View fill the remaining space?

you can use high layout_weight attribute. Below you can see a layout where ListView takes all free space with buttons at bottom:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".ConfigurationActivity"
    android:orientation="vertical"
    >

        <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1000"
            />


        <Button
            android:id="@+id/btnCreateNewRule"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Create New Rule" />



        <Button
            android:id="@+id/btnConfigureOk"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Ok" />


</LinearLayout>

How to quickly drop a user with existing privileges

Also note, if you have explicitly granted:

CONNECT ON DATABASE xxx TO GROUP ,

you will need to revoke this separately from DROP OWNED BY, using:

REVOKE CONNECT ON DATABASE xxx FROM GROUP

IIS: Where can I find the IIS logs?

I think the Default place for IIS logging is: c:\inetpub\wwwroot\log\w3svc

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

A rather separable way of doing this is to use

import tensorflow as tf
from keras import backend as K

num_cores = 4

if GPU:
    num_GPU = 1
    num_CPU = 1
if CPU:
    num_CPU = 1
    num_GPU = 0

config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
                        inter_op_parallelism_threads=num_cores, 
                        allow_soft_placement=True,
                        device_count = {'CPU' : num_CPU,
                                        'GPU' : num_GPU}
                       )

session = tf.Session(config=config)
K.set_session(session)

Here, with booleans GPU and CPU, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU and num_CPU define this value. num_cores then sets the number of CPU cores available for usage via intra_op_parallelism_threads and inter_op_parallelism_threads.

The intra_op_parallelism_threads variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).

allow_soft_placement allows for operations to be run on the CPU if any of the following criterion are met:

  1. there is no GPU implementation for the operation

  2. there are no GPU devices known or registered

  3. there is a need to co-locate with other inputs from the CPU

All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.

Note: This requires tensorflow-gpu and cuda/cudnn to be installed because the option is given to use a GPU.

Refs:

Check if a string is null or empty in XSLT

If a node has no value available in the input xml like below xpath,

<node>
    <ErrorCode/>
</node>

string() function converts into empty value. So this works fine:

string(/Node/ErrorCode) =''

HTML5 and frameborder

How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="this.target='_blank'">?

  • onsomething = " this.frameborder = '0' "

<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>

Or getElementsByTagName]("iframe")1 adding this attribute for all iframes on the page?

Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)

How to uncheck checkbox using jQuery Uniform library

A simpler solution is to do this rather than using uniform:

$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1

This will not trigger any click action defined.

You can also use:

$('#check1').click(); // 

This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.

EDIT: jQuery 1.6+ uses prop() not attr() for checkboxes checked value

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Rock, Paper, Scissors Game Java

Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:

if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}
else 
     System.out.println("Invalid user input.");

Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:

if( /* insert your check for bad characters here */ ) { 
     System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

How do you check if a certain index exists in a table?

For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY built-in function:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )  

The simplest usage is with the IndexID property:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null

If the index exists, the above will return its ID; if it doesn't, it will return NULL.

Why is using a wild card with a Java import statement bad?

Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.

That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.

If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.

But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

Try this.

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var json = config.Formatters.JsonFormatter;
        json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }

        );
    }
}

Relative URLs in WordPress

I agree with Rup. I guess the main reason is to avoid confusion on relative paths. I think wordpress can work from scratch with relative paths but the problem might come when using multiple plugins, how the theme is configured etc.

I've once used this plugin for relative paths, when working on testing servers:

Root Relative URLs
Converts all URLs to root-relative URLs for hosting the same site on multiple IPs, easier production migration and better mobile device testing.

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

How to make borders collapse (on a div)?

Use simple negative margin rather than using display table.

Updated in fiddle JS Fiddle

.container { 
    border-style: solid;
    border-color: red;
    border-width: 1px 0 0 1px;
    display: inline-block;
}
.column { 
    float: left; overflow: hidden; 
}
.cell { 
    border: 1px solid red; width: 120px; height: 20px; 
    margin:-1px 0 0 -1px;
}
.clearfix {
    clear:both;
}

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

Unable to create migrations after upgrading to ASP.NET Core 2.0

You also can use in the startup class constructor to add json file (where the connection string lies) to the configuration. Example:

    IConfigurationRoot _config;
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        _config = builder.Build();
    }

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

Counting unique / distinct values by group in a data frame

Here is a benchmark of @David Arenburg's solution there as well as a recap of some solutions posted here (@mnel, @Sven Hohenstein, @Henrik):

library(dplyr)
library(data.table)
library(microbenchmark)
library(tidyr)
library(ggplot2)

df <- mtcars
DT <- as.data.table(df)
DT_32k <- rbindlist(replicate(1e3, mtcars, simplify = FALSE))
df_32k <- as.data.frame(DT_32k)
DT_32M <- rbindlist(replicate(1e6, mtcars, simplify = FALSE))
df_32M <- as.data.frame(DT_32M)
bench <- microbenchmark(
  base_32 = aggregate(hp ~ cyl, df, function(x) length(unique(x))),
  base_32k = aggregate(hp ~ cyl, df_32k, function(x) length(unique(x))),
  base_32M = aggregate(hp ~ cyl, df_32M, function(x) length(unique(x))),
  dplyr_32 = summarise(group_by(df, cyl), count = n_distinct(hp)),
  dplyr_32k = summarise(group_by(df_32k, cyl), count = n_distinct(hp)),
  dplyr_32M = summarise(group_by(df_32M, cyl), count = n_distinct(hp)),
  data.table_32 = DT[, .(count = uniqueN(hp)), by = cyl],
  data.table_32k = DT_32k[, .(count = uniqueN(hp)), by = cyl],
  data.table_32M = DT_32M[, .(count = uniqueN(hp)), by = cyl],
  times = 10
)

Results:

print(bench)

# Unit: microseconds
#            expr          min           lq         mean       median           uq          max neval  cld
#         base_32      816.153     1064.817 1.231248e+03 1.134542e+03     1263.152     2430.191    10 a   
#        base_32k    38045.080    38618.383 3.976884e+04 3.962228e+04    40399.740    42825.633    10 a   
#        base_32M 35065417.492 35143502.958 3.565601e+07 3.534793e+07 35802258.435 37015121.086    10    d
#        dplyr_32     2211.131     2292.499 1.211404e+04 2.370046e+03     2656.419    99510.280    10 a   
#       dplyr_32k     3796.442     4033.207 4.434725e+03 4.159054e+03     4857.402     5514.646    10 a   
#       dplyr_32M  1536183.034  1541187.073 1.580769e+06 1.565711e+06  1600732.034  1733709.195    10  b  
#   data.table_32      403.163      413.253 5.156662e+02 5.197515e+02      619.093      628.430    10 a   
#  data.table_32k     2208.477     2374.454 2.494886e+03 2.448170e+03     2557.604     3085.508    10 a   
#  data.table_32M  2011155.330  2033037.689 2.074020e+06 2.052079e+06  2078231.776  2189809.835    10   c 

Plot:

as_tibble(bench) %>% 
  group_by(expr) %>% 
  summarise(time = median(time)) %>% 
  separate(expr, c("framework", "nrow"), "_", remove = FALSE) %>% 
  mutate(nrow = recode(nrow, "32" = 32, "32k" = 32e3, "32M" = 32e6),
         time = time / 1e3) %>% 
  ggplot(aes(nrow, time, col = framework)) +
  geom_line() +
  scale_x_log10() +
  scale_y_log10() + ylab("microseconds")

aggregate-VS-dplyr-VS-datatable

Session info:

sessionInfo()
# R version 3.4.1 (2017-06-30)
# Platform: x86_64-pc-linux-gnu (64-bit)
# Running under: Linux Mint 18
# 
# Matrix products: default
# BLAS: /usr/lib/atlas-base/atlas/libblas.so.3.0
# LAPACK: /usr/lib/atlas-base/atlas/liblapack.so.3.0
# 
# locale:
# [1] LC_CTYPE=fr_FR.UTF-8       LC_NUMERIC=C               LC_TIME=fr_FR.UTF-8       
# [4] LC_COLLATE=fr_FR.UTF-8     LC_MONETARY=fr_FR.UTF-8    LC_MESSAGES=fr_FR.UTF-8   
# [7] LC_PAPER=fr_FR.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
# [10] LC_TELEPHONE=C             LC_MEASUREMENT=fr_FR.UTF-8 LC_IDENTIFICATION=C       
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# other attached packages:
# [1] ggplot2_2.2.1          tidyr_0.6.3            bindrcpp_0.2           stringr_1.2.0         
# [5] microbenchmark_1.4-2.1 data.table_1.10.4      dplyr_0.7.1           
# 
# loaded via a namespace (and not attached):
# [1] Rcpp_0.12.11     compiler_3.4.1   plyr_1.8.4       bindr_0.1        tools_3.4.1      digest_0.6.12   
# [7] tibble_1.3.3     gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.1      Matrix_1.2-10   
# [13] mvtnorm_1.0-6    grid_3.4.1       glue_1.1.1       R6_2.2.2         survival_2.41-3  multcomp_1.4-6  
# [19] TH.data_1.0-8    magrittr_1.5     scales_0.4.1     codetools_0.2-15 splines_3.4.1    MASS_7.3-47     
# [25] assertthat_0.2.0 colorspace_1.3-2 labeling_0.3     sandwich_2.3-4   stringi_1.1.5    lazyeval_0.2.0  
# [31] munsell_0.4.3    zoo_1.8-0 

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I've seen several answers and that's the only procedure that let me fix that without any conflicts.

If you want all changes from branch_new in branch_old, then:

git checkout branch_new
git merge -s ours branch_old
git checkout branch_old
git merge branch_new

once applied those four commands you can push the branch_old without any problem

How to check for null in Twig?

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

Android: No Activity found to handle Intent error? How it will resolve

Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this

try{

// your intent here

} catch (ActivityNotFoundException e) {
// show message to user 
}

SystemError: Parent module '' not loaded, cannot perform relative import

I had the same problem and I solved it by using an absolute import instead of a relative one.

for example in your case, you will write something like this:

from app.mymodule import myclass

You can see in the documentation.

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

Android check null or empty string in Android

if you check null or empty String so you can try this

if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
    DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

PHP If Statement with Multiple Conditions

Dont know, why you want to use &&. Theres an easier solution

echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
      ? 'yes' 
      : 'no';

What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

System.Net.Http: missing from namespace? (using .net 4.5)

To solve the problem :

  1. Go to your solution explorer.
  2. Right click on the project name and choose add
  3. Select references and allow the .Net framework 4.5 to finish loading
  4. Scroll down and select System.Net.Http and click ok.

Problem solved.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):

_x000D_
_x000D_
 <div class="container-fluid maxx">_x000D_
   <div class="row">_x000D_
     <div class="col-sm-12">_x000D_
     <p>Hello</p>_x000D_
     </div>_x000D_
   </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

  1. Then using specificity in the css part do this:

_x000D_
_x000D_
.container-fluid.maxx {_x000D_
  padding-left: 0px;_x000D_
  padding-right: 0px; }
_x000D_
_x000D_
_x000D_

This will work 100% and will remove the padding from left and right. I hope this helps.

How to convert java.util.Date to java.sql.Date?

You can use this method to convert util date to sql date,

DateUtilities.convertUtilDateToSql(java.util.Date)

Limit the size of a file upload (html input element)

_x000D_
_x000D_
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
  const target = event.target_x000D_
   if (target.files && target.files[0]) {_x000D_
_x000D_
      /*Maximum allowed size in bytes_x000D_
        5MB Example_x000D_
        Change first operand(multiplier) for your needs*/_x000D_
      const maxAllowedSize = 5 * 1024 * 1024;_x000D_
      if (target.files[0].size > maxAllowedSize) {_x000D_
       // Here you can ask your users to load correct file_x000D_
        target.value = ''_x000D_
      }_x000D_
  }_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
_x000D_
_x000D_

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:

  1. Move to the GitHub directory for your installation
  2. Run the GitHub command

Here is an example command to use in Jupyter:

%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show

Note you need to do the commands in the same cell.

How to insert a picture into Excel at a specified cell position with VBA

Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture in their code, only .Pictures.Insert()

Dim myPic As Object
Dim picpath As String

picpath = "C:\Users\photo.jpg" 'example photo path

Set myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)

With myPic
    .Width = 25
    .Height = 25
    .Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer
    .Left = xlApp.Cells(i, 20).Left
    .LockAspectRatio = msoFalse
End With

I'm working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture, because of error "Argument not optional". Looking at this You may ask why I set Height and Width as -1, but that doesn't matter cause of those parameters are set underneath between With brackets.

Hope it may be also useful for someone :)

Find the files existing in one directory but not in the other

Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.

Meld comparing directories

Get class name of object as string in Swift

To get the type name as a string in Swift 4 (I haven't checked the earlier versions), just use string interpolation:

"\(type(of: myViewController))"

You can use .self on a type itself, and the type(of:_) function on an instance:

// Both constants will have "UIViewController" as their value
let stringFromType = "\(UIViewController.self)"
let stringFromInstance = "\(type(of: UIViewController()))"

How to list the properties of a JavaScript object?

Use Reflect.ownKeys()

var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]

Object.keys and Object.getOwnPropertyNames cannot get non-enumerable properties. It's working even for non-enumerable properties.

var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]

Call async/await functions in parallel

I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.

wamp server mysql user id and password

Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link. alt text

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

How to add custom method to Spring Data JPA

You need to create a separate interface for your custom methods:

public interface AccountRepository 
    extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }

public interface AccountRepositoryCustom {
    public void customMethod();
}

and provide an implementation class for that interface:

public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @Autowired
    @Lazy
    AccountRepository accountRepository;  /* Optional - if you need it */

    public void customMethod() { ... }
}

See also:

How can I get the number of days between 2 dates in Oracle 11g?

This will work i have tested myself.
It gives difference between sysdate and date fetched from column admitdate

  TABLE SCHEMA:
    CREATE TABLE "ADMIN"."DUESTESTING" 
    (   
  "TOTAL" NUMBER(*,0), 
"DUES" NUMBER(*,0), 
"ADMITDATE" TIMESTAMP (6), 
"DISCHARGEDATE" TIMESTAMP (6)
    )

EXAMPLE:
select TO_NUMBER(trunc(sysdate) - to_date(to_char(admitdate, 'yyyy-mm-dd'),'yyyy-mm-dd')) from admin.duestesting where total=300

Getting all documents from one collection in Firestore

if you want include Id

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = querySnapshot.docs.map((doc) => {
        return { id: doc.id, ...doc.data() }
      })
      console.log(tempDoc)
    })
}

Same way with array

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = []
      querySnapshot.forEach((doc) => {
         tempDoc.push({ id: doc.id, ...doc.data() })
      })
      console.log(tempDoc)
   })
 }

How do I alias commands in git?

This will create an alias st for status:

git config --add alias.st status

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Using pip behind a proxy with CNTLM

A simpler approach might be:

  1. Create a folder named "pip" in your $HOME directory.
  2. Create a file named "pip.ini" (Windows) or "pip.conf" (Linux) in the directory created in step 1
  3. Copy & paste the following lines under the pip.ini/pip.conf:

    [global]
    trusted-host = pypi.python.org
                   pypi.org
                   files.pythonhosted.org 
    

How to get all privileges back to the root user in MySQL?

This worked for me on Ubuntu:

Stop MySQL server:

/etc/init.d/mysql stop

Start MySQL from the commandline:

/usr/sbin/mysqld

In another terminal enter mysql and issue:

grant all privileges on *.* to 'root'@'%' with grant option;

You may also want to add

grant all privileges on *.* to 'root'@'localhost' with grant option;

and optionally use a password as well.

flush privileges;

and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with

/etc/init.d/mysql start  

Get Hours and Minutes (HH:MM) from date

If you want to display 24 hours format use:

SELECT FORMAT(GETDATE(),'HH:mm')

and to display 12 hours format use:

SELECT FORMAT(GETDATE(),'hh:mm')

Find out whether radio button is checked with JQuery?

If you have a group of radio buttons sharing the same name attribute and upon submit or some event you want to check if one of these radio buttons was checked, you can do this simply by the following code :

$(document).ready(function(){
  $('#submit_button').click(function() {
    if (!$("input[name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });
});

Source

jQuery API Ref

Using 24 hour time in bootstrap timepicker

Use capitals letter for hours HH = 24 hour format an hh = 12 hour format

_x000D_
_x000D_
$('#fecha').datetimepicker({_x000D_
   format : 'DD/MM/YYYY HH:mm'_x000D_
});
_x000D_
_x000D_
_x000D_

Is there a way to specify a max height or width for an image?

editied to add support for ie6:

Try

<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />

This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

You can try this also:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

Extract the maximum value within each group in a dataframe

Using sqldf and standard sql to get the maximum values grouped by another variable

https://cran.r-project.org/web/packages/sqldf/sqldf.pdf

library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")

or

Using the excellent Hmisc package for a groupby application of function (max) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

library(Hmisc)
summarize(df1$Value,df1$Gene,max)

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Stretch horizontal ul to fit width of div

I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.

#horizontal-style {
  padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line 
  justify-content: space-around;
  display: flex;
}

#horizontal-style a {
    text-align: center;
    color: white;
    text-decoration: none;
}

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Another reason could be because the filepath is empty where you are trying to write which is why it can't find it. just another reason why this error occurs.

Add CSS or JavaScript files to layout head from views or partial views

Try the out-of-the-box solution (ASP.NET MVC 4 or later):

@{
    var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");

    bundle.Include("~/Scripts/myFile.js");
}

shell init issue when click tab, what's wrong with getcwd?

By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?

I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd which has issues with OverlayFS. I found information about this here:

It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.

http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204

You can configure and rebuild bash with bash_cv_getcwd_malloc=yes (if you're actually building bash and your C library does malloc a getcwd call).

DateTime "null" value

If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

How to get row number from selected rows in Oracle

you can just do

select rownum, l.* from student  l where name like %ram%

this assigns the row number as the rows are fetched (so no guaranteed ordering of course).

if you wanted to order first do:

select rownum, l.*
  from (select * from student l where name like %ram% order by...) l;

How to make a JTable non-editable

If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:

JTable table = new JTable(my_rows, my_header);

for (int c = 0; c < table.getColumnCount(); c++)
{
    Class<?> col_class = table.getColumnClass(c);
    table.setDefaultEditor(col_class, null);        // remove editor
}

Without editors, data will be not editable.

How to center the text in PHPExcel merged cell

if you want to align only this cells, you can do something like this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getStyle("A1:B1")->applyFromArray($style);

But, if you want to apply this style to all cells, try this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getDefaultStyle()->applyFromArray($style);

Returning a stream from File.OpenRead()

You forgot to seek:

str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

SQL how to make null values come last when sorting ascending

If you're using MariaDB, they mention the following in the NULL Values documentation.

Ordering

When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL. Example:

SELECT col1 FROM tab ORDER BY ISNULL(col1), col1;

Descending order, with NULLs first:

SELECT col1 FROM tab ORDER BY IF(col1 IS NULL, 0, 1), col1 DESC;

All NULL values are also regarded as equivalent for the purposes of the DISTINCT and GROUP BY clauses.

The above shows two ways to order by NULL values, you can combine these with the ASC and DESC keywords as well. For example the other way to get the NULL values first would be:

SELECT col1 FROM tab ORDER BY ISNULL(col1) DESC, col1;
--                                         ^^^^

C# adding a character in a string

Here is my solution, without overdoing it.

    private static string AppendAtPosition(string baseString, int position, string character)
    {
        var sb = new StringBuilder(baseString);
        for (int i = position; i < sb.Length; i += (position + character.Length))
            sb.Insert(i, character);
        return sb.ToString();
    }


    Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));

Change Image of ImageView programmatically in Android

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down);

Here's a thread that talks about the differences between the two methods.

Check if argparse optional argument is set or not

A custom action can handle this problem. And I found that it is not so complicated.

is_set = set() #global set reference
class IsStored(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        is_set.add(self.dest) # save to global reference
        setattr(namespace, self.dest + '_set', True) # or you may inject directly to namespace
        setattr(namespace, self.dest, values) # implementation of store_action
        # You cannot inject directly to self.dest until you have a custom class


parser.add_argument("--myarg", type=int, default=1, action=IsStored)
params = parser.parse_args()
print(params.myarg, 'myarg' in is_set)
print(hasattr(params, 'myarg_set'))

Connecting PostgreSQL 9.2.1 with Hibernate

Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.

enter image description here

How do I get countifs to select all non-blank cells in Excel?

If multiple criteria use countifs

=countifs(A1:A10,">""",B1:B10,">""")

The " >"" " looks at the greater than being empty. This formula looks for two criteria and neither column can be empty on the same row for it to count. If just counting one column do this with the one criteria (i.e. Use everything before B1:B10 not including the comma)

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How to resize html canvas element?

This worked for me just now:

<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.

The first syntax is already correct.

PHP - Get bool to echo false when false

This is the easiest way to do this:

$text = var_export($bool_value,true);
echo $text;

or

var_export($bool_value)

If the second argument is not true, it will output the result directly.

How to find out what the date was 5 days ago?

Simply do this...hope it help

$fifteendaysago = date_create('15 days ago');
echo date_format($fifteendaysago, 'Y-m-d');

Clearing content of text file using php

This would truncate the file:

$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);

In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

How to set a variable inside a loop for /F

I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2

What is does, is loop all the commandline params, and that set the variable with the proper name to the value.

After that, you can just use set value=!param1! set value2=!param2!

regardless the sequence the params are given. (so called named parameters). Note the !<>!, instead of the %<>%.

SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%P IN (%*) DO (
    call :processParam %%P
)

goto:End

:processParam [%1 - param]

    @echo "processparam : %1"
    FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
        @echo a,b %%G %%H
        set nameWithSlash=%%G
        set name=!nameWithSlash:~1!
        @echo n=!name!
        set value=%%H
        set !name!=!value!
    )
    goto :eof

:End    

Keyboard shortcut to change font size in Eclipse?

Eclipse Neon (4.6)

Zoom In

Ctrl++

or

Ctrl+=

Zoom Out

Ctrl+-

This feature is described here:

In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.

So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

Revert to a commit by a SHA hash in Git?

This might work:

git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit

Insert entire DataTable into database at once instead of row by row?

I would prefer user defined data type : it is super fast.

Step 1 : Create User Defined Table in Sql Server DB

CREATE TYPE [dbo].[udtProduct] AS TABLE(
  [ProductID] [int] NULL,
  [ProductName] [varchar](50) NULL,
  [ProductCode] [varchar](10) NULL
)
GO

Step 2 : Create Stored Procedure with User Defined Type

CREATE PROCEDURE ProductBulkInsertion 
@product udtProduct readonly
AS
BEGIN
    INSERT INTO Product
    (ProductID,ProductName,ProductCode)
    SELECT ProductID,ProductName,ProductCode
    FROM @product
END

Step 3 : Execute Stored Procedure from c#

SqlCommand sqlcmd = new SqlCommand("ProductBulkInsertion", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@product", productTable);
sqlcmd.ExecuteNonQuery();

Possible Issue : Alter User Defined Table

Actually there is no sql server command to alter user defined type But in management studio you can achieve this from following steps

1.generate script for the type.(in new query window or as a file) 2.delete user defied table. 3.modify the create script and then execute.

Why does AngularJS include an empty option in select?

Though both @pkozlowski.opensource's and @Mark's answers are correct, I'd like to share my slightly modified version where I always select the first item in the list, regardless of its value:

<select ng-options="option.value as option.name for option in typeOptions" ng-init="form.type=typeOptions[0].value">
</select>

Ruby on Rails: Where to define global constants?

I typically have a 'lookup' model/table in my rails program and use it for the constants. It is very useful if the constants are going to be different for different environments. In addition, if you have a plan to extend them, say you want to add 'yellow' on a later date, you could simply add a new row to the lookup table and be done with it.

If you give the admin permissions to modify this table, they will not come to you for maintenance. :) DRY.

Here is how my migration code looks like:

class CreateLookups < ActiveRecord::Migration
  def change
    create_table :lookups do |t|
      t.string :group_key
      t.string :lookup_key
      t.string :lookup_value
      t.timestamps
    end
  end
end

I use seeds.rb to pre-populate it.

Lookup.find_or_create_by_group_key_and_lookup_key_and_lookup_value!(group_key: 'development_COLORS', lookup_key: 'color1', lookup_value: 'red');

Xpath for href element

have you tried:

//a[@id='oldcontent']/u[text()='Re-Call']

What's the source of Error: getaddrinfo EAI_AGAIN?

In my case the problem was the docker networks ip allocation range, see this post for details

Meaning of 'const' last in a function declaration of a class?

When you add the const keyword to a method the this pointer will essentially become a pointer to const object, and you cannot therefore change any member data. (Unless you use mutable, more on that later).

The const keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const, and one that isn't.

#include <iostream>

class MyClass
{
private:
    int counter;
public:
    void Foo()
    { 
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

This will output

Foo
Foo const

In the non-const method you can change the instance members, which you cannot do in the const version. If you change the method declaration in the above example to the code below you will get some errors.

    void Foo()
    {
        counter++; //this works
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++; //this will not compile
        std::cout << "Foo const" << std::endl;
    }

This is not completely true, because you can mark a member as mutable and a const method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.

#include <iostream>

class MyClass
{
private:
    mutable int counter;
public:

    MyClass() : counter(0) {}

    void Foo()
    {
        counter++;
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++;    // This works because counter is `mutable`
        std::cout << "Foo const" << std::endl;
    }

    int GetInvocations() const
    {
        return counter;
    }
};

int main(void)
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
    std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}

which would output

Foo
Foo const
Foo has been invoked 2 times

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

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

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

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

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

Try Jochen Kalmbach's Memory Leak Detector on Code Project. The URL to the latest version was somewhere in the comments when I last checked.

Is there a replacement for unistd.h for Windows (Visual C)?

The equivalent of unistd.h on Windows is windows.h

Command to run a .bat file

There are many possibilities to solve this task.

1. RUN the batch file with full path

The easiest solution is running the batch file with full path.

"F:\- Big Packets -\kitterengine\Common\Template.bat"

Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.

The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:

cd /D "%~dp0"

Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.

Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.

2. CALL the batch file with full path

Another solution is calling the batch file with full path.

call "F:\- Big Packets -\kitterengine\Common\Template.bat"

The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.

For the current directory read above.

3. Change directory and RUN batch file with one command line

There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file

I suggest for this task the && operator.

cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat

As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.

4. Change directory and CALL batch file with one command line

This command line changes the directory and on success calls the batch file.

cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat

The difference to third solution is the return to current batch script on exiting processing of Template.bat.

5. Change directory and CALL batch file with keeping current environment with one command line

The four solutions above change the current directory and it is unknown what Template.bat does regarding

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.


ONE MORE NOTE

If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.

How could others, on a local network, access my NodeJS app while it's running on my machine?

put this codes in your server.js :

app.set('port', (80))
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'))
})

after that if you can't access app on network disable firewall like this :

enter image description here

Hide all warnings in ipython

The accepted answer does not work in Jupyter (at least when using some libraries).

The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.

%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
    var s='Showing';  
    cssrules.empty()
    if(on) {
        s='Hiding';
        cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
    }
    e.text(s+' warnings (click to toggle)');
    on=!on;
}).click();
$(element).append(e);
})(true);

@ variables in Ruby on Rails

Use @title in your controllers when you want your variable to be available in your views.

The explanation is that @title is an instance variable while title is a local variable. Rails makes instance variables from controllers available to views because the template code (erb, haml, etc) is executed within the scope of the current controller instance.

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

Round up to Second Decimal Place in Python

Note that the ceil(num * 100) / 100 trick will crash on some degenerate inputs, like 1e308. This may not come up often but I can tell you it just cost me a couple of days. To avoid this, "it would be nice if" ceil() and floor() took a decimal places argument, like round() does... Meanwhile, anyone know a clean alternative that won't crash on inputs like this? I had some hopes for the decimal package but it seems to die too:

>>> from math import ceil
>>> from decimal import Decimal, ROUND_DOWN, ROUND_UP
>>> num = 0.1111111111000
>>> ceil(num * 100) / 100
0.12
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
0.12
>>> num = 1e308
>>> ceil(num * 100) / 100
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
OverflowError: cannot convert float infinity to integer
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Of course one might say that crashing is the only sane behavior on such inputs, but I would argue that it's not the rounding but the multiplication that's causing the problem (that's why, eg, 1e306 doesn't crash), and a cleaner implementation of the round-up-nth-place fn would avoid the multiplication hack.

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

if statement in ng-click

This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

How can I use querySelector on to pick an input element by name?

querySelector() matched the id in document. You must write id of password in .html

Then pass it to querySelector() with #symbol & .value property.

Example:

let myVal = document.querySelector('#pwd').value

Insert variable into Header Location PHP

Try using double quotes and keeping the L in location lowercase...

header("location: http://linkhere.com/HERE_I_WANT_THE_VARIABLE");

or for example

header("location: http://linkhere.com/$variable");

No need to concatenate here to insert variables.

How to replace space with comma using sed?

If you are talking about sed, this works:

sed -e "s/ /,/g" < a.txt

In vim, use same regex to replace:

s/ /,/g

Disable scrolling in all mobile devices

cgvector answer didn't work for me, but this did:

document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });

I wouldn't leave it just like that, a smarter logic is needed to select when to prevent the scrolling, but this is a good start.

Taken from here: Disable scrolling in an iPhone web application?

SQL Query for Selecting Multiple Records

If you know the list of ids try this query:

SELECT * FROM `Buses` WHERE BusId IN (`list of busIds`)

or if you pull them from another table list of busIds could be another subquery:

SELECT * FROM `Buses` WHERE BusId IN (SELECT SomeId from OtherTable WHERE something = somethingElse)

If you need to compare to another table you need a join:

SELECT * FROM `Buses` JOIN OtheTable on Buses.BusesId = OtehrTable.BusesId

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Typically when you see this message, it is benign. If it says

INFO: validateJarFile(/<webapp>/WEB-INF/lib/servlet-api-2.5.jar) - jar not loaded. 
See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

It means it is ignoring your servlet-api-2.5.jar because tomcat already has a built-in version of that jar, so it isn't going to be using yours. Typically this doesn't cause an issue.

If however it says WEB-INF/lib/my_jar.jar - jar not loaded...Offending class: javax/servlet/Servlet.class

then what you can do (in my instance, it's a shaded jar) is run

$ mvn dependency:tree

and discover that you have a transitive dependency on "something" that depends on a jar that is either servlet-api or something like it (ex: tomcat-servlet-api-9.0.0). So add an exclusion to that to your pom, ex: (in my case, tomcat, in your case, probably the ones mentioned in the other answers):

 <dependency>
    ...
    <exclusions>
      <exclusion>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet</artifactId>
      </exclusion>
    </exclusions> 
</dependency>

Oracle insert from select into table with more columns

Just add in the '0' in your select.

INSERT INTO table_name (a,b,c,d)
    SELECT
       other_table.a AS a,
       other_table.b AS b,
       other_table.c AS c,
       '0' AS d
    FROM other_table

What does void do in java?

You mean the tellItLikeItIs method? Yes, you have to specify void to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void.

It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.

How to enter a formula into a cell using VBA?

I would do it like this:

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

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

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

how to download file in react js

I have the exact same problem, and here is the solution I make use of now: (Note, this seems ideal to me because it keeps the files closely tied to the SinglePageApplication React app, that loads from Amazon S3. So, it's like storing on S3, and in an application, that knows where it is in S3, relatively speaking.

Steps

3 steps:

  1. Make use of file saver in project: npmjs/package/file-saver (npm install file-saver or something)
  2. Place the file in your project You say it's in the components folder. Well, chances are if you've got web-pack it's going to try and minify it.(someone please pinpoint what webpack would do with an asset file in components folder), and so I don't think it's what you'd want. So, I suggest to place the asset into the public folder, under a resource or an asset name. Webpack doesn't touch the public folder and index.html and your resources get copied over in production build as is, where you may refer them as shown in next step.
  3. Refer to the file in your project Sample code:
    import FileSaver from 'file-saver';
    FileSaver.saveAs(
        process.env.PUBLIC_URL + "/resource/file.anyType",
        "fileNameYouWishCustomerToDownLoadAs.anyType");
    

Source

Appendix

The correct way to read a data file into an array

It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.

For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.

See the answer on reading line by line with perl if that's what you need.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Generate random numbers uniformly over an entire range

This is not the code, but this logic may help you.

static double rnd(void)
{
   return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())) );
}

static void InitBetterRnd(unsigned int seed)
{
    register int i;
    srand( seed );
    for( i = 0; i < POOLSIZE; i++){
        pool[i] = rnd();
    }
}

 // This function returns a number between 0 and 1
 static double rnd0_1(void)
 {
    static int i = POOLSIZE-1;
    double r;

    i = (int)(POOLSIZE*pool[i]);
    r = pool[i];
    pool[i] = rnd();
    return (r);
}

How to extract closed caption transcript from YouTube video?

Choose Open Transcript from the ... dropdown to the right of the vote up/down and share links.

This will open a Transcript scrolling div on the right side.

You can then use Copy. Note that you cannot use Select All but need to click the top line, then scroll to the bottom using the scroll thumb, and then shift-click on the last line.

Note that you can also search within this text using the normal web page search.

What's the most efficient way to test two integer ranges for overlap?

What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.

x1 <= C <= x2

and

y1 <= C <= y2

Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test

x1 <= y2 && y1 <= x2

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

This error pops up, if you try to create a web worker with data URI scheme.

var w = new Worker('data:text/javascript;charset=utf-8,onmessage%20%3D%20function()%20%7B%20postMessage(%22pong%22)%3B%20%7D'); w.postMessage('ping');

It's not allowed according to the standard: http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#dom-worker

Is there any way to change input type="date" format?

Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.

The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.

You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:

 <date-input date="{{date}}" timezone="[[timezone]]"></date-input>

or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)

Standards-compliant, no hacks.

Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It's 2018, so chances are it'll surely cover most of your users.

Hope it helps!

Find row in datatable with specific id

You can try with method select

DataRow[] rows = table.Select("ID = 7");

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

How do I use reflection to call a generic method?

Inspired by Enigmativity's answer - let's assume you have two (or more) classes, like

public class Bar { }
public class Square { }

and you want to call the method Foo<T> with Bar and Square, which is declared as

public class myClass
{
    public void Foo<T>(T item)
    {
        Console.WriteLine(typeof(T).Name);
    }
}

Then you can implement an Extension method like:

public static class Extension
{
    public static void InvokeFoo<T>(this T t)
    {
        var fooMethod = typeof(myClass).GetMethod("Foo");
        var tType = typeof(T);
        var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });
        fooTMethod.Invoke(new myClass(), new object[] { t });
    }
}

With this, you can simply invoke Foo like:

var objSquare = new Square();
objSquare.InvokeFoo();

var objBar = new Bar();
objBar.InvokeFoo();

which works for every class. In this case, it will output:

Square
Bar

C++ Array of pointers: delete or delete []?

It would make sens if your code was like this:

#include <iostream>

using namespace std;

class Monster
{
public:
        Monster() { cout << "Monster!" << endl; }
        virtual ~Monster() { cout << "Monster Died" << endl; }
};

int main(int argc, const char* argv[])
{
        Monster *mon = new Monster[6];

        delete [] mon;

        return 0;
}

Where is database .bak file saved from SQL Server Management Studio?

have you tried:

C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup

Script to get all backups in the last week can be found at:

http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html

I have plenty more backup SQL scripts there also at

http://wraithnath.blogspot.com/search/label/SQL

JavaScript: Check if mouse button down?

You can combine @Pax and my answers to also get the duration that the mouse has been down for:

var mousedownTimeout,
    mousedown = 0;

document.body.onmousedown = function() {
  mousedown = 0; 
  window.clearInterval(mousedownTimeout);
  mousedownTimeout = window.setInterval(function() { mousedown += 200 }, 200);
}

document.body.onmouseup = function() {
  mousedown = 0;
  window.clearInterval(mousedownTimeout);
}

Then later:

if (mousedown >= 2000) {
  // do something if the mousebutton has been down for at least 2 seconds
}

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method

//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);

You use this class for resize bitmap.

public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
 public static Bitmap scaleToFitWidth(Bitmap b, int width)
  {
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
  }


  // Scale and maintain aspect ratio given a desired height
  // BitmapScaler.scaleToFitHeight(bitmap, 100);
  public static Bitmap scaleToFitHeight(Bitmap b, int height)
  {
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
   }
 }

xml code is

<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />

Sql Server string to date conversion

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

Reference excel worksheet by name?

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub

Why is this jQuery click function not working?

Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

Problem solved. Here are the steps that I tried:

  • Enable the 32-bit application in IIS -> Application pool -> Advanced settings
  • Copy System.EnterpriseServices.dll and System.EnterpriseServices.Wrapper.dll from C:\Windows\Microsoft.NET\Framework\v2.0.50727 to the application bin folder
  • Do comments/uncomments to sections on the web.config and found that problem related to the referenced DLL.

The config that I commented the previous one that I added:

<section name="handlers" overrideModeDefault="Allow" /> 
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow"/>
  • Add the required FasterFlect.DLL used by Combres.DLL v2.1.0.0 to the application bin folder (shall download the full zip from Combres codeplex, because the required fasterflect DLL V2.0.3732.24338 cannot be found in fasterflect codeplex) and other DLLs. For convinience, use the full Combres.DLL (1,3MB)
  • Check that the DLL versions and public key tokens are configured correctly in web.config using tool, e.g. .NET Reflector

How can I access getSupportFragmentManager() in a fragment?

do this in your fragment

getActivity().getSupportFragmentManager()

Adding class to element using Angular JS

Use the MV* Pattern

Based on the example you attached, It's better in angular to use the following tools:

  • ng-click - evaluates the expression when the element is clicked (Read More)
  • ng-class - place a class based on the a given boolean expression (Read More)

for example:

<button ng-click="enabled=true">Click Me!</button>

<div ng-class="{'alpha':enabled}"> 
    ...
</div>

This gives you an easy way to decouple your implementation. e.g. you don't have any dependency between the div and the button.

Read this to learn about the MV* Pattern

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

How to remove class from all elements jquery

try: $(".highlight").removeClass("highlight");. By selecting $(".edgetoedge") you are only running functions at that level.

Grep and Python

The natural question is why not just use grep?! But assuming you can't...

import re
import sys

file = open(sys.argv[2], "r")

for line in file:
     if re.search(sys.argv[1], line):
         print line,

Things to note:

  • search instead of match to find anywhere in string
  • comma (,) after print removes carriage return (line will have one)
  • argv includes python file name, so variables need to start at 1

This doesn't handle multiple arguments (like grep does) or expand wildcards (like the Unix shell would). If you wanted this functionality you could get it using the following:

import re
import sys
import glob

for arg in sys.argv[2:]:
    for file in glob.iglob(arg):
        for line in open(file, 'r'):
            if re.search(sys.argv[1], line):
                print line,

How do I reverse an int array in Java?

Here is a condensed version:

My solution creates a new array reversed With each iteration of i the for loop inserts the last index [array.length - 1] into the current index [i] Then continues the same process by subtracting the current iteration array[(array.length - 1) - i] from the last index and inserting the element into the next index of the reverse array!

private static void reverse(int[] array) {
    int[] reversed = new int[array.length];

    for (int i = 0; i < array.length; i++) {
        reversed[i] = array[(array.length - 1) - i];
    }
    System.out.println(Arrays.toString(reversed));
}

How to make the division of 2 ints produce a float instead of another int?

Just cast one of the two operands to a float first.

v = (float)s / t;

The cast has higher precedence than the division, so happens before the division.

The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17

How to delete and recreate from scratch an existing EF Code First database

dbctx.Database.EnsureDeleted(); dbctx.Database.EnsureCreated();

How to delete all rows from all tables in a SQL Server database?

Set nocount on

Exec sp_MSForEachTable 'Alter Table ? NoCheck Constraint All'

Exec sp_MSForEachTable
'
If ObjectProperty(Object_ID(''?''), ''TableHasForeignRef'')=1
Begin
-- Just to know what all table used delete syntax.
Print ''Delete from '' + ''?''
Delete From ?
End
Else
Begin
-- Just to know what all table used Truncate syntax.
Print ''Truncate Table '' + ''?''
Truncate Table ?
End
'

Exec sp_MSForEachTable 'Alter Table ? Check Constraint All'

Php artisan make:auth command is not defined

If you using >5 version of laravel then you will use.

composer require laravel/ui --dev **or** composer require laravel/ui

And then

php artisan ui:auth

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

How to remove the first character of string in PHP?

To remove every : from the beginning of a string, you can use ltrim:

$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

I found this answer to the question:

http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html

Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.

The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.

The whole lot sits in an appasembly folder inside the target folder. Epic.

============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.

Select and display only duplicate records in MySQL

use this code

 SELECT *  
    FROM  paypal_ipn_orders 
    GROUP BY  payer_email  
    HAVING COUNT( payer_email) >1  

How to format numbers?

I think with this jQuery-numberformatter you could solve your problem.

Of course, this is assuming that you don't have problem with using jQuery in your project. Please notice that the functionality is tied to the blur event.

_x000D_
_x000D_
$("#salary").blur(function(){_x000D_
      $(this).parseNumber({format:"#,###.00", locale:"us"});_x000D_
      $(this).formatNumber({format:"#,###.00", locale:"us"});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/gh/timdown/jshashtable/hashtable.js"></script>_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/gh/hardhub/jquery-numberformatter/src/jquery.numberformatter.js"></script>_x000D_
_x000D_
<input type="text" id="salary">
_x000D_
_x000D_
_x000D_

How can I autoplay a video using the new embed code style for Youtube?

Just add ?autoplay=1 after url in embed code, example :

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>

Change it to:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>

ConfigurationManager.AppSettings - How to modify and save?

You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

How to disable the ability to select in a DataGridView?

I found setting all AllowUser... properties to false, ReadOnly to true, RowHeadersVisible to false, ScollBars to None, then faking the prevention of selection worked best for me. Not setting Enabled to false still allows the user to copy the data from the grid.

The following code also cleans up the look when you want a simple display grid (assuming rows are the same height):

int width = 0;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    width += dataGridView1.Columns[i].Width;
}

dataGridView1.Width = width;
dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1);

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

I was having similar issue and I think if we simply ignore the ssl verification will work like charm as it worked for me. So connecting to server with https scheme but directing them not to verify the certificate.

Using requests. Just mention verify=False instead of None

    requests.post(url, data=payload, headers=headers, verify=False)

Hoping this will work for those who needs :).

How to find a min/max with Ruby

You can use

[5,10].min 

or

[4,7].max

It's a method for Arrays.

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

Spring Boot: Cannot access REST Controller on localhost (404)

You need to modify the Starter-Application class as shown below.

@SpringBootApplication

@EnableAutoConfiguration

@ComponentScan(basePackages="com.nice.application")

@EnableJpaRepositories("com.spring.app.repository")

public class InventoryApp extends SpringBootServletInitializer {..........

And update the Controller, Service and Repository packages structure as I mentioned below.

Example: REST-Controller

package com.nice.controller; --> It has to be modified as
package com.nice.application.controller;

You need to follow proper package structure for all packages which are in Spring Boot MVC flow.

So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.

Failed to load c++ bson extension

I had this problem because I was including the node_modules folder in my Git repository. When I rebuilt the node_modules on the other system it worked. One of them was running Linux, the other OS X. Maybe they had different processor architectures as well.