Programs & Examples On #Ads

Ads is an abbreviation for Advertisements.

Detect Click into Iframe using JavaScript

Is something like this possible?

No. All you can do is detect the mouse going into the iframe, and potentially (though not reliably) when it comes back out (ie. trying to work out the difference between the pointer passing over the ad on its way somewhere else versus lingering on the ad).

I imagine a scenario where there is an invisible div on top of the iframe and the the div will just then pass the click event to the iframe.

Nope, there is no way to fake a click event.

By catching the mousedown you'd prevent the original click from getting to the iframe. If you could determine when the mouse button was about to be pressed you could try to get the invisible div out of the way so that the click would go through... but there is also no event that fires just before a mousedown.

You could try to guess, for example by looking to see if the pointer has come to rest, guessing a click might be about to come. But it's totally unreliable, and if you fail you've just lost yourself a click-through.

Label points in geom_point

Use geom_text , with aes label. You can play with hjust, vjust to adjust text position.

ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)

enter image description here

EDIT: Label only values above a certain threshold:

  ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +
  geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)

chart with conditional labels

Java regex capturing groups indexes

Parenthesis () are used to enable grouping of regex phrases.

The group(1) contains the string that is between parenthesis (.*) so .* in this case

And group(0) contains whole matched string.

If you would have more groups (read (...) ) it would be put into groups with next indexes (2, 3 and so on).

How do I list all the columns in a table?

The following code worked very well for me:

SELECT
       o.name as tableName,
       c.name as columnName,
       o.[type],
       s.name as schemaName,
       o.type_desc
FROM
       sys.objects AS o
       INNER JOIN sys.[columns] AS c ON c.[object_id] = o.[object_id]
       INNER JOIN sys.schemas AS s ON o.[schema_id] = s.[schema_id]
WHERE
       o.type_desc='USER_TABLE' 
       AND c.name='YourColumnName' --if comment this line,show all columns
ORDER BY
        o.name,
        c.column_id

you just replace your Column name with 'YourColumnName'. then run query

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

define a List like List<int,string>?

Since your example uses a generic List, I assume you don't need an index or unique constraint on your data. A List may contain duplicate values. If you want to insure a unique key, consider using a Dictionary<TKey, TValue>().

var list = new List<Tuple<int,string>>();

list.Add(Tuple.Create(1, "Andy"));
list.Add(Tuple.Create(1, "John"));
list.Add(Tuple.Create(3, "Sally"));

foreach (var item in list)
{
    Console.WriteLine(item.Item1.ToString());
    Console.WriteLine(item.Item2);
}

docker error: /var/run/docker.sock: no such file or directory

You, maybe the not the OP, but someone may have a directory called /var/run/docker.sock/ already due to how many times you hack and slash to get things right with docker (especially noobs). Delete that directory and try again.

This helped me on my way to getting it to work on Centos 7.

How can I add a volume to an existing Docker container?

I've successfully mount /home/<user-name> folder of my host to the /mnt folder of the existing (not running) container. You can do it in the following way:

  1. Open configuration file corresponding to the stopped container, which can be found at /var/lib/docker/containers/99d...1fb/config.v2.json (may be config.json for older versions of docker).

  2. Find MountPoints section, which was empty in my case: "MountPoints":{}. Next replace the contents with something like this (you can copy proper contents from another container with proper settings):

"MountPoints":{"/mnt":{"Source":"/home/<user-name>","Destination":"/mnt","RW":true,"Name":"","Driver":"","Type":"bind","Propagation":"rprivate","Spec":{"Type":"bind","Source":"/home/<user-name>","Target":"/mnt"},"SkipMountpointCreation":false}}

or the same (formatted):

  "MountPoints": {
    "/mnt": {
      "Source": "/home/<user-name>",
      "Destination": "/mnt",
      "RW": true,
      "Name": "",
      "Driver": "",
      "Type": "bind",
      "Propagation": "rprivate",
      "Spec": {
        "Type": "bind",
        "Source": "/home/<user-name>",
        "Target": "/mnt"
      },
      "SkipMountpointCreation": false
    }
  }
  1. Restart the docker service: service docker restart

This works for me with Ubuntu 18.04.1 and Docker 18.09.0

JavaScript: How do I print a message to the error console?

Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.

function log(msg) {
    setTimeout(function() {
        throw new Error(msg);
    }, 0);
}

Usage:

log('Hello World');
log('another message');

Calculating a directory's size using Python?

for python3.5+

from pathlib import Path

def get_size(path):
    return sum(p.stat().st_size for p in Path(path).rglob('*'))

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

form_for but to post to a different action

Alternatively the same can be reached using form_tag with the syntax:

form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'

As described in http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls

How do I suspend painting for a control and its children?

I usually use a little modified version of ngLink's answer.

public class MyControl : Control
{
    private int suspendCounter = 0;

    private void SuspendDrawing()
    {
        if(suspendCounter == 0) 
            SendMessage(this.Handle, WM_SETREDRAW, false, 0);
        suspendCounter++;
    }

    private void ResumeDrawing()
    {
        suspendCounter--; 
        if(suspendCounter == 0) 
        {
            SendMessage(this.Handle, WM_SETREDRAW, true, 0);
            this.Refresh();
        }
    }
}

This allows suspend/resume calls to be nested. You must make sure to match each SuspendDrawing with a ResumeDrawing. Hence, it wouldn't probably be a good idea to make them public.

isPrime Function for Python Language

No floating point operations are done below. This is faster and will tolerate higher arguments. The reason you must go only to the square-root is that if a number has a factor larger than its square root, it also has a factor smaller than it.

def is_prime(n):
    """"pre-condition: n is a nonnegative integer
    post-condition: return True if n is prime and False otherwise."""
    if n < 2: 
         return False;
    if n % 2 == 0:             
         return n == 2  # return False
    k = 3
    while k*k <= n:
         if n % k == 0:
             return False
         k += 2
    return True

Border in shape xml

If you want make a border in a shape xml. You need to use:

For the external border,you need to use:

<stroke/>

For the internal background,you need to use:

<solid/>

If you want to set corners,you need to use:

<corners/>

If you want a padding betwen border and the internal elements,you need to use:

<padding/>

Here is a shape xml example using the above items. It works for me

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="2dp" android:color="#D0CFCC" /> 
  <solid android:color="#F8F7F5" /> 
  <corners android:radius="10dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

How can I force WebKit to redraw/repaint to propagate style changes?

I stumbled upon this today: Element.redraw() for prototype.js

Using:

Element.addMethods({
  redraw: function(element){
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    (function(){n.parentNode.removeChild(n)}).defer();
    return element;
  }
});

However, I've noticed sometimes that you must call redraw() on the problematic element directly. Sometimes redrawing the parent element won't solve the problem the child is experiencing.

Good article about the way browsers render elements: Rendering: repaint, reflow/relayout, restyle

How to pass the password to su/sudo/ssh without overriding the TTY?

USE:

echo password | sudo command

Example:

echo password | sudo apt-get update; whoami

Hope It Helps..

What is the yield keyword used for in C#?

Here is a simple way to understand the concept: The basic idea is, if you want a collection that you can use "foreach" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).

Think of it this way: You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way). With yield, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I just had to uninstall HAXM and install it again. Then it started working again. Hope this helps someone!

Edit:

Oh wow, this was a long time ago. I have been using genymotion for a few months now, and never had any issues like that.

Copy entire contents of a directory to another using php

// using exec

function rCopy($directory, $destination)
{

    $command = sprintf('cp -r %s/* %s', $directory, $destination);

    exec($command);

}

Importing lodash into angular2 + typescript application

I am using ng2 with webpack, not system JS. Steps need for me were:

npm install underscore --save
typings install dt~underscore --global --save

and then in the file I wish to import underscore into:

import * as _ from 'underscore';

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

How to set timeout in Retrofit library?

I found this example

https://github.com/square/retrofit/issues/1557

Here we set custom url client connection client before before we build API rest service implementation.

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter


class ClientBuilder {

    public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
        Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()


        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
        RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(mCustomRetrofitEndpoint)
            .setConverter(new GsonConverter(gson))
            .setClient(new MyUrlConnectionClient())
        RestAdapter restAdapter = builder.build()
        return restAdapter.create(client)
    }
}

 public final class MyUrlConnectionClient extends UrlConnectionClient {
        @Override
        protected HttpURLConnection openConnection(Request request) {
            HttpURLConnection connection = super.openConnection(request);
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(30 * 1000);
            return connection;
        }
    }

Maven: How to include jars, which are not available in reps into a J2EE project?

None of the solutions work if you are using Jenkins build!! When pom is run inside Jenkins build server.. these solutions will fail, as Jenkins run pom will try to download these files from enterprise repository.

Copy jars under src/main/resources/lib (create lib folder). These will be part of your project and go all the way to deployment server. In deployment server, make sure your startup scripts contain src/main/resources/lib/* in classpath. Viola.

Get a list of all git commits, including the 'lost' ones

What saved my life was the following command:

git reflog

There you find a screen with history commits done to git like this one:

enter image description here

At this point, you only have to find the HEAD@{X} that you need, create a temporary branch and move to it like this:

git checkout -b temp_branch HEAD@{X}

That way you will have a temporary branch with your lost commit without rebasing or breaking even more your git repository.

Hope this helps...

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

One of the values you pass on to Ancestors becomes None at some point, it says, so check if otu, tree, tree[otu] or tree[otu][0] are None in the beginning of the function instead of only checking tree[otu][0][0] == None. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.

Can't find bundle for base name

BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:

$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties 
org/jfree/chart/LocalizationBundle.properties
org/jfree/chart/editor/LocalizationBundle.properties
org/jfree/chart/plot/LocalizationBundle.properties

Configuring user and password with Git Bash

From Git Bash I prefer to run the command:

git config --global credential.helper wincred

At that point running a command like git pull and entering your credentials one time should have it stored for future use. Git has a built-in credentials system that works in different OS environments. You can get more details here: 7.14 Git Tools - Credential Storage

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

C# Pass Lambda Expression as Method Parameter

You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action and Func.

In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

P.S. You should use PascalCase for method names - GetJobs, not getJobs.

Tomcat is web server or application server?

It runs Java compiled code, it can maintain database connection pools, it can log errors of various types. I'd call it an application server, in fact I do. In our environment we have Apache as the webserver fronting a number of different application servers, including Tomcat and Coldfusion, and others.

Options for HTML scraping?

Scrubyt uses Ruby and Hpricot to do nice and easy web scraping. I wrote a scraper for my university's library service using this in about 30 minutes.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

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

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

What is the difference between C and embedded C?

Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.

ant warning: "'includeantruntime' was not set"

As @Daniel Kutik mentioned, presetdef is a good option. Especially if one is working on a project with many build.xml files which one cannot, or prefers not to, edit (e.g., those from third-parties.)

To use presetdef, add these lines in your top-level build.xml file:

  <presetdef name="javac">
    <javac includeantruntime="false" />
  </presetdef>

Now all subsequent javac tasks will essentially inherit includeantruntime="false". If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true". The latter will also get rid of warnings.

Subsequent javac tasks can still explicitly change this if desired, for example:

<javac destdir="out" includeantruntime="true">
  <src path="foo.java" />
  <src path="bar.java" />
</javac>

I'd recommend against using ANT_OPTS. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS makes this even more likely because now every system needs to use ANT_OPTS in the same way. Also, ANT_OPTS will apply globally, suppressing warnings willy-nilly in all your projects

How to get a file directory path from file path?

If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.

if [ -h $file ]
then
 base=$(dirname $(readlink $file))
else
 base=$(dirname $file)
fi

Apache giving 403 forbidden errors

it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and

Require all granted

How to dockerize maven project? and how many ways to accomplish it?

Working example.

This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.

Question originally posted 4 years ago.

1. Generate an application

Use the spring initializer to generate a demo app

https://start.spring.io/

enter image description here

Extract the zip archive locally

2. Create a Dockerfile

#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]

Note

  • This example uses a multi-stage build. The first stage is used to build the code. The second stage only contains the built jar and a JRE to run it (note how jar is copied between stages).

3. Build the image

docker build -t demo .

4. Run the image

$ docker run --rm -it demo:latest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-22 17:18:57.835  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 0.711 seconds (JVM running for 1.035)

Misc

Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.

Update (2019-02-07)

This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.

Option 1: Multi-stage build

This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.

The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.

FROM maven:3.5-jdk-8 AS build  
COPY src /usr/src/app/src  
COPY pom.xml /usr/src/app  
RUN mvn -f /usr/src/app/pom.xml clean package

FROM gcr.io/distroless/java  
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar  
EXPOSE 8080  
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]  

Note:

  • I'm using Google's distroless base image, which strives to provide just enough run-time for a java app.

Option 2: Jib

I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)

https://github.com/GoogleContainerTools/jib

The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.


Original answer (Included for completeness, but written ages ago)

Try using the new official images, there's one for Maven

https://registry.hub.docker.com/_/maven/

The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.

Example 1 - Maven running within a container

The following command runs your Maven build inside a container:

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       maven:3.2-jdk-7 \
       mvn clean install

Notes:

  • The neat thing about this approach is that all software is installed and running within the container. Only need docker on the host machine.
  • See Dockerfile for this version

Example 2 - Use Nexus to cache files

Run the Nexus container

docker run -d -p 8081:8081 --name nexus sonatype/nexus

Create a "settings.xml" file:

<settings>
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://nexus:8081/content/groups/public/</url>
    </mirror>
  </mirrors>
</settings>

Now run Maven linking to the nexus container, so that dependencies will be cached

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       --link nexus:nexus \
       maven:3.2-jdk-7 \
       mvn -s settings.xml clean install

Notes:

  • An advantage of running Nexus in the background is that other 3rd party repositories can be managed via the admin URL transparently to the Maven builds running in local containers.

Append text to textarea with javascript

Tray to add text with html value to textarea but it wil not works

value :

$(document).on('click', '.edit_targets_btn', function() {
            $('#add_edit_targets').modal('show');
            $('#add_edit_targets_form')[0].reset();
            $('#targets_modal_title').text('Doel bijwerken');
            $('#action').val('targets_update');
            $('#targets_submit_btn').val('Opslaan');

            $('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
            $('#targets_title').val($(this).attr("title"));
            $("#targets_content").append($(this).attr("content"));

            tinymce.init({
                selector: '#targets_content',
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                },
                browser_spellcheck : true,
                plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
                toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
                relative_urls : false,
                remove_script_host : false,
                image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
                min_height: 250,
                branding: false
            });
        });

How to find nth occurrence of character in a string?

I made a few changes to aioobe's answer and got a nth lastIndexOf version, and fix some NPE problems. See code below:

public int nthLastIndexOf(String str, char c, int n) {
        if (str == null || n < 1)
            return -1;
        int pos = str.length();
        while (n-- > 0 && pos != -1)
            pos = str.lastIndexOf(c, pos - 1);
        return pos;
}

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

select DocumentFormat.OpenXml under references , view it's properties, and set the Copy Local option to True so that it copies it to the output folder. That worked for me.

Textarea that can do syntax highlighting on the fly?

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

_x000D_
_x000D_
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');


var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');
  }

  return text;
}

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);
  $highlights.html(highlightedText);
}

function handleScroll() {
  var scrollTop = $textarea.scrollTop();
  $backdrop.scrollTop(scrollTop);

  var scrollLeft = $textarea.scrollLeft();
  $backdrop.scrollLeft(scrollLeft);
}

function fixIOS() {
  $highlights.css({
    'padding-left': '+=3px',
    'padding-right': '+=3px'
  });
}

function bindEvents() {
  $textarea.on({
    'input': handleInput,
    'scroll': handleScroll
  });
}

if (isIOS) {
  fixIOS();
}

bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;
}

.container,
.backdrop,
textarea {
  width: 460px;
  height: 180px;
}

.highlights,
textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;
}

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;
}

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;
}

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;
}

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;
}

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  </div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
_x000D_
_x000D_

Original Pen: https://codepen.io/lonekorean/pen/gaLEMR

Memcached vs. Redis?

The biggest remaining reason is specialization.

Redis can do a lot of different things and one side effect of that is developers may start using a lot of those different feature sets on the same instance. If you're using the LRU feature of Redis for a cache along side hard data storage that is NOT LRU it's entirely possible to run out of memory.

If you're going to setup a dedicated Redis instance to be used ONLY as an LRU instance to avoid that particular scenario then there's not really any compelling reason to use Redis over Memcached.

If you need a reliable "never goes down" LRU cache...Memcached will fit the bill since it's impossible for it to run out of memory by design and the specialize functionality prevents developers from trying to make it so something that could endanger that. Simple separation of concerns.

What is the best way to calculate a checksum for a file that is on my machine?

I personally use Cygwin, which puts the entire smörgåsbord of Linux utilities at my fingertip --- there's md5sum and all the cryptographic digests supported by OpenSSL. Alternatively, you can also use a Windows distribution of OpenSSL (the "light" version is only a 1 MB installer).

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

PHP CURL Enable Linux

If anyone else stumbles onto this page from google like I did:

use putty (putty.exe) to sign into your server and install curl using this command :

    sudo apt-get install php5-curl

Make sure curl is enabled in the php.ini file. For me it's in /etc/php5/apache2/php.ini, if you can't find it, this line might be in /etc/php5/conf.d/curl.ini. Make sure the line :

    extension=curl.so

is not commented out then restart apache, so type this into putty:

    sudo /etc/init.d/apache2 restart

Info for install from https://askubuntu.com/questions/9293/how-do-i-install-curl-in-php5, to check if it works this stack overflow might help you: Detect if cURL works?

Custom header to HttpClient request

I have found the answer to my question.

client.DefaultRequestHeaders.Add("X-Version","1");

That should add a custom header to your request

tar: Error is not recoverable: exiting now

use sudo

sudo tar -zxvf xxxxxxxxx.tar.gz

Javascript: Easier way to format numbers?

Here's the YUI version if anyone's interested:

http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html

var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );

Validation of radio button group using jQuery validation plugin

I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:

        'highlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
                    $(this).addClass(errorClass);
                });
            } else {
                $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
                $(element).addClass(errorClass);
            }
        },
        'unhighlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
                    $(this).removeClass(errorClass);
                });
            }else {
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                $(element).removeClass(errorClass);
            }
        },

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

Centering a button vertically in table cell, using Twitter Bootstrap

Add vertical-align: middle; to the td element that contains the button

<td style="vertical-align:middle;">  <--add this to center vertically
  <a href="#" class="btn btn-primary">
    <i class="icon-check icon-white"></i>
  </a>
</td>

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Assume n=2. Then we have 2-1 = 1 on the left side and 2*1/2 = 1 on the right side.

Denote f(n) = (n-1)+(n-2)+(n-3)+...+1

Now assume we have tested up to n=k. Then we have to test for n=k+1.

on the left side we have k+(k-1)+(k-2)+...+1, so it's f(k)+k

On the right side we then have (k+1)*k/2 = (k^2+k)/2 = (k^2 +2k - k)/2 = k+(k-1)k/2 = kf(k)

So this have to hold for every k, and this concludes the proof.

Fade In Fade Out Android Animation in Java

Here is what I used to fade in/out Views, hope this helps someone.

private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
    AnimatorSet mAnimationSet = new AnimatorSet();
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA,  1f, 0f);
    fadeOut.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            fadeOutTarget.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    });
    fadeOut.setInterpolator(new LinearInterpolator());

    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
    fadeIn.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            fadeInTarget.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animator animation) {}

        @Override
        public void onAnimationCancel(Animator animation) {}

        @Override
        public void onAnimationRepeat(Animator animation) {}
    });
    fadeIn.setInterpolator(new LinearInterpolator());
    mAnimationSet.setDuration(duration);
    mAnimationSet.playTogether(fadeOut, fadeIn);
    mAnimationSet.start();
}

How to print a dictionary line by line in Python?

# Declare and Initialize Map
map = {}

map ["New"] = 1
map ["to"] = 1
map ["Python"] = 5
map ["or"] = 2

# Print Statement
for i in map:
  print ("", i, ":", map[i])

#  New : 1
#  to : 1
#  Python : 5
#  or : 2

show/hide html table columns using css

No, that's pretty much it. In theory you could use visibility: collapse on some <col>?s to do it, but browser support isn't all there.

To improve what you've got slightly, you could use table-layout: fixed on the <table> to allow the browser to use the simpler, faster and more predictable fixed-table-layout algorithm. You could also drop the .show rules as when a cell isn't made display: none by a .hide rule it will automatically be display: table-cell. Allowing table display to revert to default rather than setting it explicitly avoids problems in IE<8, where the table display values are not supported.

'cannot find or open the pdb file' Visual Studio C++ 2013

It worked for me. Go to Tools-> Options -> Debugger -> Native and check the Load DLL exports. Hope this helps

Does a favicon have to be 32x32 or 16x16?

May I remind everybody that the question was:

I'd like to use a single image as both a regular favicon and iPhone/iPad friendly favicon? Is this possible? Would an iPad-friendly 72x72 PNG scale if linked to as a regular browser favicon? Or do I have to use a separate 16x16 or 32x32 image?

The answer is: YES, that is possible! YES, it will be scaled. NO, you do not need a 'regular browser favicon'. Please look at this answer: https://stackoverflow.com/a/48646940/2397550

C++ performance vs. Java/C#

Actually Sun's HotSpot JVM uses "mixed-mode" execution. It interprets the method's bytecode until it determines (usually through a counter of some sort) that a particular block of code (method, loop, try-catch block, etc.) is going to be executed a lot, then it JIT compiles it. The time required to JIT compile a method often takes longer than if the method were to be interpreted if it is a seldom run method. Performance is usually higher for "mixed-mode" because the JVM does not waste time JITing code that is rarely, if ever, run. C# and .NET do not do this. .NET JITs everything which, often times, wastes time.

MySQL CURRENT_TIMESTAMP on create and on update

I would say you don't need to have the DEFAULT CURRENT_TIMESTAMP on your ts_update: if it is empty, then it is not updated, so your 'last update' is the ts_create.

using favicon with css

If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

Due to PermGen removal some options were removed (like -XX:MaxPermSize), but options -Xms and -Xmx work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC.

Note that if you use any option which was removed in Java 8, you will see a warning upon application start:

$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

Cannot use a leading ../ to exit above the top directory

I know these answers are enough, but I'll show the place that's throwing an error.

If you have the structure like the below:

  • ./Src/Master.cs - (Master Form Page)
  • ./Invoice/SubFolder/InvoiceEdit.aspx - (Sub Form Page)

If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png").

Now ResolveClientUrl is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png. This is the wrong way.

Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../.

enabling cross-origin resource sharing on IIS7

With ASP.net Web API 2 install Microsoft ASP.NET Cross Origin support via nuget.

http://enable-cors.org/server_aspnet.html

public static void Register(HttpConfiguration config)
{
 var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com",
                                                   "Origin, Content-Type, Accept",
                                                   "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
}

Why is using "for...in" for array iteration a bad idea?

Because it enumerates through object fields, not indexes. You can get value with index "length" and I doubt you want this.

How do I do a case-insensitive string comparison?

def insenStringCompare(s1, s2):
    """ Method that takes two strings and returns True or False, based
        on if they are equal, regardless of case."""
    try:
        return s1.lower() == s2.lower()
    except AttributeError:
        print "Please only pass strings into this method."
        print "You passed a %s and %s" % (s1.__class__, s2.__class__)

Insert new item in array on any position in PHP

You can try it, use this method to make it easy

/**
 * array insert element on position
 * 
 * @link https://vector.cool
 * 
 * @since 1.01.38
 *
 * @param array $original
 * @param mixed $inserted
 * @param int   $position
 * @return array
 */
function array_insert(&$original, $inserted, int $position): array
{
    array_splice($original, $position, 0, array($inserted));
    return $original;
}


$columns = [
    ['name' => '????', 'column' => 'item_name'],
    ['name' => '????', 'column' => 'start_time'],
    ['name' => '????', 'column' => 'full_name'],
    ['name' => '????', 'column' => 'phone'],
    ['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);

Print out:

Array
(
    [0] => Array
        (
            [name] => ????
            [column] => item_name
        )
    [1] => Array
        (
            [name] => ????
            [column] => start_time
        )
    [2] => Array
        (
            [name] => ????
            [column] => full_name
        )
    [3] => Array
        (
            [name] => ????1
            [column] => num_of_people
        )
    [4] => Array
        (
            [name] => ????
            [column] => phone
        )
    [5] => Array
        (
            [name] => ????
            [column] => user_id
        )
    [6] => Array
        (
            [name] => ????
            [column] => create_time
        )
)

How to change the default background color white to something else in twitter bootstrap

I'm using cdn boostrap, the solution that I found was: First include the cdn bootstrap, then you include the file .css where you are editing the default styles of bootstrap.

How do I count occurrence of duplicate items in array

I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);

Create a Bitmap/Drawable from file path

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

How to get a enum value from string in C#?

var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  

how to set default culture info for entire c# application

If you use a Language Resource file to set the labels in your application you need to set the its value:

CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

batch/bat to copy folder and content at once

For Folder Copy You can Use

robocopy C:\Source D:\Destination /E

For File Copy

copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y 

Delete file in some folder last modify date more than some day

forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"

And you can Shedule task in windows perform this task automatically in specific time.

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Get cursor position (in characters) within a text Input field

Got a very simple solution. Try the following code with verified result-

<html>
<head>
<script>
    function f1(el) {
    var val = el.value;
    alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
    <button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>

I'm giving you the fiddle_demo

Sort array of objects by string property value

Warning!
Using this solution is not recommended as it does not result in a sorted array. It is being left here for future reference, because the idea is not rare.

objs.sort(function(a,b){return b.last_nom>a.last_nom})

Sorting rows in a data table

Or, if you can use a DataGridView, you could just call Sort(column, direction):

namespace Sorter
{
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Add("Abc", 5);
            this.dataGridView1.Rows.Add("Def", 8);
            this.dataGridView1.Rows.Add("Ghi", 3);
            this.dataGridView1.Sort(this.dataGridView1.Columns[1], 
                                    ListSortDirection.Ascending);
        }
    }
}

Which would give you the desired result:

Debugger view

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

Andrey's above post is still valid for the latest version of Intellij as of 3rd Quarter of 2017. So use it. 'Cause, build project, and external command line gradle build, does NOT add it to the external dependencies in Intellij...crazy as that sounds it is true. Only difference now is that the UI looks different to the above, but still the same icon for updating is used. I am only putting an answer here, cause I cannot paste a snapshot of the new UI...I dont want any up votes per se. Andrey still gave the correct answer above: enter image description here

How to get start and end of day in Javascript?

If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60, 12 hours: 1000 * 60 * 60 * 12, etc.)

const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds

let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999

What does "commercial use" exactly mean?

Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.

To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.

Increment a Integer's int value?

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

No grammar constraints (DTD or XML schema) detected for the document

I too had the same problem in eclipse using web.xml file
it showed me this " no grammar constraints referenced in the document "

but it can be resolved by adding tag
after the xml tag i.e. <?xml version = "1.0" encoding = "UTF-8"?>

Which Eclipse version should I use for an Android app?

As of 10/2011 ... classic is fine for Android development.

See Compare Eclipse Packages for a nice chart.

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Best practice to look up Java Enum

update: As GreenTurtle correctly remarked, the following is wrong


I would just write

boolean result = Arrays.asList(FooEnum.values()).contains("Foo");

This is possibly less performant than catching a runtime exception, but makes for much cleaner code. Catching such exceptions is always a bad idea, since it is prone to misdiagnosis. What happens when the retrieval of the compared value itself causes an IllegalArgumentException ? This would then be treaten like a non matching value for the enumerator.

What is syntax for selector in CSS for next element?

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/

What's the best way to store a group of constants that my program uses?

An empty static class is appropriate. Consider using several classes, so that you end up with good groups of related constants, and not one giant Globals.cs file.

Additionally, for some int constants, consider the notation:

[Flags]
enum Foo
{
}

As this allows for treating the values like flags.

How can I clone a JavaScript object except for one key?

How about this:

let clone = Object.assign({}, value);
delete clone.unwantedKey;

Multi-dimensional associative arrays in JavaScript

Get the value for an array of associative arrays's property when the property name is an integer:

Starting with an Associative Array where the property names are integers:

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // log progress to the console
        console.log(categoryid + " : " + category);
        //  ... do something
    }
}

Console output should look like this:

1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.

What are projection and selection?

Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

How to get HTTP response code for a URL in Java?

This has worked for me :

            import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpGet;  
            import org.apache.http.impl.client.DefaultHttpClient;
            import org.apache.http.HttpResponse;
            import java.io.BufferedReader;
            import java.io.InputStreamReader;



            public static void main(String[] args) throws Exception {   
                        HttpClient client = new DefaultHttpClient();
                        //args[0] ="http://hostname:port/xyz/zbc";
                        HttpGet request1 = new HttpGet(args[0]);
                        HttpResponse response1 = client.execute(request1);
                        int code = response1.getStatusLine().getStatusCode();

                         try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
                            // Read in all of the post results into a String.
                            String output = "";
                            Boolean keepGoing = true;
                            while (keepGoing) {
                                String currentLine = br.readLine();          
                                if (currentLine == null) {
                                    keepGoing = false;
                                } else {
                                    output += currentLine;
                                }
                            }
                            System.out.println("Response-->"+output);   
                         }

                         catch(Exception e){
                              System.out.println("Exception"+e);  

                          }


                   }

Pass array to MySQL stored routine

Simply use FIND_IN_SET like that:

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
        -> 2

so you can do:

select * from Fruits where FIND_IN_SET(fruit, fruitArray) > 0

How to change background Opacity when bootstrap modal is open

you can set the opacity by the last parameter of rgb function.

the opacity is 0.5 in the example

.modal-backdrop {
    background-color: rgb(0, 0, 0, 0.5);
}

Oracle SQL Developer - tables cannot be seen

SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.

How to get access to HTTP header information in Spring MVC REST controller?

You can use HttpEntity to read both Body and Headers.

   @RequestMapping(value = "/restURL")
   public String serveRest(HttpEntity<String> httpEntity){
                MultiValueMap<String, String> headers = 
                httpEntity.getHeaders();
                Iterator<Map.Entry<String, List<String>>> s = 
                headers.entrySet().iterator();
                while(s.hasNext()) {
                    Map.Entry<String, List<String>> obj = s.next();
                    String key = obj.getKey();
                    List<String> value = obj.getValue();
                }
                
                String body = httpEntity.getBody();

    }

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

A python class that acts like dict

UserDict from the Python standard library is designed for this purpose.

Select Multiple Fields from List in Linq

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

Limit Decimal Places in Android EditText

This is to build on pinhassi's answer - the issue that I came across was that you couldn't add values before the decimal once the decimal limit has been reached. To fix the issue, we need to construct the final string before doing the pattern match.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.InputFilter;
import android.text.Spanned;

public class DecimalLimiter implements InputFilter
{
    Pattern mPattern;

    public DecimalLimiter(int digitsBeforeZero,int digitsAfterZero) 
    {
        mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero) + "}+((\\.[0-9]{0," + (digitsAfterZero) + "})?)||(\\.)?");
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) 
    {
        StringBuilder sb = new StringBuilder(dest);
        sb.insert(dstart, source, start, end);

        Matcher matcher = mPattern.matcher(sb.toString());
        if(!matcher.matches())
            return "";
        return null;
    }
}

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

This happens when you push first time without net connection or poor net connection.But when you try again using good connection 2,3 times problem will be solved.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Deserializing JSON array into strongly typed .NET object

try

List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);

How to add an Access-Control-Allow-Origin header

In your file.php of request ajax, can set value header.

<?php header('Access-Control-Allow-Origin: *'); //for all ?>

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Getting String value from enum in Java

You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

Powershell script to check if service is started, if not then start it

[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}

How to set-up a favicon?

you could take a look at the w3 how to, i think you will find it helpful

your link tag attribute should be rel="icon"

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

OSX -bash: composer: command not found

Globally install Composer on OS X 10.11 El Capitan

This command will NOT work in OS X 10.11:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/bin --filename=composer 

Instead, let's write to the /usr/local/bin path for the user:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Now we can access the composer command globally, just like before.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

This error happened to me, generally it'll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).

In my case, it was because of a problem on the OS.

I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I've tried the web server, it work perfectly the first time.

At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that "could" have this problem!

How do I remove a property from a JavaScript object?

Try the following method. Assign the Object property value to undefined. Then stringify the object and parse.

_x000D_
_x000D_
 var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};_x000D_
_x000D_
myObject.regex = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

How can I get zoom functionality for images?

UPDATE

I've just given TouchImageView a new update. It now includes Double Tap Zoom and Fling in addition to Panning and Pinch Zoom. The code below is very dated. You can check out the github project to get the latest code.

USAGE

Place TouchImageView.java in your project. It can then be used the same as ImageView. Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view. Example:

<com.example.touch.TouchImageView
    android:id="@+id/img”
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Note: I've removed my prior answer, which included some very old code and now link straight to the most updated code on github.

ViewPager

If you are interested in putting TouchImageView in a ViewPager, refer to this answer.

How to use "like" and "not like" in SQL MSAccess for the same field?

Try this:

filed like "*AA*" and filed not like "*BB*"

iOS: present view controller programmatically

The best way is

AddTaskViewController * add = [self.storyboard instantiateViewControllerWithIdentifier:@"addID"];
[self presentViewController:add animated:YES completion:nil];

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

Alarm Manager Example

This code will help you to make a repeating alarm. The repeating time can set by you.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" 
     android:background="#000000"
     android:paddingTop="100dp">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <EditText
        android:id="@+id/ethr"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Hr"
    android:singleLine="true" >


        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/etmin"
    android:layout_width="55dp"
    android:layout_height="wrap_content"

    android:ems="10"
    android:hint="Min"
    android:singleLine="true" />

    <EditText
        android:id="@+id/etsec"
    android:layout_width="50dp"
    android:layout_height="wrap_content"

    android:ems="10"
    android:hint="Sec"
    android:singleLine="true" />

    </LinearLayout>

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:gravity="center"
    android:paddingTop="10dp">


    <Button
        android:id="@+id/setAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickSetAlarm"
        android:text="Set Alarm" />

</LinearLayout>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity {
    int hr = 0;
    int min = 0;
    int sec = 0;
    int result = 1;

    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    BroadcastReceiver mReceiver;

    EditText ethr;
    EditText etmin;
    EditText etsec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ethr = (EditText) findViewById(R.id.ethr);
        etmin = (EditText) findViewById(R.id.etmin);
        etsec = (EditText) findViewById(R.id.etsec);
        RegisterAlarmBroadcast();
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    public void onClickSetAlarm(View v) {
        String shr = ethr.getText().toString();
        String smin = etmin.getText().toString();
        String ssec = etsec.getText().toString();

        if(shr.equals("")) 
            hr = 0;
        else {
            hr = Integer.parseInt(ethr.getText().toString());
            hr=hr*60*60*1000;
        }

        if(smin.equals(""))
            min = 0;
        else {
            min = Integer.parseInt(etmin.getText().toString());
            min = min*60*1000;
        }

        if(ssec.equals(""))
            sec = 0;
        else {
             sec = Integer.parseInt(etsec.getText().toString());
             sec = sec * 1000;
        }
        result = hr+min+sec;
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent); 
    }

    private void RegisterAlarmBroadcast() {
        mReceiver = new BroadcastReceiver() {
            // private static final String TAG = "Alarm Example Receiver";
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
            }
        };

        registerReceiver(mReceiver, new IntentFilter("sample"));
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
        alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
    }

    private void UnregisterAlarmBroadcast() {
        alarmManager.cancel(pendingIntent); 
        getBaseContext().unregisterReceiver(mReceiver);
    }
}

If you need alarm only for a single time then replace

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);

with

 alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );

PostgreSQL function for last inserted ID

Leonbloy's answer is quite complete. I would only add the special case in which one needs to get the last inserted value from within a PL/pgSQL function where OPTION 3 doesn't fit exactly.

For example, if we have the following tables:

CREATE TABLE person(
   id serial,
   lastname character varying (50),
   firstname character varying (50),
   CONSTRAINT person_pk PRIMARY KEY (id)
);

CREATE TABLE client (
    id integer,
   CONSTRAINT client_pk PRIMARY KEY (id),
   CONSTRAINT fk_client_person FOREIGN KEY (id)
       REFERENCES person (id) MATCH SIMPLE
);

If we need to insert a client record we must refer to a person record. But let's say we want to devise a PL/pgSQL function that inserts a new record into client but also takes care of inserting the new person record. For that, we must use a slight variation of leonbloy's OPTION 3:

INSERT INTO person(lastname, firstname) 
VALUES (lastn, firstn) 
RETURNING id INTO [new_variable];

Note that there are two INTO clauses. Therefore, the PL/pgSQL function would be defined like:

CREATE OR REPLACE FUNCTION new_client(lastn character varying, firstn character varying)
  RETURNS integer AS
$BODY$
DECLARE
   v_id integer;
BEGIN
   -- Inserts the new person record and retrieves the last inserted id
   INSERT INTO person(lastname, firstname)
   VALUES (lastn, firstn)
   RETURNING id INTO v_id;

   -- Inserts the new client and references the inserted person
   INSERT INTO client(id) VALUES (v_id);

   -- Return the new id so we can use it in a select clause or return the new id into the user application
    RETURN v_id;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;

Now we can insert the new data using:

SELECT new_client('Smith', 'John');

or

SELECT * FROM new_client('Smith', 'John');

And we get the newly created id.

new_client
integer
----------
         1

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml from a file deployed at http://run.jsbin.com due to the same-origin policy.


As the source (aka origin) page and the target URL are at different domains (run.jsbin.com and www.ecb.europa.eu), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.


Example:

A page at http://www.example.com/myPage.html can only directly request services that are at http://www.example.com, like http://www.example.com/api/myService. If the service is hosted at another domain (say http://www.ok.com/api/myService), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:

  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then
  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).


* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.


How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com it will only make regular calls to www.example.com! Other URLs, such as api.example.com or even example.com or www.example.com:8080 are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.

Access images inside public folder in laravel

You simply need to use the asset helper function in Laravel. (The url helper can also be used in this manner)

<img src="{{ asset('images/arrow.gif') }}" />

For the absolute path, you use public_path instead.

<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>

If you are providing the URL to a public image from a controller (backend) you can use asset as well, or secure_asset if you want HTTPS. eg:

$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif

return $secure_url;

Lastly, if you want to go directly to the image on a given route you can redirect to it:

return \Redirect::to($secure_url);

More Laravel helper functions can be found here

Pandas "Can only compare identically-labeled DataFrame objects" error

Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

One solution is to sort the index first (Note: some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

Note: == is also sensitive to the order of columns, so you may have to use sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

Note: This can still raise (if the index/columns aren't identically labelled after sorting).

How can I use Ruby to colorize the text output to a terminal?

I made this method that could help. It is not a big deal but it works:

def colorize(text, color = "default", bgColor = "default")
    colors = {"default" => "38","black" => "30","red" => "31","green" => "32","brown" => "33", "blue" => "34", "purple" => "35",
     "cyan" => "36", "gray" => "37", "dark gray" => "1;30", "light red" => "1;31", "light green" => "1;32", "yellow" => "1;33",
      "light blue" => "1;34", "light purple" => "1;35", "light cyan" => "1;36", "white" => "1;37"}
    bgColors = {"default" => "0", "black" => "40", "red" => "41", "green" => "42", "brown" => "43", "blue" => "44",
     "purple" => "45", "cyan" => "46", "gray" => "47", "dark gray" => "100", "light red" => "101", "light green" => "102",
     "yellow" => "103", "light blue" => "104", "light purple" => "105", "light cyan" => "106", "white" => "107"}
    color_code = colors[color]
    bgColor_code = bgColors[bgColor]
    return "\033[#{bgColor_code};#{color_code}m#{text}\033[0m"
end

Here's how to use it:

puts "#{colorize("Hello World")}"
puts "#{colorize("Hello World", "yellow")}"
puts "#{colorize("Hello World", "white","light red")}"

Possible improvements could be:

  • colors and bgColors are being defined each time the method is called and they don't change.
  • Add other options like bold, underline, dim, etc.

This method does not work for p, as p does an inspect to its argument. For example:

p "#{colorize("Hello World")}"

will show "\e[0;38mHello World\e[0m"

I tested it with puts, print, and the Logger gem, and it works fine.


I improved this and made a class so colors and bgColors are class constants and colorize is a class method:

EDIT: Better code style, defined constants instead of class variables, using symbols instead of strings, added more options like, bold, italics, etc.

class Colorizator
    COLOURS = { default: '38', black: '30', red: '31', green: '32', brown: '33', blue: '34', purple: '35',
                cyan: '36', gray: '37', dark_gray: '1;30', light_red: '1;31', light_green: '1;32', yellow: '1;33',
                light_blue: '1;34', light_purple: '1;35', light_cyan: '1;36', white: '1;37' }.freeze
    BG_COLOURS = { default: '0', black: '40', red: '41', green: '42', brown: '43', blue: '44',
                   purple: '45', cyan: '46', gray: '47', dark_gray: '100', light_red: '101', light_green: '102',
                   yellow: '103', light_blue: '104', light_purple: '105', light_cyan: '106', white: '107' }.freeze

    FONT_OPTIONS = { bold: '1', dim: '2', italic: '3', underline: '4', reverse: '7', hidden: '8' }.freeze

    def self.colorize(text, colour = :default, bg_colour = :default, **options)
        colour_code = COLOURS[colour]
        bg_colour_code = BG_COLOURS[bg_colour]
        font_options = options.select { |k, v| v && FONT_OPTIONS.key?(k) }.keys
        font_options = font_options.map { |e| FONT_OPTIONS[e] }.join(';').squeeze
        return "\e[#{bg_colour_code};#{font_options};#{colour_code}m#{text}\e[0m".squeeze(';')
    end
end

You can use it by doing:

Colorizator.colorize "Hello World", :gray, :white
Colorizator.colorize "Hello World", :light_blue, bold: true
Colorizator.colorize "Hello World", :light_blue, :white, bold: true, underline: true

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

selecting unique values from a column

The rest are almost correct, except they should order by Date DESC

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

A cycle was detected in the build path of project xxx - Build Path Problem

When we have multiple projects in workspace, we have to set the references between the projects, not among the projects. If P1 references P2, P2 references P3, and P3 reference back to P1. That will cause a cycle.

The Solution is to draw a Diagram of the reference between projects in workspace. Check the Java Build Path of each of the projects to see the Tab of the Projects window. Take out the Project that are refering back to the main project, e.g. P3 references P1, in this example above.

Detailed operation is to select P3 project in RAD OR eclipse, right click on the project and choose the properties option, it brings up a new window for properties of P3. Click on the "Java Build Path" section, Choose the "Projects" option Tab. You can see the P3 has referenced P1 in the field. Select the P1 reference, click "Remove" button on the right side of the window. Then, click okay. The IDE will start to reset the path automatically.

Done.

Keep find all of the mis-referenced reference in every each projects until you have the right references to each of the projects in your Diagram. Good Luck!

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

When is a CDATA section necessary within a script tag?

Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:

if (a &gt; b) alert('hello world');

But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.

This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.

Get single row result with Doctrine NativeQuery

To fetch single row

$result = $this->getEntityManager()->getConnection()->fetchAssoc($sql)

To fetch all records

$result = $this->getEntityManager()->getConnection()->fetchAll($sql)

Here you can use sql native query, all will work without any issue.

How to detect if CMD is running as Administrator/has elevated privileges?

This trick only requires one command: type net session into the command prompt.

If you are NOT an admin, you get an access is denied message.

System error 5 has occurred.

Access is denied.

If you ARE an admin, you get a different message, the most common being:

There are no entries in the list.

From MS Technet:

Used without parameters, net session displays information about all sessions with the local computer.

Trying to add adb to PATH variable OSX

If anyone can't seem to get there .bash_profile file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.

That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.

How to update (append to) an href in jquery?

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.

Example:

<div class="editor-field">
    <%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
    <%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>

Here's a more specific example:

I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).

I made the following model:

namespace DeleteMeQuestion.Models
{
    public class QuizModel
    {
        public int ParentQuestionId { get; set; }
        public int QuestionId { get; set; }
        public string QuestionDisplayText { get; set; }
        public List<Response> Responses { get; set; }

        [Range(1,999, ErrorMessage = "Please choose a response.")]
        public int SelectedResponse { get; set; }
    }

    public class Response
    {
        public int ResponseId { get; set; }
        public int ChildQuestionId { get; set; }
        public string ResponseDisplayText { get; set; }
    }
}

There's a simple range validator in the model, just for fun. Next up, I made the following controller:

namespace DeleteMeQuestion.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            // TODO: get question to show based on method parameter 
            var model = GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(int? id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return View(freshModel);
            }

            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)

            var nextQuestionId = 999;
            return RedirectToAction("Index", "Home", new {id = nextQuestionId});
        }

        private QuizModel GetModel(int? questionId)
        {
            // just a stub, in lieu of a database

            var model = new QuizModel
            {
                QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
                QuestionId = 1,
                Responses = new List<Response>
                                                {
                                                    new Response
                                                        {
                                                            ChildQuestionId = 2,
                                                            ResponseId = 1,
                                                            ResponseDisplayText = "Red"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 3,
                                                            ResponseId = 2,
                                                            ResponseDisplayText = "Blue"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 4,
                                                            ResponseId = 3,
                                                            ResponseDisplayText = "Green"
                                                        },
                                                }
            };

            return model;
        }
    }
}

Finally, I made the following view that makes use of the model:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) { %>

        <div>

            <h1><%: Model.QuestionDisplayText %></h1>

            <div>
            <ul>
            <% foreach (var item in Model.Responses) { %>
                <li>
                    <%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
                    <label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
                </li>
            <% } %>
            </ul>

            <%= Html.ValidationMessageFor(m => m.SelectedResponse) %>

        </div>

        <input type="submit" value="Submit" />

    <% } %>

</asp:Content>

As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.

This gives you the radio buttons with the same name attribute, but different ID attributes.

The PowerShell -and conditional operator

The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

Call fragment from fragment

In MainActivity

private static android.support.v4.app.FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                     

    fragmentManager = getSupportFragmentManager();                                                                 


    }

public void secondFragment() {

    fragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.right_enter, R.anim.left_out)
            .replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
            .commit();
}

In FirstFragment call SecondFrgment Like this:

new MainActivity().secondFragment();

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

Check if a variable is a string in JavaScript

I recommend using the built-in functions from jQuery or lodash/Underscore. They're simpler to use and easier to read.

Either function will handle the case DRAX mentioned... that is, they both check if (A) the variable is a string literal or (B) it's an instance of the String object. In either case, these functions correctly identify the value as being a string.

lodash / Underscore.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else

jQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else

See lodash Documentation for _.isString() for more details.

See jQuery Documentation for $.type() for more details.

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

Google Colab: how to read data from my google drive?

You can simply make use of the code snippets on the left of the screen. enter image description here

Insert "Mounting Google Drive in your VM"

run the code and copy&paste the code in the URL

and then use !ls to check the directories

!ls /gdrive

for most cases, you will find what you want in the directory "/gdrive/My drive"

then you may carry it out like this:

from google.colab import drive
drive.mount('/gdrive')
import glob

file_path = glob.glob("/gdrive/My Drive/***.txt")
for file in file_path:
    do_something(file)

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

Reset CSS display property to default value

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

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

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

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

Specifying maxlength for multiline textbox

try this javascript:

function checkTextAreaMaxLength(textBox,e, length)
{

        var mLen = textBox["MaxLength"];
        if(null==mLen)
            mLen=length;

        var maxLength = parseInt(mLen);
        if(!checkSpecialKeys(e))
        {
         if(textBox.value.length > maxLength-1)
         {
            if(window.event)//IE
              e.returnValue = false;
            else//Firefox
                e.preventDefault();
         }
    }   
}
function checkSpecialKeys(e)
{
    if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
        return false;
    else
        return true;
}

On the control invoke it like this:

<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');"  TextMode="multiLine" runat="server"> </asp:TextBox>

You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.

How to know if a Fragment is Visible?

getUserVisibleHint() comes as true only when the fragment is on the view and visible

CSS: Change image src on img:hover

The following code works at both Chrome and Firefox

<a href="#"><img src="me-more-smile.jpg" onmouseover="this.src='me-thinking-about-a-date.jpg'" onmouseout="this.src='me-more-smile.jpg'" border="0" alt=""/></a>

How to "wait" a Thread in Android

Don't use wait(), use either android.os.SystemClock.sleep(1000); or Thread.sleep(1000);.

The main difference between them is that Thread.sleep() can be interrupted early -- you'll be told, but it's still not the full second. The android.os call will not wake early.

Update TensorFlow

For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge. Then simply do:

conda update -f -c conda-forge tensorflow

This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Centering text in a table in Twitter Bootstrap

add:

<p class="text-center"> Your text here... </p>

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

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

Try this..

  1. Download the Sqlite Manager jar file here.

  2. Add it to your eclipse > dropins Directory.

  3. Restart eclipse.

  4. Launch the compatible emulator or device

  5. Run your application.

  6. Go to Window > Open Perspective > DDMS >

  7. Choose the running device.

  8. Go to File Explorer tab.

  9. Select the directory called databases under your application's package.

  10. Select the .db file under the database directory.

  11. Then click Sqlite manager icon like this Sqlite manager icon.

  12. Now you're able to see the .db file.

Happy coding.....

TortoiseGit-git did not exit cleanly (exit code 1)

I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.

How do I replace a character at a particular index in JavaScript?

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

And use it like this:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // Should display He!!o World

Align image to left of text on same line - Twitter Bootstrap3

Using Twitter Bootstrap classes may be the best choice :

  • pull-left makes an element floating left
  • clearfix allows the element to contain floating elements (if not already set via another class)
<div class="paragraphs">
  <div class="row">
    <div class="span4">
      <div class="clearfix content-heading">
          <img class="pull-left" src="../site/img/success32.png"/>
          <h3>Experience &nbsp </h3>
      </div>
      <p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

How to reset index in a pandas dataframe?

data1.reset_index(inplace=True)

How to find good looking font color if background color is known?

I have implemented something similar for a different reason - that was code to tell the end user whether the foreground and background colors that they selected would result in unreadable text. To do this, rather than examining the RGB values, I converted the color value to HSL/HSV and then determined by experimentation what my cutoff point was for readability when comparing the fg and bg values. This is something you may want/need to consider.

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111 check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null

How do I loop through items in a list box and then remove those item?

Do you want to remove all items? If so, do the foreach first, then just use Items.Clear() to remove all of them afterwards.

Otherwise, perhaps loop backwards by indexer:

listBox1.BeginUpdate();
try {
  for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
    // do with listBox1.Items[i]

    listBox1.Items.RemoveAt(i);
  }
} finally {
  listBox1.EndUpdate();
}

Changing website favicon dynamically

The only way to make this work for IE is to set you web server to treat requests for *.ico to call your server side scripting language (PHP, .NET, etc). Also setup *.ico to redirect to a single script and have this script deliver the correct favicon file. I'm sure there is still going to be some interesting issues with cache if you want to be able to bounce back and forth in the same browser between different favicons.

Replace words in a string - Ruby

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https

SQL update trigger only when column is modified

You want to do the following:

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS 
BEGIN
SET NOCOUNT ON;

    IF (UPDATE(QtyToRepair))
    BEGIN
        UPDATE SCHEDULE SET modified = GETDATE()
            , ModifiedUser = SUSER_NAME()
            , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END
END

Please note that this trigger will fire each time you update the column no matter if the value is the same or not.

Why doesn't TFS get latest get the latest?

TFS, like some other source control providers, such as Perforce, do this, as the system knows what the last version you successfully got was, so get latest turns into "get changes since x". If you play by its rules and actually check things out before editing them, you don't confuse matters, and "get latest" really does as it says.

As you've seen, you can force it to reassess everything, which has a much greater bandwidth usage, but behaves closer to how SourceSafe used to.

How to shift a block of code left/right by one space in VSCode?

There was a feature request for that in vscode repo. But it was marked as extension-candidate and closed. So, here is the extension: Indent One space

Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.

enter image description here

Does swift have a trim method on String?

I created this function that allows to enter a string and returns a list of string trimmed by any character

 func Trim(input:String, character:Character)-> [String]
{
    var collection:[String] = [String]()
    var index  = 0
    var copy = input
    let iterable = input
    var trim = input.startIndex.advancedBy(index)

    for i in iterable.characters

    {
        if (i == character)
        {

            trim = input.startIndex.advancedBy(index)
            // apennding to the list
            collection.append(copy.substringToIndex(trim))

            //cut the input
            index += 1
            trim = input.startIndex.advancedBy(index)
            copy = copy.substringFromIndex(trim)

            index = 0
        }
        else
        {
            index += 1
        }
    }
    collection.append(copy)
    return collection

}

as didn't found a way to do this in swift (compiles and work perfectly in swift 2.0)

How to recover stashed uncommitted changes

To make this simple, you have two options to reapply your stash:

  1. git stash pop - Restore back to the saved state, but it deletes the stash from the temporary storage.
  2. git stash apply - Restore back to the saved state and leaves the stash list for possible later reuse.

You can read in more detail about git stashes in this article.

Get Substring - everything before certain char

One way to do this is to use String.Substring together with String.IndexOf:

int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
    sub = str.Substring(0, index);
}
else
{
    sub = ... // handle strings without the dash
}

Starting at position 0, return all text up to, but not including, the dash.

jQuery: How to get to a particular child of a parent?

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")

Run certain code every n seconds

Here is a simple example compatible with APScheduler 3.00+:

# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()

def some_job():
    print('Every 10 seconds')

# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()

...

sched.shutdown()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

import time
from threading import Event, Thread

class RepeatedTimer:

    """Repeat `function` every `interval` seconds."""

    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start = time.time()
        self.event = Event()
        self.thread = Thread(target=self._target)
        self.thread.start()

    def _target(self):
        while not self.event.wait(self._time):
            self.function(*self.args, **self.kwargs)

    @property
    def _time(self):
        return self.interval - ((time.time() - self.start) % self.interval)

    def stop(self):
        self.event.set()
        self.thread.join()


# start timer
timer = RepeatedTimer(10, print, 'Hello world')

# stop timer
timer.stop()

Babel command not found

Worked for me e.g.

./node_modules/.bin/babel --version
./node_modules/.bin/babel src/main.js

How can I use "e" (Euler's number) and power operation in python 2.7

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Refreshing all the pivot tables in my excel workbook with a macro

I have use the command listed below in the recent past and it seems to work fine.

ActiveWorkbook.RefreshAll

Hope that helps.

How to free memory from char array in C

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

Reload an iframe with jQuery

    ifrX =document.getElementById('id') //or 
    ifrX =frames['index'];

cross-browser solution is:

    ifrX.src = ifrX.contentWindow.location

this is useful especially when <iframe> is a the target of a <form>

DirectX SDK (June 2010) Installation Problems: Error Code S1023

Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it

I just wanted to say that this(I also emptied my temp folder, in Computer->C:->Properties->Disk Cleanup) made the DirectX June 2010 SDK install without failure, I have Vista32bit for all it matters. Thank you Mr.Lyn! :)