Programs & Examples On #Blacklist

A blacklist is a list of entities that are banned from some access or action (entities not in the blacklist are authorized, including unknown entities).

How to resolve the error on 'react-native start'

I found the regexp.source changed from node v12.11.0, maybe the new v8 engine caused. see more on https://github.com/nodejs/node/releases/tag/v12.11.0.

D:\code\react-native>nvm use 12.10.0
Now using node v12.10.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.10.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[\\/\\\\]react[\\/\\\\]dist[\\/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\\\]react[\\\\\\\\]dist[\\\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.11.0
Now using node v12.11.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.11.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.13.0
Now using node v12.13.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.13.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 13.3.0
Now using node v13.3.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.

plugin version Plugin version

Required Gradle version is here

Required gradle version

more compatibility you can see from here. Android Plugin for Gradle Release Notes

if you have the android studio version 4.0.1 android studio version

then your top level gradle file must be like this

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:4.0.2'
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

and the gradle version should be

gradle version must be like this

and your app gradle look like this

app gradle file

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I just want to thank @Heapify for providing a practical answer and update his answer because the attached links are not up-to-date.

Step 1: Check the existing kernel of your Ubuntu Linux:

uname -a

Step 2:

Ubuntu maintains a website for all the versions of kernel that have been released. At the time of this writing, the latest stable release of Ubuntu kernel is 4.15. If you go to this link: http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/, you will see several links for download.

Step 3:

Download the appropriate files based on the type of OS you have. For 64 bit, I would download the following deb files:

// UP-TO-DATE 2019-03-18
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500_4.15.0-041500.201802011154_all.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-image-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb

Step 4:

Install all the downloaded deb files:

sudo dpkg -i *.deb

Step 5:

Reboot your machine and check if the kernel has been updated by:

uname -aenter code here

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

JWT (JSON Web Token) automatic prolongation of expiration

How about this approach:

  • For every client request, the server compares the expirationTime of the token with (currentTime - lastAccessTime)
  • If expirationTime < (currentTime - lastAccessedTime), it changes the last lastAccessedTime to currentTime.
  • In case of inactivity on the browser for a time duration exceeding expirationTime or in case the browser window was closed and the expirationTime > (currentTime - lastAccessedTime), and then the server can expire the token and ask the user to login again.

We don't require additional end point for refreshing the token in this case. Would appreciate any feedack.

What is the right way to POST multipart/form-data using curl?

to upload a file using curl in Windows I found that the path requires escaped double quotes

e.g.

curl -v -F 'upload=@\"C:/myfile.txt\"' URL

Exploitable PHP functions

These functions can also have some nasty effects.

  • str_repeat()
  • unserialize()
  • register_tick_function()
  • register_shutdown_function()

The first two can exhaust all the available memory and the latter keep the exhaustion going...

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

Regular expression for excluding special characters

Do you really want to blacklist specific characters or rather whitelist the allowed charachters?

I assume that you actually want the latter. This is pretty simple (add any additional symbols to whitelist into the [\-] group):

^(?:\p{L}\p{M}*|[\-])*$

Edit: Optimized the pattern with the input from the comments

How to use css style in php

Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation semantics (the look and formatting) of a document written in a markup language. more info : http://en.wikipedia.org/wiki/Cascading_Style_Sheets CSS is not a programming language, and does not have the tools that come with a server side language like PHP. However, we can use Server-side languages to generate style sheets.

<html>
<head>
<title>...</title>
<style type="text/css">
table {
margin: 8px;
}

th {
font-family: Arial, Helvetica, sans-serif;
font-size: .7em;
background: #666;
color: #FFF;
padding: 2px 6px;
border-collapse: separate;
border: 1px solid #000;
}

td {
font-family: Arial, Helvetica, sans-serif;
font-size: .7em;
border: 1px solid #DDD;
}
</style>
</head>
<body>
<?php>
echo "<table>";
echo "<tr><th>ID</th><th>hashtag</th></tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr onmouseover=\"hilite(this)\" onmouseout=\"lowlite(this)\"><td>$row[0]</td>                <td>$row[1]</td></tr>\n";
}
echo "</table>";
?>
</body>
</html>

How do I read the first line of a file using cat?

cat alone may not be possible, but if you don't want to use head this works:

 cat <file> | awk 'NR == 1'

Using global variables in a function

Reference the class namespace where you want the change to show up.

In this example, runner is using max from the file config. I want my test to change the value of max when runner is using it.

main/config.py

max = 15000

main/runner.py

from main import config
def check_threads():
    return max < thread_count 

tests/runner_test.py

from main import runner                # <----- 1. add file
from main.runner import check_threads
class RunnerTest(unittest):
   def test_threads(self):
       runner.max = 0                  # <----- 2. set global 
       check_threads()

Should try...catch go inside or outside a loop?

Another aspect not mentioned in the above is the fact that every try-catch has some impact on the stack, which can have implications for recursive methods.

If method "outer()" calls method "inner()" (which may call itself recursively), try to locate the try-catch in method "outer()" if possible. A simple "stack crash" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.

In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.

How to convert string to integer in C#

Do something like:

var result = Int32.Parse(str);

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

insert datetime value in sql database with c#

you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"

Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.

DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";

sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Increase number of axis ticks

You can supply a function argument to scale, and ggplot will use that function to calculate the tick locations.

library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))
number_ticks <- function(n) {function(limits) pretty(limits, n)}

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks=number_ticks(10)) +
  scale_y_continuous(breaks=number_ticks(10))

Best way to reverse a string

Had to submit a recursive example:

private static string Reverse(string str)
{
    if (str.IsNullOrEmpty(str) || str.Length == 1)
        return str;
    else
        return str[str.Length - 1] + Reverse(str.Substring(0, str.Length - 1));
}

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

How do I set up Android Studio to work completely offline?

I'm using Android Studio 0.5.4 (Mavericks).

Preferences ? Gradle ? Global Gradle Settings ? Offline work

How to open the command prompt and insert commands using Java?

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

Javascript reduce on array of objects

After the first iteration your're returning a number and then trying to get property x of it to add to the next object which is undefined and maths involving undefined results in NaN.

try returning an object contain an x property with the sum of the x properties of the parameters:

var arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
  return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Explanation added from comments:

The return value of each iteration of [].reduce used as the a variable in the next iteration.

Iteration 1: a = {x:1}, b = {x:2}, {x: 3} assigned to a in Iteration 2

Iteration 2: a = {x:3}, b = {x:4}.

The problem with your example is that you're returning a number literal.

function (a, b) {
  return a.x + b.x; // returns number literal
}

Iteration 1: a = {x:1}, b = {x:2}, // returns 3 as a in next iteration

Iteration 2: a = 3, b = {x:2} returns NaN

A number literal 3 does not (typically) have a property called x so it's undefined and undefined + b.x returns NaN and NaN + <anything> is always NaN

Clarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.

How to check if an email address is real or valid using PHP

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>

Positioning background image, adding padding

this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center=50%, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%.

The second, and more effective way of going about this, is to use the same background-position idea, and just use background-position: 400px (width of parent) 50%;. Of course, this method requires a static width, but will give you the same thing every time.

Method 1 (99% 50%)
Method 2 (400px 50%)

Rails: Can't verify CSRF token authenticity when making a POST request

There is relevant info on a configuration of CSRF with respect to API controllers on api.rubyonrails.org:

?

It's important to remember that XML or JSON requests are also affected and if you're building an API you should change forgery protection method in ApplicationController (by default: :exception):

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

We may want to disable CSRF protection for APIs since they are typically designed to be state-less. That is, the request API client will handle the session for you instead of Rails.

?

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

JQuery: dynamic height() with window resize()

Okay, how about a CSS answer! We use display: table. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.

http://jsfiddle.net/NfmX3/3/

body { display: table; }
div { display: table-row; }
#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    background-color: blue;
    color: white;
    height: 100%;
}

How can I search (case-insensitive) in a column using LIKE wildcard?

You don't need to ALTER any table. Just use the following queries, prior to the actual SELECT query that you want to use the wildcard:

    set names `utf8`;
    SET COLLATION_CONNECTION=utf8_general_ci;
    SET CHARACTER_SET_CLIENT=utf8;
    SET CHARACTER_SET_RESULTS=utf8;

Assigning out/ref parameters in Moq

Seems like it is not possible out of the box. Looks like someone attempted a solution

See this forum post http://code.google.com/p/moq/issues/detail?id=176

this question Verify value of reference parameter with Moq

Fragment pressing back button

if you are using webview inside a fragment than use this in your onCreateView method

webView.setOnKeyListener(new View.OnKeyListener(){

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if((i==KeyEvent.KEYCODE_BACK)&& webView.canGoBack()){
                webView.goBack();
                return true;
            }
            return false;
        }
    });

and import this class

import android.view.KeyEvent;

Is there a MySQL option/feature to track history of changes to records?

It's subtle.

If the business requirement is "I want to audit the changes to the data - who did what and when?", you can usually use audit tables (as per the trigger example Keethanjan posted). I'm not a huge fan of triggers, but it has the great benefit of being relatively painless to implement - your existing code doesn't need to know about the triggers and audit stuff.

If the business requirement is "show me what the state of the data was on a given date in the past", it means that the aspect of change over time has entered your solution. Whilst you can, just about, reconstruct the state of the database just by looking at audit tables, it's hard and error prone, and for any complicated database logic, it becomes unwieldy. For instance, if the business wants to know "find the addresses of the letters we should have sent to customers who had outstanding, unpaid invoices on the first day of the month", you likely have to trawl half a dozen audit tables.

Instead, you can bake the concept of change over time into your schema design (this is the second option Keethanjan suggests). This is a change to your application, definitely at the business logic and persistence level, so it's not trivial.

For example, if you have a table like this:

CUSTOMER
---------
CUSTOMER_ID PK
CUSTOMER_NAME
CUSTOMER_ADDRESS

and you wanted to keep track over time, you would amend it as follows:

CUSTOMER
------------
CUSTOMER_ID            PK
CUSTOMER_VALID_FROM    PK
CUSTOMER_VALID_UNTIL   PK
CUSTOMER_STATUS
CUSTOMER_USER
CUSTOMER_NAME
CUSTOMER_ADDRESS

Every time you want to change a customer record, instead of updating the record, you set the VALID_UNTIL on the current record to NOW(), and insert a new record with a VALID_FROM (now) and a null VALID_UNTIL. You set the "CUSTOMER_USER" status to the login ID of the current user (if you need to keep that). If the customer needs to be deleted, you use the CUSTOMER_STATUS flag to indicate this - you may never delete records from this table.

That way, you can always find what the status of the customer table was for a given date - what was the address? Have they changed name? By joining to other tables with similar valid_from and valid_until dates, you can reconstruct the entire picture historically. To find the current status, you search for records with a null VALID_UNTIL date.

It's unwieldy (strictly speaking, you don't need the valid_from, but it makes the queries a little easier). It complicates your design and your database access. But it makes reconstructing the world a lot easier.

Use underscore inside Angular controllers

I use this:

var myapp = angular.module('myApp', [])
  // allow DI for use in controllers, unit tests
  .constant('_', window._)
  // use in views, ng-repeat="x in _.range(3)"
  .run(function ($rootScope) {
     $rootScope._ = window._;
  });

See https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection about halfway for some more info on run.

How do you set the document title in React?

React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:

Here's an example:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }

    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }

        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};

export default Title;

Just put the component in the page and set pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

What is the worst real-world macros/pre-processor abuse you've ever come across?

The obligatory

#define FOR  for

and

#define ONE  1
#define TWO  2
...

Who knew?

Prompt for user input in PowerShell

Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.

   Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )

   $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

If you want to debug and see the value of the password you just read, use:

   write-host $pw

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

I have tested all the answers here but non of them worked for me. So I decided to change angular.js file. there is a aot option there which is true. then I altered that to the false and the error vanished!

"options": {
            "outputPath": "dist/DateMeUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false, // here you have to change
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },

However, I got that there is 'tsconfig.app.json' which I couldn't find that in my project(maybe you have to add this manually ) by this file you can set the "enableIvy": false as others mention to it. tsconfig.app.json

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Get custom product attributes in Woocommerce

You can get the single value for the attribute with below code:

$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);

npm start error with create-react-app

I had the same error when running

npm start

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.

I broke my head on several tabs and applying Solutions from other devs and nothing.

Until, even using Ubuntu, I closed my vscode and restarted my pc and all my problems were solved. (kkkk zueira) just this one.

If Else If In a Sql Server Function

I think you'd be better off with a CASE statement, which works a lot more like IF/ELSEIF

DECLARE @this int, @value varchar(10)
SET @this = 200
SET @value = (
SELECT 
CASE
    WHEN @this between 5 and 10 THEN 'foo'
    WHEN @this between 10 and 15 THEN 'bar'
    WHEN @this < 0 THEN 'barfoo'
    ELSE 'foofoo'
    END
)

More info: http://technet.microsoft.com/en-us/library/ms181765.aspx

MSSQL Regular expression

Thank you all for your help.

This is what I have used in the end:

SELECT *, 
  CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' 
    THEN 'Valid' 
    ELSE 'No valid' 
  END [Validate]
FROM 
  *table*
  ORDER BY [Validate]

Regular expression to match characters at beginning of line only

Regex symbol to match at beginning of a line:

^

Add the string you're searching for (CTR) to the regex like this:

^CTR

Example: regex

That should be enough!

However, if you need to get the text from the whole line in your language of choice, add a "match anything" pattern .*:

^CTR.*

Example: more regex

If you want to get crazy, use the end of line matcher

$

Add that to the growing regex pattern:

^CTR.*$

Example: lets get crazy

Note: Depending on how and where you're using regex, you might have to use a multi-line modifier to get it to match multiple lines. There could be a whole discussion on the best strategy for picking lines out of a file to process them, and some of the strategies would require this:

Multi-line flag m (this is specified in various ways in various languages/contexts)

/^CTR.*/gm

Example: we had to use m on regex101

How do I get the title of the current active window using c#?

Loop over Application.Current.Windows[] and find the one with IsActive == true.

Please initialize the log4j system properly warning

If you are encountering the error/warning when you're running a program that uses log4j, the solution is to add a log4j.properties that can be seen by the class loader. Normally it's in the "src" folder of your Java project: Add the following contents to the file

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

Keyboard shortcut to comment lines in Sublime Text 2

For German keyboards use ctrl+shift+# to toggle a block comment and ctrl+# to toggle a line comment.

The shortcut in Preferences->Key Bindings - Default is set to Ctrl+Shift+/ and Ctrl+/, but to actually use the functions, press the keys stated above.

Call another rest api from my server in Spring-Boot

This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

Using setDate in PreparedStatement

❐ Using java.sql.Date

If your table has a column of type DATE:

  • java.lang.String

    The method java.sql.Date.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d. e.g.:

    ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
    
  • java.util.Date

    Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:

    ps.setDate(2, new java.sql.Date(endDate.getTime());
    
  • Current

    If you want to insert the current date:

    ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
    
    // Since Java 8
    ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
    

❐ Using java.sql.Timestamp

If your table has a column of type TIMESTAMP or DATETIME:

  • java.lang.String

    The method java.sql.Timestamp.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]. e.g.:

    ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");
    
  • java.util.Date

    Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:

    ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
    
  • Current

    If you require the current timestamp:

    ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
    
    // Since Java 8
    ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
    ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
    

Spring MVC 4: "application/json" Content Type is not being set correctly

I had the dependencies as specified @Greg post. I still faced the issue and could be able to resolve it by adding following additional jackson dependency:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.7.4</version>
</dependency>

How do I create HTML table using jQuery dynamically?

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

Check if value exists in the array (AngularJS)

You can use indexOf(). Like:

var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


If you want to search from end to start, use the lastIndexOf() method:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.lastIndexOf("brown");
    alert(a);

The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

Returns -1 if the item is not found.

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

Angular JS Uncaught Error: [$injector:modulerr]

Just throwing this in in case it helps, I had this issue and the reason for me was because when I bundled my Angular stuff I referenced the main app file as "AngularWebApp" instead of "AngularWebApp.js", hope this helps.

Make git automatically remove trailing whitespace before committing

Please try my pre-commit hooks, it can auto detect trailing-whitespace and remove it. Thank you!

it can work under GitBash(windows), Mac OS X and Linux!


Snapshot:

$ git commit -am "test"
auto remove trailing whitespace in foobar/main.m!
auto remove trailing whitespace in foobar/AppDelegate.m!
[master 80c11fe] test
1 file changed, 2 insertions(+), 2 deletions(-)

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

Android ClassNotFoundException: Didn't find class on path

This happens if we change Build Path of the APP, this can be in any case of Adding or Removing or Changing Libraries or .jar file. The Best solution is to Restart the Eclipse.

How to specify line breaks in a multi-line flexbox layout?

The simplest and most reliable solution is inserting flex items at the right places. If they are wide enough (width: 100%), they will force a line break.

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  width: 100px;_x000D_
  background: gold;_x000D_
  height: 100px;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px_x000D_
}_x000D_
.item:nth-child(4n - 1) {_x000D_
  background: silver;_x000D_
}_x000D_
.line-break {_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="line-break"></div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="line-break"></div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
  <div class="line-break"></div>_x000D_
  <div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But that's ugly and not semantic. Instead, we could generate pseudo-elements inside the flex container, and use order to move them to the right places.

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  width: 100px;_x000D_
  background: gold;_x000D_
  height: 100px;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
  background: silver;_x000D_
}_x000D_
.container::before, .container::after {_x000D_
  content: '';_x000D_
  width: 100%;_x000D_
  order: 1;_x000D_
}_x000D_
.item:nth-child(n + 4) {_x000D_
  order: 1;_x000D_
}_x000D_
.item:nth-child(n + 7) {_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But there is a limitation: the flex container can only have a ::before and a ::after pseudo-element. That means you can only force 2 line breaks.

To solve that, you can generate the pseudo-elements inside the flex items instead of in the flex container. This way you won't be limited to 2. But those pseudo-elements won't be flex items, so they won't be able to force line breaks.

But luckily, CSS Display L3 has introduced display: contents (currently only supported by Firefox 37):

The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.

So you can apply display: contents to the children of the flex container, and wrap the contents of each one inside an additional wrapper. Then, the flex items will be those additional wrappers and the pseudo-elements of the children.

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  display: contents;_x000D_
}_x000D_
.item > div {_x000D_
  width: 100px;_x000D_
  background: gold;_x000D_
  height: 100px;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px;_x000D_
}_x000D_
.item:nth-child(3n) > div {_x000D_
  background: silver;_x000D_
}_x000D_
.item:nth-child(3n)::after {_x000D_
  content: '';_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item"><div>1</div></div>_x000D_
  <div class="item"><div>2</div></div>_x000D_
  <div class="item"><div>3</div></div>_x000D_
  <div class="item"><div>4</div></div>_x000D_
  <div class="item"><div>5</div></div>_x000D_
  <div class="item"><div>6</div></div>_x000D_
  <div class="item"><div>7</div></div>_x000D_
  <div class="item"><div>8</div></div>_x000D_
  <div class="item"><div>9</div></div>_x000D_
  <div class="item"><div>10</div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternatively, according to Fragmenting Flex Layout and CSS Fragmentation, Flexbox allows forced breaks by using break-before, break-after or their CSS 2.1 aliases:

.item:nth-child(3n) {
  page-break-after: always; /* CSS 2.1 syntax */
  break-after: always; /* New syntax */
}

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  width: 100px;_x000D_
  background: gold;_x000D_
  height: 100px;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
  page-break-after: always;_x000D_
  background: silver;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
  <div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Forced line breaks in flexbox are not widely supported yet, but it works on Firefox.

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

Vim and Ctags tips and tricks

Several definitions of the same name

<C-w>g<C-]> open the definition in a split, but also do :tjump which either goes to the definition or, if there are several definitions, presents you with a list of definitions to choose from.

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

Android how to convert int to String?

Use Integer.toString(tmpInt) instead.

java: ArrayList - how can I check if an index exists?

Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:

Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
   // not available
}
else {
   // do something
}

Best-Practice

If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.

Control flow using exception is bad practice.

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

How to convert a Java object (bean) to key-value pairs (and vice versa)?

If it comes to a simple object tree to key value list mapping, where key might be a dotted path description from the object's root element to the leaf being inspected, it's rather obvious that a tree conversion to a key-value list is comparable to an object to xml mapping. Each element within an XML document has a defined position and can be converted into a path. Therefore I took XStream as a basic and stable conversion tool and replaced the hierarchical driver and writer parts with an own implementation. XStream also comes with a basic path tracking mechanism which - being combined with the other two - strictly leads to a solution being suitable for the task.

How can I retrieve a table from stored procedure to a datatable?

Explaining if any one want to send some parameters while calling stored procedure as below,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

Generating Random Number In Each Row In Oracle Query

At first I thought that this would work:

select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:

select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.

I'd suggest using something like:

floor(dbms_random.value(1,10))

Hence:

select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953

Switch: Multiple values in one case?

What about this?

switch (true) 
{
    case (age >= 1 && age <= 8):
        MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
    break;
    case (age >= 9 && age <= 15):
        MessageBox.Show("You are only " + age + " years old\n That's too young!");
    break;
    case (age >= 16 && age <= 100):
        MessageBox.Show("You are " + age + " years old\n Perfect.");
    break;
    default:
        MessageBox.Show("You an old person.");
    break;
}

Cheers

CR LF notepad++ removal

Please find the below screenshot

enter image description here

enter image description here

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

Extract a substring according to a pattern

Another method to extract a substring

library(stringr)
substring <- str_extract(string, regex("(?<=:).*"))
#[1] "E001" "E002" "E003
  • (?<=:): look behind the colon (:)

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Difference between object and class in Scala

The object is similar to the static class in Java to some extend, the static characteristic means the static class need not to create an object when putting to the JVM, it can be used by it's class name directly and the same instance(same data state) is shared wherever it is used.

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

Write lines of text to a file in R

Actually you can do it with sink():

sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()

hence do:

file.show("outfile.txt")
# hello
# world

What is pluginManagement in Maven's pom.xml?

So if i understood well, i would say that <pluginManagement> just like <dependencyManagement> are both used to share only the configuration between a parent and it's sub-modules.

For that we define the dependencie's and plugin's common configurations in the parent project and then we only have to declare the dependency/plugin in the sub-modules to use it, without having to define a configuration for it (i.e version or execution, goals, etc). Though this does not prevent us from overriding the configuration in the submodule.

In contrast <dependencies> and <plugins> are inherited along with their configurations and should not be redeclared in the sub-modules, otherwise a conflict would occur.

is that right ?

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

Create an Array of Arraylists

The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant

How to identify all stored procedures referring a particular table

sometimes above queries will not give correct result, there is built in stored procedure available to get the table dependencies as:

EXEC sp_depends @objname = N'TableName';

Apache 13 permission denied in user's home directory

Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.

If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:

sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html

See if one of those gives you the "permission denied" error.

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

Speed up rsync with Simultaneous/Concurrent File Transfers?

You can use xargs which supports running many processes at a time. For your case it will be:

ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

How do I get this javascript to run every second?

You can use setInterval:

var timer = setInterval( myFunction, 1000);

Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.

What is the difference between ndarray and array in numpy?

I think with np.array() you can only create C like though you mention the order, when you check using np.isfortran() it says false. but with np.ndarrray() when you specify the order it creates based on the order provided.

Type converting slices of interfaces

Convert interface{} into any type.

Syntax:

result := interface.(datatype)

Example:

var employee interface{} = []string{"Jhon", "Arya"}
result := employee.([]string)   //result type is []string.

Font Awesome not working, icons showing as squares

font-weight: 900;

I had a different issue with Font Awesome 5. Default font-weight should be 900 for FontAwesome icons but I overwrote it to 400 for span and i tags. It just worked, when I corrected it.

Here is the issue reference in their Github page, https://github.com/FortAwesome/Font-Awesome/issues/11946

I hope it will help someone.

Using multiple delimiters in awk

Perl one-liner:

perl -F'/[\/=]/' -lane 'print "$F[2]\t$F[4]\t$F[7]"' file

These command-line options are used:

  • -n loop around every line of the input file, put the line in the $_ variable, do not automatically print every line

  • -l removes newlines before processing, and adds them back in afterwards

  • -a autosplit mode – perl will automatically split input lines into the @F array. Defaults to splitting on whitespace

  • -F autosplit modifier, in this example splits on either / or =

  • -e execute the perl code

Perl is closely related to awk, however, the @F autosplit array starts at index $F[0] while awk fields start with $1.

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0

Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".

Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"

public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
    var currentIPaddress = ipInfo.Address.ToString();
    var currentSubnetMask = ipInfo.IPv4Mask.ToString();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

public bool SetDHCP(string networkInterfaceName)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (isDHCPenabled)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

Node.js: socket.io close client connection

Just try socket.disconnect(true) on the server side by emitting any event from the client side.

How can I pass arguments to anonymous functions in JavaScript?

Example:

<input type="button" value="Click me" id="myButton">
<script>
    var myButton = document.getElementById("myButton");
    var test = "zipzambam";
    myButton.onclick = function(eventObject) {
        if (!eventObject) {
            eventObject = window.event;
        }
        if (!eventObject.target) {
            eventObject.target = eventObject.srcElement;
        }
        alert(eventObject.target);
        alert(test);
    };
    (function(myMessage) {
        alert(myMessage);
    })("Hello");
</script>

How do I get the last word in each line with bash

there are many ways. as awk solutions shows, it's the clean solution

sed solution is to delete anything till the last space. So if there is no space at the end, it should work

sed 's/.* //g' <file>

you can avoid sed also and go for a while loop.

while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file

it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back

the same can be done in a pure bash way

while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file

it is called parameter expansion

Selecting a Linux I/O Scheduler

It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like

# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"

inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules). This answer is based on the debian wiki

To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:

for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done

Button Listener for button in fragment in android

Try this :

FragmentOne.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentOne extends Fragment{

    View rootView;        

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_one, container, false);


        Button button = (Button) rootView.findViewById(R.id.buttonSayHi);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                onButtonClicked(v);
            }
        });
        return rootView;
    }

  public void onButtonClicked(View view)
  {
          //do your stuff here..           
    final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag"); 
    ft.commit(); 

    ft.addToBackStack(null);    
  }
}

check this : click here

How to convert a Django QuerySet to a list

It is a little hard to follow what you are really trying to do. Your first statement looks like you may be fetching the same exact QuerySet of Answer objects twice. First via answer_set.answers.all() and then again via .filter(id__in=...). Double check in the shell and see if this will give you the list of answers you are looking for:

answers = answer_set.answers.all()

Once you have that cleaned up so it is a little easier for you (and others working on the code) to read you might want to look into .exclude() and the __in field lookup.

existing_question_answers = QuestionAnswer.objects.filter(...)

new_answers = answers.exclude(question_answer__in=existing_question_answers)

The above lookup might not sync up with your model definitions but it will probably get you close enough to finish the job yourself.

If you still need to get a list of id values then you want to play with .values_list(). In your case you will probably want to add the optional flat=True.

answers.values_list('id', flat=True)

Need to ZIP an entire directory using Node.js

Archive.bulk is now deprecated, the new method to be used for this is glob:

var fileName =   'zipOutput.zip'
var fileOutput = fs.createWriteStream(fileName);

fileOutput.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.pipe(fileOutput);
archive.glob("../dist/**/*"); //some glob pattern here
archive.glob("../dist/.htaccess"); //another glob pattern
// add as many as you like
archive.on('error', function(err){
    throw err;
});
archive.finalize();

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

REST / SOAP endpoints for a WCF service

This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Inside service model

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

EndPoint Behaviour

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

How to get 0-padded binary representation of an integer in java?

A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":

private String toBinaryString32(int i) {
    String binaryWithOutLeading0 = Integer.toBinaryString(i);
    return "00000000000000000000000000000000"
            .substring(binaryWithOutLeading0.length())
            + binaryWithOutLeading0;
}

Git Cherry-Pick and Conflicts

Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.

So you could something like this git cherry-pick --strategy=recursive -X theirs commit or git cherry-pick --strategy=recursive -X ours commit

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

SQL Delete Records within a specific Range

you can also just change your delete to a select *

and test your selection

the records selected will be the same as the ones deleted

you can also wrap your statement in a begin / rollback if you are not sure - test the statement then if all is good remove rollback

for example

SELECT * FROM table WHERE id BETWEEN 79 AND 296

will show all the records matching the where if they are the wants you 'really' want to delete then use

DELETE FROM table WHERE id BETWEEN 79 AND 296

You can also create a trigger / which catches deletes and puts them into a history table

so if you delete something by mistake you can always get it back

(keep your history table records no older than say 6 months or whatever business rules say)

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

The ideas provided above are good. For fast access (in case you would like to make a real time application) you could try the following:

//suppose you read an image from a file that is gray scale
Mat image = imread("Your path", CV_8UC1);
//...do some processing
uint8_t *myData = image.data;
int width = image.cols;
int height = image.rows;
int _stride = image.step;//in case cols != strides
for(int i = 0; i < height; i++)
{
    for(int j = 0; j < width; j++)
    {
        uint8_t val = myData[ i * _stride + j];
        //do whatever you want with your value
    }
}

Pointer access is much faster than the Mat.at<> accessing. Hope it helps!

How to get the last row of an Oracle a table

You can do it like this:

SELECT * FROM (SELECT your_table.your_field, versions_starttime
               FROM your_table
               VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE)
WHERE ROWNUM = 1;

Or:

SELECT your_field,ora_rowscn,scn_to_timestamp(ora_rowscn) from your_table WHERE ROWNUM = 1;

How to create a multiline UITextfield?

UITextField is specifically one-line only.

Your Google search is correct, you need to use UITextView instead of UITextField for display and editing of multiline text.

In Interface Builder, add a UITextView where you want it and select the "editable" box. It will be multiline by default.

How do I remove lines between ListViews on Android?

I find it easier to implement it in the XML file as it can be harder to trace the line of code in a class with hundreds of lines. For the XML you can use "null":

android:divider="@null"

How to concatenate int values in java?

I would suggest converting them to Strings.

StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);

Then converting back to an Integer:

Integer.valueOf(concatenated.toString());

When is it acceptable to call GC.Collect?

As a memory fragmentation solution. I was getting out of memory exceptions while writing a lot of data into a memory stream (reading from a network stream). The data was written in 8K chunks. After reaching 128M there was exception even though there was a lot of memory available (but it was fragmented). Calling GC.Collect() solved the issue. I was able to handle over 1G after the fix.

Get name of current script in Python

For modern Python versions (3.4+), Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

http://lists.mysql.com/mysql/197901

Handle Button click inside a row in RecyclerView

I find that typically:

  • I need to use multiple listeners because I have several buttons.
  • I want my logic to be in the activity and not the adapter or viewholder.

So @mark-keen's answer works well but having an interface provides more flexibility:

public static class MyViewHolder extends RecyclerView.ViewHolder {

    public ImageView iconImageView;
    public TextView iconTextView;

    public MyViewHolder(final View itemView) {
        super(itemView);

        iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
        iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

        iconTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickListener.iconTextViewOnClick(v, getAdapterPosition());
            }
        });
        iconImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickListener.iconImageViewOnClick(v, getAdapterPosition());
            }
        });
    }
}

Where onClickListener is defined in your adapter:

public MyAdapterListener onClickListener;

public interface MyAdapterListener {

    void iconTextViewOnClick(View v, int position);
    void iconImageViewOnClick(View v, int position);
}

And probably set through your constructor:

public MyAdapter(ArrayList<MyListItems> newRows, MyAdapterListener listener) {

    rows = newRows;
    onClickListener = listener;
}

Then you can handle the events in your Activity or wherever your RecyclerView is being used:

mAdapter = new MyAdapter(mRows, new MyAdapter.MyAdapterListener() {
                    @Override
                    public void iconTextViewOnClick(View v, int position) {
                        Log.d(TAG, "iconTextViewOnClick at position "+position);
                    }

                    @Override
                    public void iconImageViewOnClick(View v, int position) {
                        Log.d(TAG, "iconImageViewOnClick at position "+position);
                    }
                });
mRecycler.setAdapter(mAdapter);

Displaying Image in Java

Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?

How to get file extension from string in C++

If you use Qt library, you can give a try to QFileInfo's suffix()

Open a file with Notepad in C#

You need System.Diagnostics.Process.Start().

The simplest example:

Process.Start("notepad.exe", fileName);

More Generic Approach:

Process.Start(fileName);

The second approach is probably a better practice as this will cause the windows Shell to open up your file with it's associated editor. Additionally, if the file specified does not have an association, it'll use the Open With... dialog from windows.

Note to those in the comments, thankyou for your input. My quick n' dirty answer was slightly off, i've updated the answer to reflect the correct way.

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

MySQL error 2006: mysql server has gone away

If you know you're going offline for a while, you can close your connection, do your processing, reconnect and write your reports.

What's the difference between Docker Compose vs. Dockerfile

Dockerfile is a file that contains text commands to assemble an image.

Docker compose is used to run a multi-container environment.

In your specific scenario, if you have multiple services for each technology you mentioned (service 1 using reddis, service 2 using rabbit mq etc), then you can have a Dockerfile for each of the services and a common docker-compose.yml to run all the "Dockerfile" as containers.

If you want them all in a single service, docker-compose will be a viable option.

Call function with setInterval in jQuery?

First of all: Yes you can mix jQuery with common JS :)

Best way to build up an intervall call of a function is to use setTimeout methode:

For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:

function test(){
    console.log('test called');
    setTimeout(test, 5000);
}

Finally you have to trigger the function once:

$(document).ready(function(){
    test();
});

This document ready function is called automatically, after all html is loaded.

How can building a heap be O(n) time complexity?

Intuitively:

"The complexity should be O(nLog n)... for each item we "heapify", it has the potential to have to filter down once for each level for the heap so far (which is log n levels)."

Not quite. Your logic does not produce a tight bound -- it over estimates the complexity of each heapify. If built from the bottom up, insertion (heapify) can be much less than O(log(n)). The process is as follows:

( Step 1 ) The first n/2 elements go on the bottom row of the heap. h=0, so heapify is not needed.

( Step 2 ) The next n/22 elements go on the row 1 up from the bottom. h=1, heapify filters 1 level down.

( Step i ) The next n/2i elements go in row i up from the bottom. h=i, heapify filters i levels down.

( Step log(n) ) The last n/2log2(n) = 1 element goes in row log(n) up from the bottom. h=log(n), heapify filters log(n) levels down.

NOTICE: that after step one, 1/2 of the elements (n/2) are already in the heap, and we didn't even need to call heapify once. Also, notice that only a single element, the root, actually incurs the full log(n) complexity.


Theoretically:

The Total steps N to build a heap of size n, can be written out mathematically.

At height i, we've shown (above) that there will be n/2i+1 elements that need to call heapify, and we know heapify at height i is O(i). This gives:

enter image description here

The solution to the last summation can be found by taking the derivative of both sides of the well known geometric series equation:

enter image description here

Finally, plugging in x = 1/2 into the above equation yields 2. Plugging this into the first equation gives:

enter image description here

Thus, the total number of steps is of size O(n)

Using setattr() in python

I'm here in general only to find out that through dict it is necessary to work inside setattr XD

How to sort a list of lists by a specific index of the inner list?

array.sort(key = lambda x:x[1])

You can easily sort using this snippet, where 1 is the index of the element.

How to call javascript function on page load in asp.net

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in asp.net c#

Type.GetType("namespace.a.b.ClassName") returns null

I am opening user controls depending on what user controls the user have access to specified in a database. So I used this method to get the TypeName...

Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))

So now one can use the value returned in strType to create an instance of that object.

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

Php multiple delimiters in explode

If your delimiter is only characters, you can use strtok, which seems to be more fit here. Note that you must use it with a while loop to achieve the effects.

Split string with string as delimiter

@ECHO OFF
SETLOCAL
SET "string=string1 by string2.txt"
SET "string=%string:* by =%"
ECHO +%string%+

GOTO :EOF

The above SET command will remove the unwanted data. Result shown between + to demonstrate absence of spaces.

Formula: set var=%somevar:*string1=string2%

will assign to var the value of somevar with all characters up to string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.

Split long commands in multiple lines through Windows batch file

(This is basically a rewrite of Wayne's answer but with the confusion around the caret cleared up. So I've posted it as a CW. I'm not shy about editing answers, but completely rewriting them seems inappropriate.)

You can break up long lines with the caret (^), just remember that the caret and the newline that follows it are removed entirely from the command, so if you put it where a space would be required (such as between parameters), be sure to include the space as well (either before the ^, or at the beginning of the next line — that latter choice may help make it clearer it's a continuation).

Examples: (all tested on Windows XP and Windows 7)

xcopy file1.txt file2.txt

can be written as:

xcopy^
 file1.txt^
 file2.txt

or

xcopy ^
file1.txt ^
file2.txt

or even

xc^
opy ^
file1.txt ^
file2.txt

(That last works because there are no spaces betwen the xc and the ^, and no spaces at the beginning of the next line. So when you remove the ^ and the newline, you get...xcopy.)

For readability and sanity, it's probably best breaking only between parameters (be sure to include the space).

Be sure that the ^ is not the last thing in a batch file, as there appears to be a major issue with that.

cannot load such file -- bundler/setup (LoadError)

Bundler Version maybe cause the issue.

Please install bundler with other version number.

For example,

gem install bundler -v 1.0.10

Set background image in CSS using jquery

try this

 $(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");

How to change package name of an Android Application

The fastest way to do that in Android Studio 1.3:

  1. Change the package name in the manifest
  2. Go to Module Settings[F4]-> Flavors, into Application Id write the same name.
  3. Create new package with that name: [right-click-> new-> package]
  4. Select all java files of your project and then proceed [Right-click-> Refactor-> Move-> {Select package}-> Refactor]

P.S. If you will not follow this order you can end up changing all the java files one by one with new imports and a bunch of compile time errors, so the order is very important.

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

AngularJS Multiple ng-app within a page

To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap()

HTML

<!-- Automatic Initialization -->
<div ng-app="myFirstModule">
    ...
</div>
<!-- Need To Manually Bootstrap All Other Modules -->
<div id="module2">
    ...
</div>

JS

angular.
  bootstrap(document.getElementById("module2"), ['mySecondModule']);

The reason for this is that only one AngularJS application can be automatically bootstrapped per HTML document. The first ng-app found in the document will be used to define the root element to auto-bootstrap as an application.

In other words, while it is technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework.

What does 'corrupted double-linked list' mean

I ran into this error in some code where someone was calling exit() in one thread about the same time as main() returned, so all the global/static constructors were being kicked off in two separate threads simultaneously.

This error also manifests as double free or corruption, or a segfault/sig11 inside exit() or inside malloc_consolidate, and likely others. The call stack for the malloc_consolidate crash may resemble:

#0  0xabcdabcd in malloc_consolidate () from /lib/libc.so.6
#1  0xabcdabcd in _int_free () from /lib/libc.so.6
#2  0xabcdabcd in operator delete (...)
#3  0xabcdabcd in operator delete[] (...)
(...)

I couldn't get it to exhibit this problem while running under valgrind.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

My pod kept crashing and I was unable to find the cause. Luckily there is a space where kubernetes saves all the events that occurred before my pod crashed.
(#List Events sorted by timestamp)

To see these events run the command:

kubectl get events --sort-by=.metadata.creationTimestamp

make sure to add a --namespace mynamespace argument to the command if needed

The events shown in the output of the command showed my why my pod kept crashing.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Simple dictionary in C++

BASEPAIRS = { "T": "A", "A": "T", "G": "C", "C": "G" } What would you use?

Maybe:

static const char basepairs[] = "ATAGCG";
// lookup:
if (const char* p = strchr(basepairs, c))
    // use p[1]

;-)

How to convert a double to long without casting?

Simply put, casting is more efficient than creating a Double object.

Better techniques for trimming leading zeros in SQL Server?

Other answers here to not take into consideration if you have all-zero's (or even a single zero).
Some always default an empty string to zero, which is wrong when it is supposed to remain blank.
Re-read the original question. This answers what the Questioner wants.

Solution #1:

--This example uses both Leading and Trailing zero's.
--Avoid losing those Trailing zero's and converting embedded spaces into more zeros.
--I added a non-whitespace character ("_") to retain trailing zero's after calling Replace().
--Simply remove the RTrim() function call if you want to preserve trailing spaces.
--If you treat zero's and empty-strings as the same thing for your application,
--  then you may skip the Case-Statement entirely and just use CN.CleanNumber .
DECLARE @WackadooNumber VarChar(50) = ' 0 0123ABC D0 '--'000'--
SELECT WN.WackadooNumber, CN.CleanNumber,
       (CASE WHEN WN.WackadooNumber LIKE '%0%' AND CN.CleanNumber = '' THEN '0' ELSE CN.CleanNumber END)[AllowZero]
 FROM (SELECT @WackadooNumber[WackadooNumber]) AS WN
 OUTER APPLY (SELECT RTRIM(RIGHT(WN.WackadooNumber, LEN(LTRIM(REPLACE(WN.WackadooNumber + '_', '0', ' '))) - 1))[CleanNumber]) AS CN
--Result: "123ABC D0"

Solution #2 (with sample data):

SELECT O.Type, O.Value, Parsed.Value[WrongValue],
       (CASE WHEN CHARINDEX('0', T.Value)  > 0--If there's at least one zero.
              AND LEN(Parsed.Value) = 0--And the trimmed length is zero.
             THEN '0' ELSE Parsed.Value END)[FinalValue],
       (CASE WHEN CHARINDEX('0', T.Value)  > 0--If there's at least one zero.
              AND LEN(Parsed.TrimmedValue) = 0--And the trimmed length is zero.
             THEN '0' ELSE LTRIM(RTRIM(Parsed.TrimmedValue)) END)[FinalTrimmedValue]
  FROM 
  (
    VALUES ('Null', NULL), ('EmptyString', ''),
           ('Zero', '0'), ('Zero', '0000'), ('Zero', '000.000'),
           ('Spaces', '    0   A B C '), ('Number', '000123'),
           ('AlphaNum', '000ABC123'), ('NoZero', 'NoZerosHere')
  ) AS O(Type, Value)--O is for Original.
  CROSS APPLY
  ( --This Step is Optional.  Use if you also want to remove leading spaces.
    SELECT LTRIM(RTRIM(O.Value))[Value]
  ) AS T--T is for Trimmed.
  CROSS APPLY
  ( --From @CadeRoux's Post.
    SELECT SUBSTRING(O.Value, PATINDEX('%[^0]%', O.Value + '.'), LEN(O.Value))[Value],
           SUBSTRING(T.Value, PATINDEX('%[^0]%', T.Value + '.'), LEN(T.Value))[TrimmedValue]
  ) AS Parsed

Results:

MikeTeeVee_SQL_Server_Remove_Leading_Zeros

Summary:

You could use what I have above for a one-off removal of leading-zero's.
If you plan on reusing it a lot, then place it in an Inline-Table-Valued-Function (ITVF).
Your concerns about performance problems with UDF's is understandable.
However, this problem only applies to All-Scalar-Functions and Multi-Statement-Table-Functions.
Using ITVF's is perfectly fine.

I have the same problem with our 3rd-Party database.
With Alpha-Numeric fields many are entered in without the leading spaces, dang humans!
This makes joins impossible without cleaning up the missing leading-zeros.

Conclusion:

Instead of removing the leading-zeros, you may want to consider just padding your trimmed-values with leading-zeros when you do your joins.
Better yet, clean up your data in the table by adding leading zeros, then rebuilding your indexes.
I think this would be WAY faster and less complex.

SELECT RIGHT('0000000000' + LTRIM(RTRIM(NULLIF(' 0A10  ', ''))), 10)--0000000A10
SELECT RIGHT('0000000000' + LTRIM(RTRIM(NULLIF('', ''))), 10)--NULL --When Blank.

How to get substring from string in c#?

You could do this manually or using IndexOf method.

Manually:

int index = 43;
string piece = myString.Substring(index);

Using IndexOf you can see where the fullstop is:

int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);

Error message "Strict standards: Only variables should be passed by reference"

Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.

$monthly_index = @array_shift(unpack('H*', date('m/Y')));

It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.

As result, I am sure your friend 'system administrator' will be pleased with a less polluted error.log.

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

It sounds like installing the VS2017 update for that specific version didn't also install the .NET Core 2.0 SDK. You can download that here.

To check which version of the SDK you've already got installed, run

dotnet --info

from the command line. Note that if there's a global.json file in either your current working directory or any ancestor directory, that will override which version of the SDK is run. (That's useful if you want to enforce a particular version for a project, for example.)

Judging by comments, some versions of VS2017 updates do install the .NET Core SDK. I suspect it may vary somewhat over time.

Convert a tensor to numpy array in Tensorflow?

You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy

Check if a file exists or not in Windows PowerShell?

cls

$exactadminfile = "C:\temp\files\admin" #First folder to check the file

$userfile = "C:\temp\files\user" #Second folder to check the file

$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations

foreach ($filename in $filenames) {
  if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
    Write-Warning "$filename absent from both locations"
  } else {
    Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
  }
}

Copy array items into another array

The function below doesn't have an issue with the length of arrays and performs better than all suggested solutions:

function pushArray(list, other) {
    var len = other.length;
    var start = list.length;
    list.length = start + len;
    for (var i = 0; i < len; i++ , start++) {
        list[start] = other[i];
    }
}

unfortunately, jspref refuses to accept my submissions, so here they are the results using benchmark.js

        Name            |   ops/sec   |  ± %  | runs sampled
for loop and push       |      177506 |  0.92 | 63
Push Apply              |      234280 |  0.77 | 66
spread operator         |      259725 |  0.40 | 67
set length and for loop |      284223 |  0.41 | 66

where

for loop and push is:

    for (var i = 0, l = source.length; i < l; i++) {
        target.push(source[i]);
    }

Push Apply:

target.push.apply(target, source);

spread operator:

    target.push(...source);

and finally the 'set length and for loop' is the above function

phonegap open link in browser

None of these answers are explicit enough to get external links to open in each platform. As per the inAppBrowser docs:

Install

cordova plugin add cordova-plugin-inappbrowser

Overwrite window.open (optional, but recommended for simplicity)

window.open = cordova.InAppBrowser.open;

If you don't overwrite window.open, you will be using the native window.open function, and can't expect to get the same results cross-platform.

Use it to open links in default browser

window.open(your_href_value, '_system');

Note that the target for the inAppBrowser (which is what the plugin name suggests it is to be used for) is '_blank', instead of '_system'.


Without the steps above, I was not able to get links to open in the default browser app cross-platform.

Extra credit

Here's an example (live) click handler for the links:

document.addEventListener('click', function (e) {
    if (e.target.tagName === 'A' &&
        e.target.href.match(/^https?:\/\//)) {
        e.preventDefault();
        window.open(e.target.href, '_system');
    }
});

How do I install cURL on cygwin?

If you don't see a certain package, you can access to a full list of ports (also unnoficials, the packages you see on the web) launching the setup.exe with -k argument with value http://cygwinports.org/ports.gpg (example: C:\cygwin\setup\setup-x86.exe -K http://cygwinports.org/ports.gpg).

Doing so, you can choose a lot of extra packages, also extra versions of cURL (compat one). I do that to get Apache, cUrl, php5, php5-curl and some others :)

I don't know if apt-cyg can get those extra packages.

How to split a string into an array in Bash?

All of the answers to this question are wrong in one way or another.


Wrong answer #1

IFS=', ' read -r -a array <<< "$string"

1: This is a misuse of $IFS. The value of the $IFS variable is not taken as a single variable-length string separator, rather it is taken as a set of single-character string separators, where each field that read splits off from the input line can be terminated by any character in the set (comma or space, in this example).

Actually, for the real sticklers out there, the full meaning of $IFS is slightly more involved. From the bash manual:

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters <space>, <tab>, and <newline> are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.

Basically, for non-default non-null values of $IFS, fields can be separated with either (1) a sequence of one or more characters that are all from the set of "IFS whitespace characters" (that is, whichever of <space>, <tab>, and <newline> ("newline" meaning line feed (LF)) are present anywhere in $IFS), or (2) any non-"IFS whitespace character" that's present in $IFS along with whatever "IFS whitespace characters" surround it in the input line.

For the OP, it's possible that the second separation mode I described in the previous paragraph is exactly what he wants for his input string, but we can be pretty confident that the first separation mode I described is not correct at all. For example, what if his input string was 'Los Angeles, United States, North America'?

IFS=', ' read -ra a <<<'Los Angeles, United States, North America'; declare -p a;
## declare -a a=([0]="Los" [1]="Angeles" [2]="United" [3]="States" [4]="North" [5]="America")

2: Even if you were to use this solution with a single-character separator (such as a comma by itself, that is, with no following space or other baggage), if the value of the $string variable happens to contain any LFs, then read will stop processing once it encounters the first LF. The read builtin only processes one line per invocation. This is true even if you are piping or redirecting input only to the read statement, as we are doing in this example with the here-string mechanism, and thus unprocessed input is guaranteed to be lost. The code that powers the read builtin has no knowledge of the data flow within its containing command structure.

You could argue that this is unlikely to cause a problem, but still, it's a subtle hazard that should be avoided if possible. It is caused by the fact that the read builtin actually does two levels of input splitting: first into lines, then into fields. Since the OP only wants one level of splitting, this usage of the read builtin is not appropriate, and we should avoid it.

3: A non-obvious potential issue with this solution is that read always drops the trailing field if it is empty, although it preserves empty fields otherwise. Here's a demo:

string=', , a, , b, c, , , '; IFS=', ' read -ra a <<<"$string"; declare -p a;
## declare -a a=([0]="" [1]="" [2]="a" [3]="" [4]="b" [5]="c" [6]="" [7]="")

Maybe the OP wouldn't care about this, but it's still a limitation worth knowing about. It reduces the robustness and generality of the solution.

This problem can be solved by appending a dummy trailing delimiter to the input string just prior to feeding it to read, as I will demonstrate later.


Wrong answer #2

string="1:2:3:4:5"
set -f                     # avoid globbing (expansion of *).
array=(${string//:/ })

Similar idea:

t="one,two,three"
a=($(echo $t | tr ',' "\n"))

(Note: I added the missing parentheses around the command substitution which the answerer seems to have omitted.)

Similar idea:

string="1,2,3,4"
array=(`echo $string | sed 's/,/\n/g'`)

These solutions leverage word splitting in an array assignment to split the string into fields. Funnily enough, just like read, general word splitting also uses the $IFS special variable, although in this case it is implied that it is set to its default value of <space><tab><newline>, and therefore any sequence of one or more IFS characters (which are all whitespace characters now) is considered to be a field delimiter.

This solves the problem of two levels of splitting committed by read, since word splitting by itself constitutes only one level of splitting. But just as before, the problem here is that the individual fields in the input string can already contain $IFS characters, and thus they would be improperly split during the word splitting operation. This happens to not be the case for any of the sample input strings provided by these answerers (how convenient...), but of course that doesn't change the fact that any code base that used this idiom would then run the risk of blowing up if this assumption were ever violated at some point down the line. Once again, consider my counterexample of 'Los Angeles, United States, North America' (or 'Los Angeles:United States:North America').

Also, word splitting is normally followed by filename expansion (aka pathname expansion aka globbing), which, if done, would potentially corrupt words containing the characters *, ?, or [ followed by ] (and, if extglob is set, parenthesized fragments preceded by ?, *, +, @, or !) by matching them against file system objects and expanding the words ("globs") accordingly. The first of these three answerers has cleverly undercut this problem by running set -f beforehand to disable globbing. Technically this works (although you should probably add set +f afterward to reenable globbing for subsequent code which may depend on it), but it's undesirable to have to mess with global shell settings in order to hack a basic string-to-array parsing operation in local code.

Another issue with this answer is that all empty fields will be lost. This may or may not be a problem, depending on the application.

Note: If you're going to use this solution, it's better to use the ${string//:/ } "pattern substitution" form of parameter expansion, rather than going to the trouble of invoking a command substitution (which forks the shell), starting up a pipeline, and running an external executable (tr or sed), since parameter expansion is purely a shell-internal operation. (Also, for the tr and sed solutions, the input variable should be double-quoted inside the command substitution; otherwise word splitting would take effect in the echo command and potentially mess with the field values. Also, the $(...) form of command substitution is preferable to the old `...` form since it simplifies nesting of command substitutions and allows for better syntax highlighting by text editors.)


Wrong answer #3

str="a, b, c, d"  # assuming there is a space after ',' as in Q
arr=(${str//,/})  # delete all occurrences of ','

This answer is almost the same as #2. The difference is that the answerer has made the assumption that the fields are delimited by two characters, one of which being represented in the default $IFS, and the other not. He has solved this rather specific case by removing the non-IFS-represented character using a pattern substitution expansion and then using word splitting to split the fields on the surviving IFS-represented delimiter character.

This is not a very generic solution. Furthermore, it can be argued that the comma is really the "primary" delimiter character here, and that stripping it and then depending on the space character for field splitting is simply wrong. Once again, consider my counterexample: 'Los Angeles, United States, North America'.

Also, again, filename expansion could corrupt the expanded words, but this can be prevented by temporarily disabling globbing for the assignment with set -f and then set +f.

Also, again, all empty fields will be lost, which may or may not be a problem depending on the application.


Wrong answer #4

string='first line
second line
third line'

oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"

This is similar to #2 and #3 in that it uses word splitting to get the job done, only now the code explicitly sets $IFS to contain only the single-character field delimiter present in the input string. It should be repeated that this cannot work for multicharacter field delimiters such as the OP's comma-space delimiter. But for a single-character delimiter like the LF used in this example, it actually comes close to being perfect. The fields cannot be unintentionally split in the middle as we saw with previous wrong answers, and there is only one level of splitting, as required.

One problem is that filename expansion will corrupt affected words as described earlier, although once again this can be solved by wrapping the critical statement in set -f and set +f.

Another potential problem is that, since LF qualifies as an "IFS whitespace character" as defined earlier, all empty fields will be lost, just as in #2 and #3. This would of course not be a problem if the delimiter happens to be a non-"IFS whitespace character", and depending on the application it may not matter anyway, but it does vitiate the generality of the solution.

So, to sum up, assuming you have a one-character delimiter, and it is either a non-"IFS whitespace character" or you don't care about empty fields, and you wrap the critical statement in set -f and set +f, then this solution works, but otherwise not.

(Also, for information's sake, assigning a LF to a variable in bash can be done more easily with the $'...' syntax, e.g. IFS=$'\n';.)


Wrong answer #5

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

Similar idea:

IFS=', ' eval 'array=($string)'

This solution is effectively a cross between #1 (in that it sets $IFS to comma-space) and #2-4 (in that it uses word splitting to split the string into fields). Because of this, it suffers from most of the problems that afflict all of the above wrong answers, sort of like the worst of all worlds.

Also, regarding the second variant, it may seem like the eval call is completely unnecessary, since its argument is a single-quoted string literal, and therefore is statically known. But there's actually a very non-obvious benefit to using eval in this way. Normally, when you run a simple command which consists of a variable assignment only, meaning without an actual command word following it, the assignment takes effect in the shell environment:

IFS=', '; ## changes $IFS in the shell environment

This is true even if the simple command involves multiple variable assignments; again, as long as there's no command word, all variable assignments affect the shell environment:

IFS=', ' array=($countries); ## changes both $IFS and $array in the shell environment

But, if the variable assignment is attached to a command name (I like to call this a "prefix assignment") then it does not affect the shell environment, and instead only affects the environment of the executed command, regardless whether it is a builtin or external:

IFS=', ' :; ## : is a builtin command, the $IFS assignment does not outlive it
IFS=', ' env; ## env is an external command, the $IFS assignment does not outlive it

Relevant quote from the bash manual:

If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment.

It is possible to exploit this feature of variable assignment to change $IFS only temporarily, which allows us to avoid the whole save-and-restore gambit like that which is being done with the $OIFS variable in the first variant. But the challenge we face here is that the command we need to run is itself a mere variable assignment, and hence it would not involve a command word to make the $IFS assignment temporary. You might think to yourself, well why not just add a no-op command word to the statement like the : builtin to make the $IFS assignment temporary? This does not work because it would then make the $array assignment temporary as well:

IFS=', ' array=($countries) :; ## fails; new $array value never escapes the : command

So, we're effectively at an impasse, a bit of a catch-22. But, when eval runs its code, it runs it in the shell environment, as if it was normal, static source code, and therefore we can run the $array assignment inside the eval argument to have it take effect in the shell environment, while the $IFS prefix assignment that is prefixed to the eval command will not outlive the eval command. This is exactly the trick that is being used in the second variant of this solution:

IFS=', ' eval 'array=($string)'; ## $IFS does not outlive the eval command, but $array does

So, as you can see, it's actually quite a clever trick, and accomplishes exactly what is required (at least with respect to assignment effectation) in a rather non-obvious way. I'm actually not against this trick in general, despite the involvement of eval; just be careful to single-quote the argument string to guard against security threats.

But again, because of the "worst of all worlds" agglomeration of problems, this is still a wrong answer to the OP's requirement.


Wrong answer #6

IFS=', '; array=(Paris, France, Europe)

IFS=' ';declare -a array=(Paris France Europe)

Um... what? The OP has a string variable that needs to be parsed into an array. This "answer" starts with the verbatim contents of the input string pasted into an array literal. I guess that's one way to do it.

It looks like the answerer may have assumed that the $IFS variable affects all bash parsing in all contexts, which is not true. From the bash manual:

IFS    The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is <space><tab><newline>.

So the $IFS special variable is actually only used in two contexts: (1) word splitting that is performed after expansion (meaning not when parsing bash source code) and (2) for splitting input lines into words by the read builtin.

Let me try to make this clearer. I think it might be good to draw a distinction between parsing and execution. Bash must first parse the source code, which obviously is a parsing event, and then later it executes the code, which is when expansion comes into the picture. Expansion is really an execution event. Furthermore, I take issue with the description of the $IFS variable that I just quoted above; rather than saying that word splitting is performed after expansion, I would say that word splitting is performed during expansion, or, perhaps even more precisely, word splitting is part of the expansion process. The phrase "word splitting" refers only to this step of expansion; it should never be used to refer to the parsing of bash source code, although unfortunately the docs do seem to throw around the words "split" and "words" a lot. Here's a relevant excerpt from the linux.die.net version of the bash manual:

Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

You could argue the GNU version of the manual does slightly better, since it opts for the word "tokens" instead of "words" in the first sentence of the Expansion section:

Expansion is performed on the command line after it has been split into tokens.

The important point is, $IFS does not change the way bash parses source code. Parsing of bash source code is actually a very complex process that involves recognition of the various elements of shell grammar, such as command sequences, command lists, pipelines, parameter expansions, arithmetic substitutions, and command substitutions. For the most part, the bash parsing process cannot be altered by user-level actions like variable assignments (actually, there are some minor exceptions to this rule; for example, see the various compatxx shell settings, which can change certain aspects of parsing behavior on-the-fly). The upstream "words"/"tokens" that result from this complex parsing process are then expanded according to the general process of "expansion" as broken down in the above documentation excerpts, where word splitting of the expanded (expanding?) text into downstream words is simply one step of that process. Word splitting only touches text that has been spit out of a preceding expansion step; it does not affect literal text that was parsed right off the source bytestream.


Wrong answer #7

string='first line
        second line
        third line'

while read -r line; do lines+=("$line"); done <<<"$string"

This is one of the best solutions. Notice that we're back to using read. Didn't I say earlier that read is inappropriate because it performs two levels of splitting, when we only need one? The trick here is that you can call read in such a way that it effectively only does one level of splitting, specifically by splitting off only one field per invocation, which necessitates the cost of having to call it repeatedly in a loop. It's a bit of a sleight of hand, but it works.

But there are problems. First: When you provide at least one NAME argument to read, it automatically ignores leading and trailing whitespace in each field that is split off from the input string. This occurs whether $IFS is set to its default value or not, as described earlier in this post. Now, the OP may not care about this for his specific use-case, and in fact, it may be a desirable feature of the parsing behavior. But not everyone who wants to parse a string into fields will want this. There is a solution, however: A somewhat non-obvious usage of read is to pass zero NAME arguments. In this case, read will store the entire input line that it gets from the input stream in a variable named $REPLY, and, as a bonus, it does not strip leading and trailing whitespace from the value. This is a very robust usage of read which I've exploited frequently in my shell programming career. Here's a demonstration of the difference in behavior:

string=$'  a  b  \n  c  d  \n  e  f  '; ## input string

a=(); while read -r line; do a+=("$line"); done <<<"$string"; declare -p a;
## declare -a a=([0]="a  b" [1]="c  d" [2]="e  f") ## read trimmed surrounding whitespace

a=(); while read -r; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="  a  b  " [1]="  c  d  " [2]="  e  f  ") ## no trimming

The second issue with this solution is that it does not actually address the case of a custom field separator, such as the OP's comma-space. As before, multicharacter separators are not supported, which is an unfortunate limitation of this solution. We could try to at least split on comma by specifying the separator to the -d option, but look what happens:

string='Paris, France, Europe';
a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France")

Predictably, the unaccounted surrounding whitespace got pulled into the field values, and hence this would have to be corrected subsequently through trimming operations (this could also be done directly in the while-loop). But there's another obvious error: Europe is missing! What happened to it? The answer is that read returns a failing return code if it hits end-of-file (in this case we can call it end-of-string) without encountering a final field terminator on the final field. This causes the while-loop to break prematurely and we lose the final field.

Technically this same error afflicted the previous examples as well; the difference there is that the field separator was taken to be LF, which is the default when you don't specify the -d option, and the <<< ("here-string") mechanism automatically appends a LF to the string just before it feeds it as input to the command. Hence, in those cases, we sort of accidentally solved the problem of a dropped final field by unwittingly appending an additional dummy terminator to the input. Let's call this solution the "dummy-terminator" solution. We can apply the dummy-terminator solution manually for any custom delimiter by concatenating it against the input string ourselves when instantiating it in the here-string:

a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string,"; declare -p a;
declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

There, problem solved. Another solution is to only break the while-loop if both (1) read returned failure and (2) $REPLY is empty, meaning read was not able to read any characters prior to hitting end-of-file. Demo:

a=(); while read -rd,|| [[ -n "$REPLY" ]]; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

This approach also reveals the secretive LF that automatically gets appended to the here-string by the <<< redirection operator. It could of course be stripped off separately through an explicit trimming operation as described a moment ago, but obviously the manual dummy-terminator approach solves it directly, so we could just go with that. The manual dummy-terminator solution is actually quite convenient in that it solves both of these two problems (the dropped-final-field problem and the appended-LF problem) in one go.

So, overall, this is quite a powerful solution. It's only remaining weakness is a lack of support for multicharacter delimiters, which I will address later.


Wrong answer #8

string='first line
        second line
        third line'

readarray -t lines <<<"$string"

(This is actually from the same post as #7; the answerer provided two solutions in the same post.)

The readarray builtin, which is a synonym for mapfile, is ideal. It's a builtin command which parses a bytestream into an array variable in one shot; no messing with loops, conditionals, substitutions, or anything else. And it doesn't surreptitiously strip any whitespace from the input string. And (if -O is not given) it conveniently clears the target array before assigning to it. But it's still not perfect, hence my criticism of it as a "wrong answer".

First, just to get this out of the way, note that, just like the behavior of read when doing field-parsing, readarray drops the trailing field if it is empty. Again, this is probably not a concern for the OP, but it could be for some use-cases. I'll come back to this in a moment.

Second, as before, it does not support multicharacter delimiters. I'll give a fix for this in a moment as well.

Third, the solution as written does not parse the OP's input string, and in fact, it cannot be used as-is to parse it. I'll expand on this momentarily as well.

For the above reasons, I still consider this to be a "wrong answer" to the OP's question. Below I'll give what I consider to be the right answer.


Right answer

Here's a naïve attempt to make #8 work by just specifying the -d option:

string='Paris, France, Europe';
readarray -td, a <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

We see the result is identical to the result we got from the double-conditional approach of the looping read solution discussed in #7. We can almost solve this with the manual dummy-terminator trick:

readarray -td, a <<<"$string,"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe" [3]=$'\n')

The problem here is that readarray preserved the trailing field, since the <<< redirection operator appended the LF to the input string, and therefore the trailing field was not empty (otherwise it would've been dropped). We can take care of this by explicitly unsetting the final array element after-the-fact:

readarray -td, a <<<"$string,"; unset 'a[-1]'; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

The only two problems that remain, which are actually related, are (1) the extraneous whitespace that needs to be trimmed, and (2) the lack of support for multicharacter delimiters.

The whitespace could of course be trimmed afterward (for example, see How to trim whitespace from a Bash variable?). But if we can hack a multicharacter delimiter, then that would solve both problems in one shot.

Unfortunately, there's no direct way to get a multicharacter delimiter to work. The best solution I've thought of is to preprocess the input string to replace the multicharacter delimiter with a single-character delimiter that will be guaranteed not to collide with the contents of the input string. The only character that has this guarantee is the NUL byte. This is because, in bash (though not in zsh, incidentally), variables cannot contain the NUL byte. This preprocessing step can be done inline in a process substitution. Here's how to do it using awk:

readarray -td '' a < <(awk '{ gsub(/, /,"\0"); print; }' <<<"$string, "); unset 'a[-1]';
declare -p a;
## declare -a a=([0]="Paris" [1]="France" [2]="Europe")

There, finally! This solution will not erroneously split fields in the middle, will not cut out prematurely, will not drop empty fields, will not corrupt itself on filename expansions, will not automatically strip leading and trailing whitespace, will not leave a stowaway LF on the end, does not require loops, and does not settle for a single-character delimiter.


Trimming solution

Lastly,

Can you control how an SVG's stroke-width is drawn?

As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.

The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)

The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.

Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.

How to get DataGridView cell value in messagebox?

You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.

So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

The above probably isn't exactly what you need to do. If you provide more details we can provide better help.

How do I find the width & height of a terminal window?

There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

function term_size
{
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
    do
        echo $i $(( i - 2 ))
    done
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

Any way to generate ant build.xml file automatically from Eclipse?

Take a look at the .classpath file in your project, which probably contains most of the information that you want. The easiest option may be to roll your own "build.xml export", i.e. process .classpath into a new build.xml during the build itself, and then call it with an ant subtask.

Parsing a little XML sounds much easier to me than to hook into Eclipse JDT.

Opening a .ipynb.txt File

What you have on your hands is an IPython Notebook file. (Now renamed to Jupyter Notebook

you can open it using the command ipython notebook filename.ipynb from the directory it is downloaded on to.

If you are on a newer machine, open the file as jupyter notebook filename.ipynb.

do not forget to remove the .txt extension.

the file has a series of python code/statements and markdown text that you can run/inspect/save/share. read more about ipython notebook from the website.

if you do not have IPython installed, you can do

pip install ipython

or check out installation instructions at the ipython website

UIDevice uniqueIdentifier deprecated - What to do now?

+ (NSString *) getUniqueUUID {
    NSError * error;
    NSString * uuid = [KeychainUtils getPasswordForUsername:kBuyassUser andServiceName:kIdOgBetilngService error:&error];
    if (error) {
    NSLog(@"Error geting unique UUID for this device! %@", [error localizedDescription]);
    return nil;
    }
    if (!uuid) {
        DLog(@"No UUID found. Creating a new one.");
        uuid = [IDManager GetUUID];
        uuid = [Util md5String:uuid];
        [KeychainUtils storeUsername:USER_NAME andPassword:uuid forServiceName:SERVICE_NAME updateExisting:YES error:&error];
        if (error) {
            NSLog(@"Error getting unique UUID for this device! %@", [error localizedDescription]);
            return nil;
        }
    }
    return uuid;
}

curl.h no such file or directory

To those who use centos and have stumbled upon this post :

 $ yum install curl-devel

and when compiling your program example.cpp, link to the curl library:

 $ g++ example.cpp -lcurl -o example

"-o example" creates the executable example instead of the default a.out.

The next line runs example:

 $ ./example

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I'm not sure what you mean by "myself".

Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.

e.g. On page load:

<body onload="myfunction();">

Or on mouseover:

<table onmouseover="myfunction();">

As a result the first question is, "What do you want to do to cause the function to execute?"

After you determine that it will be much easier to give you a direct answer.

What is the most effective way for float and double comparison?

There are actually cases in numerical software where you want to check whether two floating point numbers are exactly equal. I posted this on a similar question

https://stackoverflow.com/a/10973098/1447411

So you can not say that "CompareDoubles1" is wrong in general.

WhatsApp API (java/python)

From my blog

courtesy

There is a secret pilot program which WhatsApp is working on with selected businesses

News coverage:

For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.

Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.

However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:

  1. Bots App Bots App is interesting because it shows that something is really tried and tested.

  2. Yowsup A project still actively developed to interact with WhatsApp platform.

  3. Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652

  4. Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.

  5. Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.

  6. Oye Gennie A bot blocked by WhatsApp.

  7. App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.

  8. Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.

  9. WhatsBot Deactivated WhatsApp bot. Created during a hackathon.

  10. No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.

  11. Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.

  12. Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.

  13. Unofficial API This API can shut off any time.

    And the number goes on...

How to execute cmd commands via Java

I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

   String[] command =
    {
        "cmd",
    };
    Process p = Runtime.getRuntime().exec(command);
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
    PrintWriter stdin = new PrintWriter(p.getOutputStream());
    stdin.println("dir c:\\ /A /Q");
    // write any other commands you want here
    stdin.close();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);

SyncPipe Class:

class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
              ostrm_.write(buffer, 0, length);
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  private final OutputStream ostrm_;
  private final InputStream istrm_;
}

How to always show scrollbar

Try this as the above suggestions didn't work for me when I wanted to do this for a TextView:

TextView.setScrollbarFadingEnabled(false);

Good Luck.

Calling a function within a Class method?

To call any method of an object instantiated from a class (with statement new), you need to "point" to it. From the outside you just use the resource created by the new statement. Inside any object PHP created by new, saves the same resource into the $this variable. So, inside a class you MUST point to the method by $this. In your class, to call smallTest from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:

$this->smallTest();

C# Timer or Thread.Sleep

I would have to say a sleep is a better implementation with a state machine behind it. This would still keep you in control of the application at all times, but allowing any response needed at any specific time. This also will handle timer callbacks that are shorter than the "Processing execution time in the loop"

For example..

<!-- language: c# -->
public enum State
{
    Idle = 0,
    Processing = 1,
    Stop = 100,
}
public void Run()
{
    State state = State.Idle;   // could be a member variable, so a service could stop this too

    double intervalInSeconds = 60;
    System.DateTime nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
    while (state != State.Stop)
    {
        switch (state)
        {
            case State.Idle:
                {
                    if (nextExecution > System.DateTime.Now)
                    {
                        state = State.Processing;
                    }
                }
                break;
            case State.Processing:
                {
                    // do your once-per-minute code here

                    // if you want it to stop, just set it state to stop.
                    // if this was a service, you could stop execution by setting state to stop, also
                    // only time it would not stop is if it was waiting for the process to finish, which you can handle in other ways

                    state = State.Idle;
                    nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
                }
                break;
            default:
                break;
        }

        System.Threading.Thread.Sleep(1);
    }
}

What does '<?=' mean in PHP?

It's a shorthand for this:

<?php echo $a; ?>

They're called short tags; see example #2 in the documentation.

What is the difference between a deep copy and a shallow copy?

char * Source = "Hello, world.";

char * ShallowCopy = Source;    

char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);        

'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.

How can I get nth element from a list?

You can use !!, but if you want to do it recursively then below is one way to do it:

dataAt :: Int -> [a] -> a
dataAt _ [] = error "Empty List!"
dataAt y (x:xs)  | y <= 0 = x
                 | otherwise = dataAt (y-1) xs

How do I make a checkbox required on an ASP.NET form?

C# version of andrew's answer:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ErrorMessage="Please accept the terms..." 
        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    <asp:CheckBox ID="CheckBox1" runat="server" />

Code-behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = CheckBox1.Checked;
}

ISO time (ISO 8601) in Python

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2010-12-16 17:22:15
20101216T172215

(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.

I recommend use of this format to store times in files.

One way to get the current time in this representation is to use strftime from the time module in the Python standard library:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'

You can use the strptime constructor of the datetime class:

>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)

The most robust is the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)

References

How to add http:// if it doesn't exist in the URL

A modified version of @nickf code:

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.

Rollback a Git merge

From here:

http://www.christianengvall.se/undo-pushed-merge-git/

git revert -m 1 <merge commit hash>

Git revert adds a new commit that rolls back the specified commit.

Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.

Using JavaMail with TLS

Just use the following code. It is really useful to send email via Java, and it works:

import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;

public class Main {

    public static void main(String[] args) {
            final String username="[email protected]";
            final String password="password";
            Properties prop=new Properties();
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtp.host", "smtp.gmail.com");
            prop.put("mail.smtp.port", "587");
            prop.put("mail.smtp.starttls.enable", "true");

            Session session = Session.getDefaultInstance(prop,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
          }
        });
          try {
                 String body="Dear Renish Khunt Welcome";
                 String htmlBody = "<strong>This is an HTML Message</strong>";
                 String textBody = "This is a Text Message.";
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress("[email protected]"));
                 message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
            message.setText(htmlBody);
                        message.setContent(textBody, "text/html");
            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}

How can foreign key constraints be temporarily disabled using T-SQL?

I have a more useful version if you are interested. I lifted a bit of code from here a website where the link is no longer active. I modifyied it to allow for an array of tables into the stored procedure and it populates the drop, truncate, add statements before executing all of them. This gives you control to decide which tables need truncating.

/****** Object:  UserDefinedTableType [util].[typ_objects_for_managing]    Script Date: 03/04/2016 16:42:55 ******/
CREATE TYPE [util].[typ_objects_for_managing] AS TABLE(
    [schema] [sysname] NOT NULL,
    [object] [sysname] NOT NULL
)
GO

create procedure [util].[truncate_table_with_constraints]
@objects_for_managing util.typ_objects_for_managing readonly

--@schema sysname
--,@table sysname

as 
--select
--    @table = 'TABLE',
--    @schema = 'SCHEMA'

declare @exec_table as table (ordinal int identity (1,1), statement nvarchar(4000), primary key (ordinal));

--print '/*Drop Foreign Key Statements for ['+@schema+'].['+@table+']*/'

insert into @exec_table (statement)
select
          'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+ o.name+'] DROP CONSTRAINT ['+fk.name+']'
from sys.foreign_keys fk
inner join sys.objects o
          on fk.parent_object_id = o.object_id
where 
exists ( 
select * from @objects_for_managing chk 
where 
chk.[schema] = SCHEMA_NAME(o.schema_id)  
and 
chk.[object] = o.name
) 
;
          --o.name = @table and
          --SCHEMA_NAME(o.schema_id)  = @schema

insert into @exec_table (statement) 
select
'TRUNCATE TABLE ' + src.[schema] + '.' + src.[object] 
from @objects_for_managing src
; 

--print '/*Create Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+o.name+'] ADD CONSTRAINT ['+fk.name+'] FOREIGN KEY (['+c.name+']) 
REFERENCES ['+SCHEMA_NAME(refob.schema_id)+'].['+refob.name+'](['+refcol.name+'])'
from sys.foreign_key_columns fkc
inner join sys.foreign_keys fk
          on fkc.constraint_object_id = fk.object_id
inner join sys.objects o
          on fk.parent_object_id = o.object_id
inner join sys.columns c
          on      fkc.parent_column_id = c.column_id and
                   o.object_id = c.object_id
inner join sys.objects refob
          on fkc.referenced_object_id = refob.object_id
inner join sys.columns refcol
          on fkc.referenced_column_id = refcol.column_id and
                   fkc.referenced_object_id = refcol.object_id
where 
exists ( 
select * from @objects_for_managing chk 
where 
chk.[schema] = SCHEMA_NAME(o.schema_id)  
and 
chk.[object] = o.name
) 
;

          --o.name = @table and
          --SCHEMA_NAME(o.schema_id)  = @schema



declare @looper int , @total_records int, @sql_exec nvarchar(4000)

select @looper = 1, @total_records = count(*) from @exec_table; 

while @looper <= @total_records 
begin

select @sql_exec = (select statement from @exec_table where ordinal =@looper)
exec sp_executesql @sql_exec 
print @sql_exec 
set @looper = @looper + 1
end

Finding partial text in range, return an index

You can use "wildcards" with MATCH so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula

=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)

MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100

=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)

confirmed with Ctrl-Shift-Enter

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Set value of textbox using JQuery

You are logging sup directly which is a string

console.log('sup')

Also you are using the wrong id

The template says #main_search but you are using #searchBar

I suppose you are trying this out

$(function() {
   var sup = $('#main_search').val('hi')
   console.log(sup);  // sup is a variable here
});

Non-recursive depth first search algorithm

Just wanted to add my python implementation to the long list of solutions. This non-recursive algorithm has discovery and finished events.


worklist = [root_node]
visited = set()
while worklist:
    node = worklist[-1]
    if node in visited:
        # Node is finished
        worklist.pop()
    else:
        # Node is discovered
        visited.add(node)
        for child in node.children:
            worklist.append(child)

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

If you use Git Extensions GUI it can show you a graphical visualization of dangling commits if you check "View -> Show reflog references". This will show dangling commits in the tree, just like all other referenced ones. This way it is way easier to find what you are looking for.

See this image for demonstration. Commits C2, C3, C4, and C5 on the image are dangling but still visible.

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

How can I check for "undefined" in JavaScript?

Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

CASE in WHERE, SQL Server

A few ways:

-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)

-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END

Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

Plot multiple boxplot in one graph

ggplot version of the lattice plot:

library(reshape2)
library(ggplot2)
df <- read.csv("TestData.csv", header=T)
df.m <- melt(df, id.var = "Label")

ggplot(data = df.m, aes(x=Label, y=value)) + 
         geom_boxplot() + facet_wrap(~variable,ncol = 4)

Plot: enter image description here

Input jQuery get old value before onchange and get value after on change

The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.

The function may also break when using focus, because of the ?? (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:

<input id="my-textbox" type="text" data-initial-value="6" value="6" />

Display Adobe pdf inside a div

I don't think you can. You may need to use an Iframe instead.

Java - Relative path of a file in a java web application

The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.

You don't need it to be a file:... URL. You just need it to be a URL that your JVM can read--and it will be.

What is the use of GO in SQL Server Management Studio & Transact SQL?

GO is not a SQL keyword.

It's a batch separator used by client tools (like SSMS) to break the entire script up into batches

Answered before several times... example 1

How can I check if a scrollbar is visible?

This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.

(function($) {
    $.fn.hasScrollBar = function() {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);

Example:

element.hasScrollBar()             // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical    // Returns true/false
element.hasScrollBar().horizontal  // Returns true/false

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

make sounds (beep) with c++

#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;

int main()
{

    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1245, 1000);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1175, 1000);

cout<<endl;
_getch()

return 0
}

How do I clear a search box with an 'x' in bootstrap 3?

Thanks unwired your solution was very clean. I was using horizontal bootstrap forms and made a couple modifications to allow for a single handler and form css.

html: - UPDATED to use Bootstrap's has-feedback and form-control-feedback

 <div class="container">
  <form class="form-horizontal">
   <div class="form-group has-feedback">
    <label for="txt1" class="col-sm-2 control-label">Label 1</label>
    <div class="col-sm-10">
     <input id="txt1" type="text" class="form-control hasclear" placeholder="Textbox 1">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt2" class="col-sm-2 control-label">Label 2</label>
    <div class="col-sm-10">
      <input id="txt2" type="text" class="form-control hasclear" placeholder="Textbox 2">
      <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt3" class="col-sm-2 control-label">Label 3</label>
    <div class="col-sm-10">
     <input id="txt3" type="text" class="form-control hasclear" placeholder="Textbox 3">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>   
   </div>
  </form>
 </div>

javascript:

$(".hasclear").keyup(function () {
    var t = $(this);
    t.next('span').toggle(Boolean(t.val()));
});
$(".clearer").hide($(this).prev('input').val());
$(".clearer").click(function () {
    $(this).prev('input').val('').focus();
    $(this).hide();
});

example: http://www.bootply.com/130682

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Figure out size of UILabel based on String in Swift

extension String{

    func widthWithConstrainedHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)

        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.width)
    }

    func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat? {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.height)
    }

}

Bootstrap 3 panel header with buttons wrong position

You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.

Here is a fix, just replace it with your code.

  <div class="panel-heading clearfix">
     <b>Panel header</b>
       <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
      </div>
   </div>

Editted on 12/22/2015 - added .clearfix to heading div

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Install AspNetMVC3ToolsUpdateSetup downloaded from here would solve this problem without adding reference

How to find and replace string?

Do we really need a Boost library for seemingly such a simple task?

To replace all occurences of a substring use this function:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.