Programs & Examples On #Unbind

Remove a previously-attached binding to an IP address:port pair, naming context, event handler, communication channel, or other system object. See [tag:bind] for a partial list of the common uses of the bind/unbind concept.

jQuery bind/unbind 'scroll' event on $(window)

try this:

$(window).unbind('scroll');

it works in my project

How to get ip address of a server on Centos 7 in bash

Run this command to show ip4 and ip6:

ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1

How can I make a CSS glass/blur effect work for an overlay?

I came up with this solution.

Click to view image of blurry effect

It is kind of a trick which uses an absolutely positioned child div, sets its background image same as the parent div and then uses the background-attachment:fixed CSS property together with the same background properties set on the parent element.

Then you apply filter:blur(10px) (or any value) on the child div.

_x000D_
_x000D_
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}
.background{
    position: relative;
    width:100%;
    height:100vh;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-size:cover;
    background-position: center;
    background-repeat:no-repeat;
}

.blur{
    position: absolute;
    top:0;
    left:0;
    width:50%;
    height:100%;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size:cover;
    filter:blur(10px);
    transition:filter .5s ease;
    backface-visibility: hidden;
}

.background:hover .blur{
    filter:blur(0);
}
.text{
    display: inline-block;
    font-family: sans-serif;
    color:white;
    font-weight: 600;
    text-align: center;
    position: relative;
    left:25%;
    top:50%;
    transform:translate(-50%,-50%);
}
_x000D_
<head>
    <title>Blurry Effect</title>
</head>
<body>
    <div class="background">
        <div class="blur"></div>
        <h1 class="text">This is the <br>blurry side</h1>
    </div>
</body>
_x000D_
_x000D_
_x000D_

view on codepen

New features in java 7

The following list contains links to the the enhancements pages in the Java SE 7.

Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
    Requesting and Customizing Applet Decoration in Dragg able Applets
    Embedding JNLP File in Applet Tag
    Deploying without Codebase
    Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
    Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
    Binary Literals
    Strings in switch Statements
    The try-with-resources Statement
    Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    Underscores in Numeric Literals
    Type Inference for Generic Instance Creation
    Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
    Java Virtual Machine Support for Non-Java Languages
    Garbage-First Collector
    Java HotSpot Virtual Machine Performance Enhancements
JDBC

Reference 1 Reference 2

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Auto margins don't center image in page

For a bootstrap button:

display: table; 
margin: 0 auto;

How to convert from Hex to ASCII in JavaScript?

You can use this..

_x000D_
_x000D_
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){_x000D_
      return String.fromCharCode(parseInt(v, 16));_x000D_
    }).join('');_x000D_
    _x000D_
document.write(asciiVal);
_x000D_
_x000D_
_x000D_

How to check a string for specific characters?

s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

else:
print("Non Space Special Character")

ReactJS lifecycle method inside a function Component

Edit: With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They are released in React as a part of v16.8.0

useEffect hook can be used to replicate lifecycle behavior, and useState can be used to store state in a function component.

Basic syntax:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

You can implement your use case in hooks like

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    useEffect(() => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    }, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount:

Eg: componentWillUnmount

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:

Eg: componentDidUpdate

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

Hooks Equivalent

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.

There are some subtleties to using useEffect; check out the API Here.


Before v16.7.0

The property of function components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.

class Grid extends React.Component  {
    constructor(props) {
       super(props)
    }

    componentDidMount () {
        if(!this.props.fetched) {
            this.props.fetchRules();
        }
        console.log('mount it!');
    }
    render() {
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
  }
}

Function components are useful when you only want to render your Component without the need of extra logic.

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

How to find a user's home directory on linux or unix?

To find the home directory for user FOO on a UNIX-ish system, use ~FOO. For the current user, use ~.

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

Android - Start service on boot

Well here is a complete example of an AutoStart Application

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pack.saltriver" android:versionCode="1" android:versionName="1.0">

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver android:name=".autostart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity android:name=".hello"></activity>
        <service android:enabled="true" android:name=".service" />
    </application>
</manifest>

autostart.java

public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context context, Intent arg1) 
    {
        Intent intent = new Intent(context,service.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
        Log.i("Autostart", "started");
    }
}

service.java

public class service extends Service
{
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onStart(Intent intent, int startid)
    {
        Intent intents = new Intent(getBaseContext(),hello.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}

hello.java - This will pop-up everytime you start the device after executing the Applicaton once.

public class hello extends Activity 
{   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
    }
}

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

VB.NET Empty String Array

A little verbose, but self documenting...

Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray

How to center a checkbox in a table cell?

How about this... http://jsfiddle.net/gSaPb/


Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:

_x000D_
_x000D_
td {
  text-align: center;
  /* center checkbox horizontally */
  vertical-align: middle;
  /* center checkbox vertically */
}

table {
  border: 1px solid;
  width: 200px;
}

tr {
  height: 80px;
}
_x000D_
<table>
  <tr>
    <td>
      <input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

How to underline a UILabel in swift?

Just a little fix for the Shlome answer in Swift 4 and Xcode 9.

extension UILabel {
    func underline() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
                                          value: NSUnderlineStyle.styleSingle.rawValue,
                                          range: NSRange(location: 0, length: attributedString.length - 1))
            attributedText = attributedString
        }
    }
}

    extension UIButton {
        func underline() {
            let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
                                          value: NSUnderlineStyle.styleSingle.rawValue,
                                          range: NSRange(location: 0, length: (self.titleLabel?.text!.count)!))
            self.setAttributedTitle(attributedString, for: .normal)
        }
    }

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

How to fetch JSON file in Angular 2

You need to make an HTTP call to your games.json to retrieve it. Something like:

this.http.get(./app/resources/games.json).map

How to hide collapsible Bootstrap 4 navbar on click

You can use a simply bind on click and close, like this: (click)="drawer.close()

<a class="nav-link" [routerLink]="navItem.link" routerLinkActive="selected" (click)="drawer.close()">

Removing first x characters from string?

Use del.

Example:

>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

Maintaining href "open in new tab" with an onClick handler in React

React + TypeScript inline util method:

const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;

Can I set an opacity only to the background image of a div?

This can be done by using the different div class for the text Hi There...

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

Now you can apply the styles to the

tag. otherwise for bg class. I am sure it works fine

Loading basic HTML in Node.js

try this one:

var http = require('http');
var fs = require('fs');
var PORT = 8080;

http.createServer((req, res) => {
    fs.readFile('./' + req.url, (err, data) => {
        if (!err) {
            var dotoffset = req.url.lastIndexOf('.');
            var mimetype = dotoffset == -1 ? 'text/plaint' : {
                '.html': 'text/html',
                '.css': 'text/css',
                '.js': 'text/javascript',
                '.jpg': 'image/jpeg',
                '.png': 'image/png',
                '.ico': 'image/x-icon',
                '.gif': 'image/gif'
            }[ req.url.substr(dotoffset) ];
            res.setHeader('Content-Type', mimetype);
            res.end(data);
            console.log(req.url, mimetype);
        } else {
            console.log('File not fount: ' + req.url);
            res.writeHead(404, "Not Found");
            res.end();
        }
    });
 }).listen(PORT);

With this, you can include js, css source-codes when linking them and you can load icons, imgs, gifs. And if you want, you can add more if you need.

"No X11 DISPLAY variable" - what does it mean?

One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.

What's the best way to select the minimum value from several columns?

If you're able to make a stored procedure, it could take an array of values, and you could just call that.

How to check if a string contains a substring in Bash

Extension of the question answered here How do you tell if a string contains another string in POSIX sh?:

This solution works with special characters:

# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"

    if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"

contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"

Executing a shell script from a PHP script

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver
      

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>
      

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
      
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2
    

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

How can I get column names from a table in Oracle?

For MySQL, use

SELECT column_name 
FROM information_schema.columns 
WHERE 
table_schema = 'Schema' AND table_name = 'Table_Name'

How to open a new form from another form

private void Button1_Click(object sender, EventArgs e)
{
    NewForm newForm = new NewForm();    //Create the New Form Object
    this.Hide();    //Hide the Old Form
    newForm.ShowDialog();    //Show the New Form
    this.Close();    //Close the Old Form
}

Dynamically fill in form values with jQuery

Automatically fill all form fields from an array

http://jsfiddle.net/brynner/wf0rk7tz/2/

JS

function fill(a){
    for(var k in a){
        $('[name="'+k+'"]').val(a[k]);
    }
}

array_example = {"God":"Jesus","Holy":"Spirit"};

fill(array_example);

HTML

<form>
<input name="God">
<input name="Holy">
</form>

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

Select distinct values from a list using LINQ in C#

You can try with this code

var result =  (from  item in List
              select new 
              {
                 EmpLoc = item.empLoc,
                 EmpPL= item.empPL,
                 EmpShift= item.empShift
              })
              .ToList()
              .Distinct();

ORA-00932: inconsistent datatypes: expected - got CLOB

The problem may lie in selected null values ??in combination with a CLOB-type column.

select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       valueVvarchar c4
of Table_1
union
select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       null c4
of table_2

I reworked the cursor. The first cursor is composed of four non-null columns. The second cursor selects three non-null columns. The null values ??were injected into the cursorForLoop .

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Find common substring between two strings

**Return the comman longest substring** 
def longestSubString(str1, str2):
    longestString = ""
    maxLength = 0
    for i in range(0, len(str1)):
        if str1[i] in str2:
            for j in range(i + 1, len(str1)):
                if str1[i:j] in str2:
                    if(len(str1[i:j]) > maxLength):
                        maxLength = len(str1[i:j])
                        longestString =  str1[i:j]
return longestString

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you're using Radiant CMS, simply add

require 'thread'

to the top of config/boot.rb.

(Kudos to Aaron's and nathanvda's responses.)

Show a number to two decimal places

You can use the PHP printf or sprintf functions:

Example with sprintf:

$num = 2.12;
echo sprintf("%.3f", $num);

You can run the same without echo as well. Example: sprintf("%.3f", $num);

Output:

2.120

Alternatively, with printf:

echo printf("%.2f", $num);

Output:

2.124

Get cookie by name

Here is a pretty short version

 function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

Stopword removal with NLTK

You can use string.punctuation with built-in NLTK stopwords list:

from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation

words = tokenize(text)
wordsWOStopwords = removeStopWords(words)

def tokenize(text):
        sents = sent_tokenize(text)
        return [word_tokenize(sent) for sent in sents]

def removeStopWords(words):
        customStopWords = set(stopwords.words('english')+list(punctuation))
        return [word for word in words if word not in customStopWords]

NLTK stopwords complete list

how to display full stored procedure code?

To see the full code(query) written in stored procedure/ functions, Use below Command:

sp_helptext procedure/function_name

for function name and procedure name don't add prefix 'dbo.' or 'sys.'.

don't add brackets at the end of procedure or function name and also don't pass the parameters.

use sp_helptext keyword and then just pass the procedure/ function name.

use below command to see full code written for Procedure:

sp_helptext ProcedureName

use below command to see full code written for function:

sp_helptext FunctionName

Allow 2 decimal places in <input type="number">

You can use this. react hooks

_x000D_
_x000D_
<input
                  type="number"
                  name="price"
                  placeholder="Enter price"
                  step="any"
                  required
                />
_x000D_
_x000D_
_x000D_

How to add files/folders to .gitignore in IntelliJ IDEA?

right click on the project create a file with name .ignore, then you can see that file opened.

at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).

Now when ever you give a right click on the file or project you can see the option call add to .ignore

Currency formatting in Python

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

Unordered List (<ul>) default indent

I found the following removed the indent and the margin from both the left AND right sides, but allowed the bullets to remain left-justified below the text above it. Add this to your css file:

ul.noindent {
    margin-left: 5px;
    margin-right: 0px;
    padding-left: 10px;
    padding-right: 0px;
}

To use it in your html file add class="noindent" to the UL tag. I've tested w/FF 14 and IE 9.

I have no idea why browsers default to the indents, but I haven't really had a reason for changing them that often.

Making the Android emulator run faster

I've been using the Intel(86) CPU/ABI. I created another emulator using the ARM(armeabi-v7a) and i found quite an improvement with the speed. I'm using platform 4.1.2 API level 16

libxml/tree.h no such file or directory

You also need to add /usr/include/libxml2 to your include path.

WCF on IIS8; *.svc handler mapping doesn't work

On windows 10 (client) you can also script this using

Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName WCF-HTTP-Activation45 -All

Note that this is a different command from the server skus

Bash script to run php script

You just need to set :

/usr/bin/php path_to_your_php_file

in your crontab.

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

My case was that I did not have direct access to EF context from my MVC app.

So if you are using some kind of repository for entity persistence it could be appropiate to simply detach explicitly loaded entity and then set binded EntityState to Modified.

Sample (abstract) code:

MVC

public ActionResult(A a)
{
  A aa = repo.Find(...);
  // some logic
  repo.Detach(aa);
  repo.Update(a);
}

Repository

void Update(A a)
{
   context.Entry(a).EntityState = EntityState.Modified;
   context.SaveChanges();
}

void Detach(A a)
{
   context.Entry(a).EntityState = EntityState.Detached;
}

How can I select the record with the 2nd highest salary in database Oracle?

select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))

so in our emp table(default provided by oracle) here is the output

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


  7698 BLAKE      MANAGER         7839 01-MAY-81       3000            30
  7788 SCOTT      ANALYST         7566 19-APR-87       3000            20
  7902 FORD       ANALYST         7566 03-DEC-81       3000            20

or just you want 2nd maximum salary to be displayed

select max(sal) from emp where sal<(select max(sal) from emp)

MAX(SAL)

  3000

Remove attribute "checked" of checkbox

Try:

$("#captureAudio")[0].checked = false;

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

PostgreSQL create table if not exists

There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:

CREATE OR REPLACE FUNCTION execute(TEXT) RETURNS VOID AS $$
BEGIN
  EXECUTE $1;
END; $$ LANGUAGE plpgsql;


SELECT 
  execute($$
      CREATE TABLE sch.foo 
      (
        i integer
      )
  $$) 
WHERE 
  NOT exists 
  (
    SELECT * 
    FROM information_schema.tables 
    WHERE table_name = 'foo'
      AND table_schema = 'sch'
  );

How do I escape a percentage sign in T-SQL?

Use brackets. So to look for 75%

WHERE MyCol LIKE '%75[%]%'

This is simpler than ESCAPE and common to most RDBMSes.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

Vue 2 - Mutating props vue-warn

You can achieve 2 way data-binding in Nuxt/Vue like this:

Child.vue

<template>
    <input
      v-model="content"
       <!-- How you choose to emit the event is up to you could be @keydown or even inside a watch prop -->
      @keyup="$emit('update:dataFromParent', content)"
    />
</template>

<script>
export default {
  props: ["dataFromParent"],
  mounted() {
    this.content = this.dataFromParent;
  },
  data: () => ({
    content: "",
  }),
};
</script>

Parent.vue

<tenplate>
  <Child :dataFromParent.sync="text" />
</template>

<script>
import Child from "~/components/Child";

export default {
  components: {
    Child,
  },
  data: () => ({
    text: "Hello World!" ,
  }),
 
};
</script>

Node / Express: EADDRINUSE, Address already in use - Kill server

I was facing the same problem. I just changed my port number from 8000 to 6000. as you have 3000 you try 5000,4000,7000,8000 etc.

What is the equivalent of Java's System.out.println() in Javascript?

Essentially console.log("Put a message here.") if the browser has a supporting console.

Another typical debugging method is using alerts, alert("Put a message here.")

RE: Update II

This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.

Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print() method for evaluating expressions and printing them out. Checkout this documentation.

These links might be of interest to you.

QUnit and Automated Testing

JavaScript Unit Tests with QUnit

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

To center the table in the middle of the email use

<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            Your Content
        </td>
    </tr>
</table>

To align the content in the middle use:

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

IF... OR IF... in a windows batch file

The zmbq solution is good, but cannot be used in all situations, such as inside a block of code like a FOR DO(...) loop.

An alternative is to use an indicator variable. Initialize it to be undefined, and then define it only if any one of the OR conditions is true. Then use IF DEFINED as a final test - no need to use delayed expansion.

FOR ..... DO (
  set "TRUE="
  IF cond1 set TRUE=1
  IF cond2 set TRUE=1
  IF defined TRUE (
    ...
  ) else (
    ...
  )
)

You could add the ELSE IF logic that arasmussen uses on the grounds that it might perform a wee bit faster if the 1st condition is true, but I never bother.

Addendum - This is a duplicate question with nearly identical answers to Using an OR in an IF statement WinXP Batch Script

Final addendum - I almost forgot my favorite technique to test if a variable is any one of a list of case insensitive values. Initialize a test variable containing a delimitted list of acceptable values, and then use search and replace to test if your variable is within the list. This is very fast and uses minimal code for an arbitrarily long list. It does require delayed expansion (or else the CALL %%VAR%% trick). Also the test is CASE INSENSITIVE.

set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" (echo true) else (echo false)

The above can fail if VAR contains =, so the test is not fool-proof.

If doing the test within a block where delayed expansion is needed to access current value of VAR then

for ... do (
  set "TEST=;val1;val2;val3;val4;val5;"
  for /f %%A in (";!VAR!;") do if "!TEST:%%A=!" neq "!TEST!" (echo true) else (echo false)
)

FOR options like "delims=" might be needed depending on expected values within VAR

The above strategy can be made reliable even with = in VAR by adding a bit more code.

set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" if "!TEST:;%VAR%;=;%VAR%;"=="!TEST!" echo true

But now we have lost the ability of providing an ELSE clause unless we add an indicator variable. The code has begun to look a bit "ugly", but I think it is the best performing reliable method for testing if VAR is any one of an arbitrary number of case-insensitive options.

Finally there is a simpler version that I think is slightly slower because it must perform one IF for each value. Aacini provided this solution in a comment to the accepted answer in the before mentioned link

for %%A in ("val1" "val2" "val3" "val4" "val5") do if "%VAR%"==%%A echo true

The list of values cannot include the * or ? characters, and the values and %VAR% should not contain quotes. Quotes lead to problems if the %VAR% also contains spaces or special characters like ^, & etc. One other limitation with this solution is it does not provide the option for an ELSE clause unless you add an indicator variable. Advantages are it can be case sensitive or insensitive depending on presence or absence of IF /I option.

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Edit seaborn legend

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

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

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

g._legend.set_title("New Title")

How do I check if an index exists on a table field in MySQL?

Try:

SELECT * FROM information_schema.statistics 
  WHERE table_schema = [DATABASE NAME] 
    AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]

It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)

PHP Session timeout

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>

Installing R with Homebrew

You can also install R from this page:

https://cran.r-project.org/bin/macosx/

It works out of the box

INSERT INTO TABLE from comma separated varchar-list

Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin       
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return       
end  

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

Entity framework self referencing loop detected

I only had one model i wanted to use, so i ended up with the following code:

var JsonImageModel = Newtonsoft.Json.JsonConvert.SerializeObject(Images, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

JPA Query selecting only specific columns without using Criteria Query?

You can use something like this:

List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();

then you can iterate over it:

for (Object[] obj : list){
    System.out.println(obj[0]);
    System.out.println(obj[1]);
}

BUT if you have only one field in query, you get a list of the type not from Object[]

Get the item doubleclick event of listview

Use the ListView.HitTest method

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;
        var clickedItem = senderList.HitTest(e.Location).Item;
        if (clickedItem != null)
        {
            //do something
        }            
    }

Or the old way

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;                        
        if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
        {
            //Do something
        }
    }

    public  bool IsInBound(Point location, Rectangle bound)
    {
        return (bound.Y <= location.Y && 
                bound.Y + bound.Height >= location.Y &&
                bound.X <= location.X && 
                bound.X + bound.Width >= location.X);
    }

Using a Glyphicon as an LI bullet point (Bootstrap 3)

This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.

  1. Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.

    Inspecting a glyphicon

  2. Use that character code in the following CSS

    li {
        display: block;
    }
    
    li:before {
        /*Using a Bootstrap glyphicon as the bullet point*/
        content: "\e080";
        font-family: 'Glyphicons Halflings';
        font-size: 9px;
        float: left;
        margin-top: 4px;
        margin-left: -17px;
        color: #CCCCCC;
    }
    

    You may like to tweak the colour and margins to suit your font size and taste.

View Demo & Code

IIS7 Cache-Control

I use this

<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="500.00:00:00" />
</staticContent>

to cache static content for 500 days with public cache-control header.

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

Get Date Object In UTC format in Java

final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));

The thread has exited with code 0 (0x0) with no unhandled exception

if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...

If the above does not help then please provide more details since I am not sure what exactly the problem is you face...

PHP CURL DELETE request

I finally solved this myself. If anyone else is having this problem, here is my solution:

I created a new method:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

Update 2

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

How can I subset rows in a data frame in R based on a vector of values?

Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff statement unnecessary.

Using the data from Dinre's example:

In base R:

cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)

Using the dplyr package:

library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))

To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.

How do I populate a JComboBox with an ArrayList?

I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.

JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));

my example is only strings though.

Configuring RollingFileAppender in log4j

I'm suspicious of the ActiveFileName property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy class. (No setActiveFileName or getActiveFileName methods.)

I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.

Try leaving it out and seeing what happens.

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

clear form values after submission ajax

it works: call this function after ajax success and send your form id as it's paramete. something like this:

This function clear all input fields value including button, submit, reset, hidden fields

function resetForm(formid) {
 $('#' + formid + ' :input').each(function(){  
  $(this).val('').attr('checked',false).attr('selected',false);
 });
}

* This function clears all input fields value except button, submit, reset, hidden fields * */

 function resetForm(formid) {
   $(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
  }

example:

<script>
   (function($){
       function processForm( e ){
           $.ajax({
               url: 'insert.php',
               dataType: 'text',
               type: 'post',
               contentType: 'application/x-www-form-urlencoded',
               data: $(this).serialize(),
               success: function( data, textStatus, jQxhr ){
                $('#alertt').fadeIn(2000);
                $('#alertt').html( data );
                $('#alertt').fadeOut(3000);
               resetForm('userInf');
            },
            error: function( jqXhr, textStatus, errorThrown ){
                console.log( errorThrown );
            }
        });

        e.preventDefault();
    }

    $('#userInf').submit( processForm );
})(jQuery);

 function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
 }
  </script>

When do I have to use interfaces instead of abstract classes?

Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

Interface : It define just protocol which all subclass need to follow.

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

Preloading CSS Images

I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.

Here's a test : http://paragraphe.org/slidetoggletest/test.html

<script>
    var pic = new Image();
    var pic2 = new Image();
    var pic3 = new Image();
    pic.src="images/inputs/input1.png";
    pic2.src="images/inputs/input2.png";
    pic3.src="images/inputs/input3.png";
</script>

Move the most recent commit(s) to a new branch with Git

Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.

You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:

(Notice see commit hash)

To avoid this:

1) git checkout master

2) git branch <feature branch> master

3) git reset --hard <commit hash>

4) git push -f origin master

How to create JSON string in JavaScript?

Javascript doesn't handle Strings over multiple lines.

You will need to concatenate those:

var obj = '{'
       +'"name" : "Raj",'
       +'"age"  : 32,'
       +'"married" : false'
       +'}';

You can also use template literals in ES6 and above: (See here for the documentation)

var obj = `{
           "name" : "Raj",
           "age" : 32,
           "married" : false,
           }`;

jQuery autoComplete view all on click?

I found this to work best

var data = [
    { label: "Choice 1", value: "choice_1" },
    { label: "Choice 2", value: "choice_2" },
    { label: "Choice 3", value: "choice_3" }
];

$("#example")
.autocomplete({
    source: data,
    minLength: 0
})
.focus(function() {
    $(this).autocomplete('search', $(this).val())
});

It searches the labels and places the value into the element $(#example)

Alternative to google finance api

I'm way late, but check out Quandl. They have an API for stock prices and fundamentals.

Here's an example call, using Quandl-api download in csv

example:

https://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?column=4&sort_order=asc&collapse=quarterly&trim_start=2012-01-01&trim_end=2013-12-31

They support these languages. Their source data comes from Yahoo Finance, Google Finance, NSE, BSE, FSE, HKEX, LSE, SSE, TSE and more (see here).

In Bash, how do I add a string after each line in a file?

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename

The name 'model' does not exist in current context in MVC3

Reinstalling the nuget solved it for me

PM> Install-Package Microsoft.AspNet.Razor -Version 3.2.3

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

Inner text shadow with CSS

I've had a few instances where I've needed inner shadows on text, and the following has worked out well for me:

.inner {
    color: rgba(252, 195, 67, 0.8);
    font-size: 48px;
    text-shadow: 1px 2px 3px #fff, 0 0 0 #000;
}

This sets the opacity of the text to 80%, and then creates two shadows:

  • The first is a white shadow (assuming the text is on a white background) offset 1px from the left and 2px from the top, blurred 3px.
  • The second is a black shadow which is visible through the 80% opacity text but not through the first shadow, which means it's visible inside the text letters only where the first shadow is displaced (1px from the left and 2px from the top). To change the blur of the this visible shadow, modify the blur parameter for the first layer shadow.

Caveats

  • This will only work if the desired color of the text can be achieved without it having to be at 100% opacity.
  • This will only work if the background color is solid (so, it won't work for the questioner's specific example where the text sits on a textured background).

Python equivalent of a given wget command

urllib.request should work. Just set it up in a while(not done) loop, check if a localfile already exists, if it does send a GET with a RANGE header, specifying how far you got in downloading the localfile. Be sure to use read() to append to the localfile until an error occurs.

This is also potentially a duplicate of Python urllib2 resume download doesn't work when network reconnects

Set Focus After Last Character in Text Box

One can use these simple javascript within the input tag.

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />

Java error: Comparison method violates its general contract

I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...

After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.

How to match a substring in a string, ignoring case

import re
if re.search('(?i)Mandy Pande:', line):
    ...

How do I copy a version of a single file from one git branch to another?

I ended up at this question on a similar search. In my case I was looking to extract a file from another branch into current working directory that was different from the file's original location. Answer:

git show TREEISH:path/to/file > path/to/local/file

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

use a cursor

ADDENDUM: [MS SQL cursor example]

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

open cur

fetch next from cur into @field1, @field2

while @@FETCH_STATUS = 0 BEGIN

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

    fetch next from cur into @field1, @field2
END

close cur
deallocate cur

in MS SQL, here's an example article

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

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

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

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Add some word to all or some rows in Excel?

Insert a column, for instance a new A column. Then use this function;

="k"&B1

and copy it down.

Then you can hide the new column A if you need too.

How to Disable GUI Button in Java

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.

Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.

Twitter Bootstrap alert message close and open again

I've tried all the methods and the best way for me is to use the built-in bootstrap classes .fade and .in

Example:

<div class="alert alert-danger fade <?php echo ($show) ? 'in' : '' ?>" role="alert">...</div>

Note: In jQuery, addClass('in') to show the alert, removeClass('in') to hide it.

Fun fact: This works for all elements. Not just alerts.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

I used Palash's answer given above but it was somewhat incomplete, I had to provide permission like this

Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(path));

        List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }else {
        uri = Uri.fromFile(new File(path));
    }

    intent.setDataAndType(uri, "application/vnd.android.package-archive");

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

Get the current year in JavaScript

Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:

let currentYear = new Date().getFullYear;

The currentYear variable will hold the value you are looking out for.

Print in one line dynamically

change

print item

to

print "\033[K", item, "\r",
sys.stdout.flush()
  • "\033[K" clears to the end of the line
  • the \r, returns to the beginning of the line
  • the flush statement makes sure it shows up immediately so you get real-time output.

The split() method in Java does not work on a dot (.)

    private String temp = "mahesh.hiren.darshan";

    String s_temp[] = temp.split("[.]");

  Log.e("1", ""+s_temp[0]);

How to add Options Menu to Fragment in Android

TL;DR

Use the android.support.v7.widget.Toolbar and just do:

toolbar.inflateMenu(R.menu.my_menu)
toolbar.setOnMenuItemClickListener {
    onOptionsItemSelected(it)
}

Standalone Toolbar

Most of the suggested solutions like setHasOptionsMenu(true) are only working when the parent Activity has the Toolbar in its layout and declares it via setSupportActionBar(). Then the Fragments can participate in the menu population of this exact ActionBar:

Fragment.onCreateOptionsMenu(): Initialize the contents of the Fragment host's standard options menu.

If you want a standalone toolbar and menu for one specific Fragment you can to do the following:

menu_custom_fragment.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_save"
        android:title="SAVE" />
</menu>

custom_fragment.xml

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    ...

CustomFragment.kt

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(layout.custom_fragment, container, false)
    val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
    toolbar.inflateMenu(R.menu.menu_custom_fragment)
    toolbar.setOnMenuItemClickListener {
        onOptionsItemSelected(it)
    }
    return view
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.menu_save -> {
            // TODO: User clicked the save button
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

Yes, it's that easy. You don't even need to override onCreate() or onCreateOptionsMenu().

PS: This is only working with android.support.v4.app.Fragment and android.support.v7.widget.Toolbar (also be sure to use AppCompatActivity and an AppCompat theme in your styles.xml).

How to turn off page breaks in Google Docs?

The solution I came up with was to use the publishing feature.

File > Publish to the web...

Then in the URL you can just replace the .../edit path with .../pub

This solves the problem described in the question of breaking up a table with footnotes.

Is there a "null coalescing" operator in JavaScript?

Need to support old browser and have a object hierarchy

body.head.eyes[0]  //body, head, eyes  may be null 

may use this,

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Maximum execution time in phpMyadmin

Changing php.ini for a web application requires restarting Apache.

You should verify that the change took place by running a PHP script that executes the function phpinfo(). The output of that function will tell you a lot of PHP parameters, including the timeout value.

You might also have changed a copy of php.ini that is not the same file used by Apache.

How to find rows in one table that have no corresponding row in another table

You can also use exists, since sometimes it's faster than left join. You'd have to benchmark them to figure out which one you want to use.

select
    id
from
    tableA a
where
    not exists
    (select 1 from tableB b where b.id = a.id)

To show that exists can be more efficient than a left join, here's the execution plans of these queries in SQL Server 2008:

left join - total subtree cost: 1.09724:

left join

exists - total subtree cost: 1.07421:

exists

Delete all rows in a table based on another table

While the OP doesn't want to use an 'in' statement, in reply to Ankur Gupta, this was the easiest way I found to delete the records in one table which didn't exist in another table, in a one to many relationship:

DELETE
FROM Table1 as t1
WHERE ID_Number NOT IN
(SELECT ID_Number FROM Table2 as t2)

Worked like a charm in Access 2016, for me.

ORA-12170: TNS:Connect timeout occurred

I have tried changing the tnsnames.ora file putting the IP of the server instead of localhost or loopback address, it did not work. The firewall was blocking the requests. Please configure your firewall or turn it off(not recommended), it would work.

element not interactable exception in selenium web automation

I had the same problem and then figured out the cause. I was trying to type in a span tag instead of an input tag. My XPath was written with a span tag, which was a wrong thing to do. I reviewed the Html for the element and found the problem. All I then did was to find the input tag which happens to be a child element. You can only type in an input field if your XPath is created with an input tagname

What are 'get' and 'set' in Swift?

variable declares and call like this in a class

class X {
    var x: Int = 3

}
var y = X()
print("value of x is: ", y.x)

//value of x is:  3

now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.

class X {
    var _x: Int = 3
    var x: Int {
        get {
            return _x
        }
        set(newVal) {  //set always take 1 argument
            if newVal >= 3 {
             _x = newVal //updating _x with the input value by the user
            print("new value is: ", _x)
            }
            else {
                print("error must be greater than 3")
            }
        }
    }
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8

if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.

How do I make an attributed string using Swift?

Swift 2.0

Here is a sample:

let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString

Swift 5.x

let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString

OR

let stringAttributes = [
    NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 17.0)!,
    NSUnderlineStyleAttributeName : 1,
    NSForegroundColorAttributeName : UIColor.orangeColor(),
    NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
    NSStrokeWidthAttributeName : 2.0]
let atrributedString = NSAttributedString(string: "Sample String: Attributed", attributes: stringAttributes)
sampleLabel.attributedText = atrributedString

Hide Spinner in Input Number - Firefox 29

According to this blog post, you need to set -moz-appearance:textfield; on the input.

_x000D_
_x000D_
input[type=number]::-webkit-outer-spin-button,_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
    -webkit-appearance: none;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
    -moz-appearance:textfield;_x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

How to connect html pages to mysql database?

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

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

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

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

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

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

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

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

Python element-wise tuple operations like sum

import operator
tuple(map(operator.add, a, b))

How to bind list to dataGridView?

Instead of create the new Container class you can use a dataTable.

DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");

dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });

myDataGridView.DataSource = dt;

More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

Chart.JS API has changed since this was posted and older examples did not seem to be working for me. here is an updated fiddle that works on the newer versions

HTML:

<body>
    <canvas id="canvas" height="450" width="600"></canvas>
    <img id="url" />
</body>

JS:

function done(){
  alert("haha");
  var url=myLine.toBase64Image();
  document.getElementById("url").src=url;
}

var options = {
  bezierCurve : false,
  animation: {
    onComplete: done
  }
};

var myLine = new 
   Chart(document.getElementById("canvas").getContext("2d"),
     {
        data:lineChartData,
        type:"line",
        options:options
      }
    );

http://jsfiddle.net/KSgV7/585/

Fatal error: [] operator not supported for strings

this was available in php 5.6 in php 7+ you should declare the array first

$users = array(); // not $users = ";
$users[] = "762";

Changing background colour of tr element on mouseover

I had the same problem:

tr:hover { background: #000 !important; }

allone did not work, but adding

tr:hover td { background: transparent; }

to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.

Actually, I used it with a classnames:

.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }

Thanks for these answers, they made my day!! :)

Vagrant ssh authentication failure

Mac Solution:

  1. Added local ssh id_rsa key to vagrant private key

    vi /Users//.vagrant/machines/default/virtualbox/private_key

    /Users//.ssh/id_rsa

  2. copied public key /Users//.ssh/id_rsa.pub on vagrant box authorized_keys

ssh vagrant@localhost -p 2222 (password: vagrant) ls -la cd .ssh

  1. chmod 0600 ~/.ssh/authorized_keys

  2. vagrant reload

Problem resolved.

Thanks to

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

http://plnkr.co/edit/A2IG03FLYnEYMpZ5RxEm?p=preview

Here is a case sensitive search that also separates your search into words to search in each model as well. Only when it finds a space will it try to split the query into an array and then search each word.

It returns true if every word is at least in one of the models.

$scope.songSearch = function (row) {
    var query = angular.lowercase($scope.query);
    if (query.indexOf(" ") > 0) {
        query_array = query.split(" ");
        search_result = false;
        for (x in query_array) {
            query = query_array[x];
            if (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1){
                search_result = true;
            } else {
                search_result = false;
                break;
            }
        }
        return search_result;
    } else {
        return (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1);
    }
};

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in

ngOnInt(){

    userForm = new FormGroup({
        name: new FormControl(),
        email: new FormControl(),
        adresse: new FormGroup({
            rue: new FormControl(),
            ville: new FormControl(),
            cp: new FormControl(),
        })
     });
)

ORA-00054: resource busy and acquire with NOWAIT specified

When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.

If you absolutely must, you can kill the OS process as well (look up v$process.spid), which would release any locks it was holding on to.

See this for more detailed info.

How to overlay density plots in R?

I took the above lattice example and made a nifty function. There is probably a better way to do this with reshape via melt/cast. (Comment or edit if you see an improvement.)

multi.density.plot=function(data,main=paste(names(data),collapse = ' vs '),...){
  ##combines multiple density plots together when given a list
  df=data.frame();
  for(n in names(data)){
    idf=data.frame(x=data[[n]],label=rep(n,length(data[[n]])))
    df=rbind(df,idf)
  }
  densityplot(~x,data=df,groups = label,plot.points = F, ref = T, auto.key = list(space = "right"),main=main,...)
}

Example usage:

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1),main='BN1 vs BN2')

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1))

Using mysql concat() in WHERE clause?

You can try this:

select * FROM table where (concat(first_name, ' ', last_name)) = $search_term;

Change bootstrap navbar collapse breakpoint without using LESS

You have to write a specific media query for this, from your question, below 768px, the navbar will collapse, so apply it above 768px and below 1000px, just like that:

@media (min-width: 768px) and (max-width: 1000px) {
   .collapse {
       display: none !important;
   }
}

This will hide the navbar collapse until the default occurrence of the bootstrap unit. As the collapse class flips the inner assets inside navbar collapse will be automatically hidden, like wise you have to set your css as you desired design.

warning: implicit declaration of function

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search. Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

SQL - HAVING vs. WHERE

HAVING operates on aggregates. Since COUNT is an aggregate function, you can't use it in a WHERE clause.

Here's some reading from MSDN on aggregate functions.

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

What is the difference between a generative and a discriminative algorithm?

An addition informative point that goes well with the answer by StompChicken above.

The fundamental difference between discriminative models and generative models is:

Discriminative models learn the (hard or soft) boundary between classes

Generative models model the distribution of individual classes

Edit:

A Generative model is the one that can generate data. It models both the features and the class (i.e. the complete data).

If we model P(x,y): I can use this probability distribution to generate data points - and hence all algorithms modeling P(x,y) are generative.

Eg. of generative models

  • Naive Bayes models P(c) and P(d|c) - where c is the class and d is the feature vector.

    Also, P(c,d) = P(c) * P(d|c)

    Hence, Naive Bayes in some form models, P(c,d)

  • Bayes Net

  • Markov Nets

A discriminative model is the one that can only be used to discriminate/classify the data points. You only require to model P(y|x) in such cases, (i.e. probability of class given the feature vector).

Eg. of discriminative models:

  • logistic regression

  • Neural Networks

  • Conditional random fields

In general, generative models need to model much more than the discriminative models and hence are sometimes not as effective. As a matter of fact, most (not sure if all) unsupervised learning algorithms like clustering etc can be called generative, since they model P(d) (and there are no classes:P)

PS: Part of the answer is taken from source

How to print last two columns using awk

try with this

$ cat /tmp/topfs.txt
/dev/sda2      xfs        32G   10G   22G  32% /

awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'

awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%

awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /

Is there a way to automatically generate getters and setters in Eclipse?

Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:

  1. Go to Window > Preferences
  2. Go to General > Keys
  3. List for "Quick Assist - Create getter/setter for field"
  4. In the "Binding" textfield below, hold the desired keys (in my case, I use ALT + SHIFT + G)
  5. Hit Apply and Ok
  6. Now in your Java editor, select the field you want to create getter/setter methods for and press the shortcut you setup in Step 4. Hit ok in this window to create the methods.

Hope this helps!

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

I assume you are using gcc, to simply link object files do:

$ gcc -o output file1.o file2.o

To get the object-files simply compile using

$ gcc -c file1.c

this yields file1.o and so on.

If you want to link your files to an executable do

$ gcc -o output file1.c file2.c

CSS scale down image to fit in containing div, without specifing original size

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>

What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

How to make a edittext box in a dialog

Simplified version

final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Add a new task")
        .setMessage("What do you want to do next?")
        .setView(taskEditText)
        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String task = String.valueOf(taskEditText.getText());
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                        null,
                        values,
                        SQLiteDatabase.CONFLICT_REPLACE);
                db.close();
                updateUI();
            }
        })
        .setNegativeButton("Cancel", null)
        .create();
dialog.show();
return true;

How do you handle a form change in jQuery?

Here is an elegant solution.

There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example

  • for text/textarea it's defaultValue
  • for select it's defaultSelect
  • for checkbox/radio it's defaultChecked

Here is the example.

function bindFormChange($form) {

  function touchButtons() {
    var
      changed_objects = [],
      $observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');

    changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
      var
        $input = $(this),
        changed = false;

      if ($input.is('input:text') || $input.is('textarea') ) {
        changed = (($input).prop('defaultValue') != $input.val());
      }
      if (!changed && $input.is('select') ) {
        changed = !$('option:selected', $input).prop('defaultSelected');
      }
      if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
        changed = (($input).prop('defaultChecked') != $input.is(':checked'));
      }
      if (changed) {
        return $input.attr('id');
      }

    }).toArray();

    if (changed_objects.length) {
      $observable_buttons.removeAttr('disabled')   
    } else {
      $observable_buttons.attr('disabled', 'disabled');
    }
  };
  touchButtons();

  $('input, textarea, select', $form).each(function () {
    var $input = $(this);

    $input.on('keyup change', function () {
      touchButtons();
    });
  });

};

Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.

$('form').each(function () {
    bindFormChange($(this));
});

Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable

How to set the font style to bold, italic and underlined in an Android TextView?

For bold and italic whatever you are doing is correct for underscore use following code

HelloAndroid.java

 package com.example.helloandroid;

 import android.app.Activity;
 import android.os.Bundle;
 import android.text.SpannableString;
 import android.text.style.UnderlineSpan;
import android.widget.TextView;

public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textview = (TextView)findViewById(R.id.textview);
    SpannableString content = new SpannableString(getText(R.string.hello));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textview.setText(content);
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
android:textStyle="bold|italic"/>

string.xml

<?xml version="1.0" encoding="utf-8"?>
 <resources>
  <string name="hello">Hello World, HelloAndroid!</string>
  <string name="app_name">Hello, Android</string>
</resources>

How to print a dictionary's key?

Try this:

def name_the_key(dict, key):
    return key, dict[key]

mydict = {'key1':1, 'key2':2, 'key3':3}

key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value

How to get the return value from a thread in python?

Define your target to
1) take an argument q
2) replace any statements return foo with q.put(foo); return

so a function

def func(a):
    ans = a * a
    return ans

would become

def func(a, q):
    ans = a * a
    q.put(ans)
    return

and then you would proceed as such

from Queue import Queue
from threading import Thread

ans_q = Queue()
arg_tups = [(i, ans_q) for i in xrange(10)]

threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]
_ = [t.start() for t in threads]
_ = [t.join() for t in threads]
results = [q.get() for _ in xrange(len(threads))]

And you can use function decorators/wrappers to make it so you can use your existing functions as target without modifying them, but follow this basic scheme.

UIView with rounded corners and drop shadow?

Here is my version in Swift 3 for a UIView

let corners:UIRectCorner = [.bottomLeft, .topRight]
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()

mask.path = path.cgPath
mask.fillColor = UIColor.white.cgColor

let shadowLayer = CAShapeLayer()
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 4.0)
shadowLayer.shadowRadius = 6.0
shadowLayer.shadowOpacity = 0.25
shadowLayer.shadowPath = mask.path

self.layer.insertSublayer(shadowLayer, at: 0)
self.layer.insertSublayer(mask, at: 1)

AngularJS disable partial caching on dev machine

There is no solution to prevent browser/proxy caching since you cannot have the control on it.

The other way to force fresh content to your users it to rename the HTML file! Exactly like https://www.npmjs.com/package/grunt-filerev does for assets.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

If you are pulling your queries using java code, there is a great class that can be used, ResultSetMetaData, that can retrieve column names and the properties of the columns (type and length).

Example

ResultSet rs = null;

        rs = sql.executeQuery();

        if (rs != null) {
            if (rs.next()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    System.out.println("column name: "
                            + rsmd.getColumnName(i));
                    System.out.println("column size: "
                            + rsmd.getColumnDisplaySize(i));
                }
            }

Binding multiple events to a listener (without JQuery)?

AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.

This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types.

    // Add elem as a property of the handle function
    // This is to prevent a memory leak with non-native events in IE.
    eventHandle.elem = elem;

    // Handle multiple events separated by a space
    // jQuery(...).bind("mouseover mouseout", fn);
    types = types.split(" ");  

    var type, i = 0, namespaces;

    while ( (type = types[ i++ ]) ) {  <-- iterates thru 1 by 1

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

you should add this line above your page

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

How do I upgrade to Python 3.6 with conda?

In the past, I have found it quite difficult to try to upgrade in-place.

Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda to create environments, this may be destructive because conda creates environments with hard-links inside your Anaconda/envs directory.

So if you use environments, you may first want to export your environments. After activating your environment, do something like:

conda env export > environment.yml

After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):

$ rm -rf ~/anaconda3/

and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:

$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh 

(see here for a more recent one),

and then executing it:

$ bash Anaconda3-4.3.0-Linux-x86_64.sh 

How to generate a core dump in Linux on a segmentation fault?

By default you will get a core file. Check to see that the current directory of the process is writable, or no core file will be created.

How can I add the sqlite3 module to Python?

I have python 2.7.3 and this solved my problem:

pip install pysqlite

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.

A:you need to configure the primeng tabulemodule in ngmodule

How to set focus on input field?

If you are using modalInstance and have the object you can use "then" to do actions after opening the modal. If you are not using the modalInstance, and hard coded to open the modal you can use the event. The $timeout is not a good solution.

You can do (Bootstrap3):

$("#" + modalId).on("shown.bs.modal", function() {
    angular.element("[name='name']").focus();
});

At modalInstance you can look at library to how execute the code after open modal.

Don't use $timeout like this, the $timeout can be 0, 1, 10, 30, 50, 200 or more this will depend on client computer, and the process to open modal.

Don't use $timeout let the method tell you when you can focus ;)

I hope that this help! :)

SQL select * from column where year = 2010

NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between statement:

declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate 
    between dateadd(year, year(@referenceTime) - 1900, '01-01-1900')                        --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901'))  --31st Dec end of this year (just before midnight of the new year)

Similarly, if you're using a year value, swapping year(@referenceDate) for your reference year's value will work

declare @referenceYear int = 2010
select *
from myTable
where SomeDate 
    between dateadd(year,@referenceYear - 1900, '01-01-1900')                       --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)

Using IS NULL or IS NOT NULL on join conditions - Theory question

The NULL part is calculated AFTER the actual join, so that is why it needs to be in the where clause.

Exception of type 'System.OutOfMemoryException' was thrown.

This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command

start -> run -> %temp%

checking if a number is divisible by 6 PHP

So you want the next multiple of 6, is that it?

You can divide your number by 6, then ceil it, and multiply it again:

$answer = ceil($foo / 6) * 6;

Wget output document and headers to STDOUT

wget -S -O - http://google.com works as expected for me, but with a caveat: the headers are considered debugging information and as such they are sent to the standard error rather than the standard output. If you are redirecting the standard output to a file or another process, you will only get the document contents.

You can try redirecting the standard error to the standard output as a possible solution. For example, in bash:

$ wget -q -S -O - 2>&1 | grep ...

or

$ wget -q -S -O - 1>wget.txt 2>&1

The -q option suppresses the progress bar and some other annoyingly chatty parts of the wget output.

How to create a jar with external libraries included in Eclipse?

While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.

You then run the jar directly by java -jar example.jar.

gcc warning" 'will be initialized after'

The order of initialization doesn’t matter. All fields are initialized in the order of their definition in their class/struct. But if the order in initialization list is different gcc/g++ generate this warning. Only change the initialization order to avoid this warning. But you can't define field using in initialization before its construct. It will be a runtime error. So you change the order of definition. Be careful and keep attention!

Array to Hash Ruby

a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }

That's it. The * is called the splat operator.

One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."

So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Lukasz Niemier (also in the comments) offers this method for large data sets:

h = Hash[a.each_slice(2).to_a]

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

try like this,

 sudo fuser -n tcp -k 8080

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

How to monitor network calls made from iOS Simulator

Xcode provides CFNetwork Diagnostic Logging. Apple doc

To enable it, add CFNETWORK_DIAGNOSTICS=3 in the Environment Variable section:

enter image description here

This will show requests from the App with its headers & body. Note that OS_ACTIVITY_MODE must be set to enable as shown. Otherwise no output will be shown on the Console.

How to change the href for a hyperlink using jQuery

This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

my case seems to be invalid JRE version.

1.7+ required while I launched with 1.6

plus: I filtered some plugin jars which might be required. so changed to select all

How to check type of variable in Java?

Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.

Example:

class Typetester {
    void printType(byte x) {
        System.out.println(x + " is an byte");
    }
    void printType(int x) {
        System.out.println(x + " is an int");
    }
    void printType(float x) {
        System.out.println(x + " is an float");
    }
    void printType(double x) {
        System.out.println(x + " is an double");
    }
    void printType(char x) {
        System.out.println(x + " is an char");
    }
}

then:

Typetester t = new Typetester();
t.printType( yourVariable );

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

How to convert currentTimeMillis to a date in Java?

Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.

import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class time {

    public static void main(String args[]){

        String str = "1431601084000";
        long geTime= Long.parseLong(str);
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
        calendar.setTimeInMillis(geTime);
        DateTime jodaTime = new DateTime(geTime, 
               DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
        DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
        System.out.println("Get Time : "+parser1.print(jodaTime));

   }
}

Generating Unique Random Numbers in Java

With Java 8+ you can use the ints method of Random to get an IntStream of random values then distinct and limit to reduce the stream to a number of unique random values.

ThreadLocalRandom.current().ints(0, 100).distinct().limit(5).forEach(System.out::println);

Random also has methods which create LongStreams and DoubleStreams if you need those instead.

If you want all (or a large amount) of the numbers in a range in a random order it might be more efficient to add all of the numbers to a list, shuffle it, and take the first n because the above example is currently implemented by generating random numbers in the range requested and passing them through a set (similarly to Rob Kielty's answer), which may require generating many more than the amount passed to limit because the probability of a generating a new unique number decreases with each one found. Here's an example of the other way:

List<Integer> range = IntStream.range(0, 100).boxed()
        .collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
range.subList(0, 99).forEach(System.out::println);

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

Correct way to read a text file into a buffer in C?

Have you considered mmap()? You can read from the file directly as if it were already in memory.

http://beej.us/guide/bgipc/output/html/multipage/mmap.html

How to include js file in another js file?

You need to write a document.write object:

document.write('<script type="text/javascript" src="file.js" ></script>');

and place it in your main javascript file

store and retrieve a class object in shared preference

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc

How to reload .bashrc settings without logging out and back in again?

Or you could use:

exec bash

This does the same thing, and is easier to remember (at least for me).

The exec command completely replaces the shell process by running the specified command-line. In our example, it replaces whatever the current shell is with a fresh instance of bash (with the updated configuration files).

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Try with,

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

instead of,

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

How to replace a whole line with sed?

You can also use sed's change line to accomplish this:

sed -i "/aaa=/c\aaa=xxx" your_file_here

This will go through and find any lines that pass the aaa= test, which means that the line contains the letters aaa=. Then it replaces the entire line with aaa=xxx. You can add a ^ at the beginning of the test to make sure you only get the lines that start with aaa= but that's up to you.

What’s the difference between Response.Write() andResponse.Output.Write()?

Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.

Here is example:

protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write ("hi good morning!"+"is it right?");//only strings are allowed        
       Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
       Response.Output.Write("\nhi goood morning!");//works fine
       Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
    }

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Regex: ignore case sensitivity

JavaScript

If you want to make it case insensitive just add i at the end of regex:

'Test'.match(/[A-Z]/gi) //Returns ["T", "e", "s", "t"]

Without i

'Test'.match(/[A-Z]/g) //Returns ["T"]

Find package name for Android apps to use Intent to launch Market app from web

Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >

Sorting an array in C?

I'd like to make some changes: In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
   int int_a = * ( (int*) a );
   int int_b = * ( (int*) b );

   // an easy expression for comparing
   return (int_a > int_b) - (int_a < int_b);
}

qsort( a, 6, sizeof(int), compare )