Programs & Examples On #Voicexml

VoiceXML is designed for creating audio dialogs that feature synthesized speech, digitized audio, recognition of spoken and DTMF key input, recording of spoken input, telephony, and mixed initiative conversations.

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

ScrollIntoView() causing the whole page to move

I've added a way to display the imporper behavior of the ScrollIntoView - http://jsfiddle.net/LEqjm/258/ [it should be a comment but I don't have enough reputation]

$("ul").click(function() {
    var target = document.getElementById("target");
if ($('#scrollTop').attr('checked')) {
    target.parentNode.scrollTop = target.offsetTop;    
} else {
        target.scrollIntoView(!0);
}
});

JSON order mixed up

I found a "neat" reflection tweak on "the interwebs" that I like to share. (origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)

It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.

I tested succesfully:

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;

private static void makeJSONObjLinear(JSONObject jsonObject) {
    try {
            Field changeMap = jsonObject.getClass().getDeclaredField("map");
            changeMap.setAccessible(true);
            changeMap.set(jsonObject, new LinkedHashMap<>());
            changeMap.setAccessible(false);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
}

[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);

requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned   '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)

PostgreSQL: How to change PostgreSQL user password?

Then type:

$ sudo -u postgres psql

Then:

\password postgres

Then to quit psql:

\q

If that does not work, reconfigure authentication.

Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

    local   all             all                                     peer

to:

    local   all             all                                     md5

Then restart the server:

$ sudo service postgresql restart

C# code to validate email address

A simple one without using Regex (which I don't like for its poor readability):

bool IsValidEmail(string email)
{
    string emailTrimed = email.Trim();

    if (!string.IsNullOrEmpty(emailTrimed))
    {
        bool hasWhitespace = emailTrimed.Contains(" ");

        int indexOfAtSign = emailTrimed.LastIndexOf('@');

        if (indexOfAtSign > 0 && !hasWhitespace)
        {
            string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);

            int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');

            if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
                return true;
        }
    }

    return false;
}

Examples:

It is meant to be simple and therefore it doesn't deal with rare cases like emails with bracketed domains that contain spaces (typically allowed), emails with IPv6 addresses, etc.

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

How can I extract substrings from a string in Perl?

This just requires a small change to my last answer:

my ($guid, $scheme, $star) = $line =~ m{
    The [ ] Scheme [ ] GUID: [ ]
    ([a-zA-Z0-9-]+)          #capture the guid
    [ ]
    \(  (.+)  \)             #capture the scheme 
    (?:
        [ ]
        ([*])                #capture the star 
    )?                       #if it exists
}x;

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

SQL Server IN vs. EXISTS Performance

The execution plans are typically going to be identical in these cases, but until you see how the optimizer factors in all the other aspects of indexes etc., you really will never know.

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Retrofit 2 - URL Query Parameter

If you specify @GET("foobar?a=5"), then any @Query("b") must be appended using &, producing something like foobar?a=5&b=7.

If you specify @GET("foobar"), then the first @Query must be appended using ?, producing something like foobar?b=7.

That's how Retrofit works.

When you specify @GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.

Remove the ?, and you will get the desired result.

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

What is the purpose of backbone.js?

So many good answers already. Backbone js helps to keep the code organised. Changing the model/collection takes care of the view rendering automaticallty which reduces lot of development overhead.

Even though it provides maximum flexibility for development, developers should be careful to destroy the models and remove the views properly. Otherwise there may be memory leak in the application.

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

What does the exclamation mark do before the function?

Its another way of writing IIFE (immediately-invoked function expression).

Its other way of writing -

(function( args ) {})()

same as

!function ( args ) {}();

How to set menu to Toolbar in Android

Simple fix to this was setting showAsAction to always in menu.xml in res/menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/add_alarm"
        android:icon="@drawable/ic_action_name"
        android:orderInCategory="100"
        android:title="Add"
        app:showAsAction="always"
        android:visible="true"/>

</menu>

What causes the Broken Pipe Error?

When peer close, you just do not know whether it just stop sending or both sending and receiving.Because TCP allows this, btw, you should know the difference between close and shutdown. If peer both stop sending and receiving, first you send some bytes, it will succeed. But the peer kernel will send you RST. So subsequently you send some bytes, your kernel will send you SIGPIPE signal, if you catch or ignore this signal, when your send returns, you just get Broken pipe error, or if you don't , the default behavior of your program is crashing.

C# Copy a file to another location with a different name

The easiest method you can use is this:

System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);

This will take care of everything you requested.

CSS How to set div height 100% minus nPx

You can do something like height: calc(100% - nPx); for example height: calc(100% - 70px);

How to trim a string in SQL Server before 2017?

I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

ALTER TABLE Customer ADD
   CONSTRAINT customer_names__whitespace
      CHECK (
             Names NOT LIKE ' %'
             AND Names NOT LIKE '% '
             AND Names NOT LIKE '%  %'
            );

Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

It may also be a good time to split those Names into family_name, first_name, etc :)

How to select a single field for all documents in a MongoDB collection?

Try the following query:

db.student.find({}, {roll: 1, _id: 0}).pretty();

Hope this helps!!

How do you change the colour of each category within a highcharts column chart?

Also you can set option:

  {plotOptions: {column: {colorByPoint: true}}}

for more information read docs

How to query MongoDB with "like"?

You would use regex for that in mongo.

e.g:

db.users.find({"name": /^m/})

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Reload content in modal (twitter bootstrap)

I made a small change to Softlion answer, so all my modals won't refresh on hide. The modals with data-refresh='true' attribute are only refreshed, others work as usual. Here is the modified version.

$(document).on('hidden.bs.modal', function (e) {
    if ($(e.target).attr('data-refresh') == 'true') {
        // Remove modal data
        $(e.target).removeData('bs.modal');
        // Empty the HTML of modal
        $(e.target).html('');
    }
});

Now use the attribute as shown below,

<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>

This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.

Setting selected option in laravel form

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

How to capture the browser window close event?

Unfortunately, whether it is a reload, new page redirect, or browser close the event will be triggered. An alternative is catch the id triggering the event and if it is form dont trigger any function and if it is not the id of the form then do what you want to do when the page closes. I am not sure if that is also possible directly and is tedious.

You can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  /* Do you small action code here */
  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

Paramiko's SSHClient with SFTP

paramiko.SFTPClient

Sample Usage:

import paramiko
paramiko.util.log_to_file("paramiko.log")

# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"
transport.connect(None,username,password)

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)

# Close
if sftp: sftp.close()
if transport: transport.close()

Open a new tab in the background?

Here is a complete example for navigating valid URL on a new tab with focused.

HTML:

<div class="panel">
  <p>
    Enter Url: 
    <input type="text" id="txturl" name="txturl" size="30" class="weburl" />
    &nbsp;&nbsp;    
    <input type="button" id="btnopen"  value="Open Url in New Tab" onclick="openURL();"/>
  </p>
</div>

CSS:

.panel{
  font-size:14px;
}
.panel input{
  border:1px solid #333;
}

JAVASCRIPT:

function isValidURL(url) {
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if (RegExp.test(url)) {
        return true;
    } else {
        return false;
    }
}

function openURL() {
    var url = document.getElementById("txturl").value.trim();
    if (isValidURL(url)) {
        var myWindow = window.open(url, '_blank');
        myWindow.focus();
        document.getElementById("txturl").value = '';
    } else {
        alert("Please enter valid URL..!");
        return false;
    }
}

I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

Cannot set property 'innerHTML' of null

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="hello"></div>_x000D_
<script type ="text/javascript">_x000D_
    what();_x000D_
    function what(){_x000D_
        document.getElementById('hello').innerHTML = 'hi';_x000D_
    };_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

bootstrap 3 navbar collapse button not working

Well i had the same problem what when i added the following code within the tag my problem fixed :

    <head>
       <meta name="viewport" content="width=device-width , initial-scale=1" />
    </head>

I hope this can help you guys!

Difference between == and ===

In Swift we have === simbol which means is both objects are referring to the same reference same address

class SomeClass {
var a: Int;

init(_ a: Int) {
    self.a = a
}

}

var someClass1 = SomeClass(4)
var someClass2 = SomeClass(4)
someClass1 === someClass2 // false
someClass2 = someClass1
someClass1 === someClass2 // true

How do I override nested NPM dependency versions?

You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.

I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

npm should automatically pick it up while doing the install for the project.

(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)

How can I convert a dictionary into a list of tuples?

[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

How to remove underline from a link in HTML?

The other answers all mention text-decoration. Sometimes you use a Wordpress theme or someone else's CSS where links are underlined by other methods, so that text-decoration: none won't turn off the underlining.

Border and box-shadow are two other methods I'm aware of for underlining links. To turn these off:

border: none;

and

box-shadow: none;

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

The number of method references in a .dex file cannot exceed 64k API 17

I have been facing the same problem and for multidex support, you have to keep in mind the minSdkVersion of your application. If you are using minSdkVersion 21 or above then just write multiDexEnabled true like this

defaultConfig {
    applicationId *******************
    minSdkVersion 21
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}

It works for me and if you are using minSdkVersion below 21 (below lolipop) then you have to do two extra simple things

1. First add this dependency

compile 'com.android.support:multidex:1.0.1'

in your build.gradle.

2. Last and second add one this below line to your application in manifest

android:name="android.support.multidex.MultiDexApplication"

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:name="android.support.multidex.MultiDexApplication"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Bingo then it will work in the lower version also..:) Happy coding

Finding moving average from data points in Python

Before reading this answer, bear in mind that there is another answer below, from Roman Kh, which uses numpy.cumsum and is MUCH MUCH FASTER than this one.


Best One common way to apply a moving/sliding average (or any other sliding window function) to a signal is by using numpy.convolve().

def movingaverage(interval, window_size):
    window = numpy.ones(int(window_size))/float(window_size)
    return numpy.convolve(interval, window, 'same')

Here, interval is your x array, and window_size is the number of samples to consider. The window will be centered on each sample, so it takes samples before and after the current sample in order to calculate the average. Your code would become:

plot(x,y)
xlim(0,1000)

x_av = movingaverage(interval, r)
plot(x_av, y)

xlabel("Months since Jan 1749.")
ylabel("No. of Sun spots")
show()

Hope this helps!

Finding duplicate integers in an array and display how many times they occurred

Use Group by:

int[] values = new []{1,2,3,4,5,4,4,3};

var groups = values.GroupBy(v => v);
foreach(var group in groups)
    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());

How to extract public key using OpenSSL?

For AWS importing an existing public key,

  1. Export from the .pem doing this... (on linux)

    openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
    

This will produce a file which if you open in a text editor looking something like this...

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
9WyrKhxq4Vbt42BthadX3Ty/pKkJ81Qn8KjxWoL+SMaCGFzRlfWsFju9Q5C7+aTj
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
  1. However AWS will NOT accept this file.

    You have to strip off the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- from the file. Save it and import and it should work in AWS.

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

To write to a file

import codecs
import json

with codecs.open('your_file.txt', 'w', encoding='utf-8') as f:
    json.dump({"message":"xin chào vi?t nam"}, f, ensure_ascii=False)

To print to stdout

import json
print(json.dumps({"message":"xin chào vi?t nam"}, ensure_ascii=False))

VBoxManage: error: Failed to create the host-only adapter

Got the error in Mac after the update to Mojave. Probably you have an older version of virtual box.

Update to a recent version of virtualbox. (5.2 at the time of wrting this post)

Edit: adding @lsimonetti's comment.

In addition to that upgrade to Virtualbox 5.2, you need Vagrant >= 2.0.1

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

Regarding 'main(int argc, char *argv[])'

The arguments argc and argv of main is used as a way to send arguments to a program, the possibly most familiar way is to use the good ol' terminal where an user could type cat file. Here the word cat is a program that takes a file and outputs it to standard output (stdout).

The program receives the number of arguments in argc and the vector of arguments in argv, in the above the argument count would be two (The program name counts as the first argument) and the argument vector would contain [cat,file,null]. While the last element being a null-pointer.

Commonly, you would write it like this:

int  // Specifies that type of variable the function returns.
     // main() must return an integer
main ( int argc, char **argv ) {
     // code
     return 0; // Indicates that everything went well.
}

If your program does not require any arguments, it is equally valid to write a main-function in the following fashion:

int main() {
  // code
  return 0; // Zero indicates success, while any 
  // Non-Zero value indicates a failure/error
}

In the early versions of the C language, there was no int before main as this was implied. Today, this is considered to be an error.

On POSIX-compliant systems (and Windows), there exists the possibility to use a third parameter char **envp which contains a vector of the programs environment variables. Further variations of the argument list of the main function exists, but I will not detail it here since it is non-standard.

Also, the naming of the variables is a convention and has no actual meaning. It is always a good idea to adhere to this so that you do not confuse others, but it would be equally valid to define main as

int main(int c, char **v, char **e) {
   // code
   return 0;
}

And for your second question, there are several ways to send arguments to a program. I would recommend you to look at the exec*()family of functions which is POSIX-standard, but it is probably easier to just use system("command arg1 arg2"), but the use of system() is usually frowned upon as it is not guaranteed to work on every system. I have not tested it myself; but if there is no bash,zsh, or other shell installed on a *NIX-system, system() will fail.

How to calculate the IP range when the IP address and the netmask is given?

You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.

How to center a subview of UIView

You can use

yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))

And In Swift 3.0

yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)

IN-clause in HQL or Java Persistence Query Language

in HQL you can use query parameter and set Collection with setParameterList method.

    Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
    q.setParameterList("names", names);

What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

pull/push from multiple remote locations

I added these aliases to my ~/.bashrc:

alias pushall='for i in `git remote`; do git push $i; done;'
alias pullall='for i in `git remote`; do git pull $i; done;'

css overflow - only 1 line of text

You can use this css code:

text-overflow: ellipsis; 
overflow: hidden; 
white-space: nowrap;

The text-overflow property in CSS deals with situations where text is clipped when it overflows the element's box. It can be clipped (i.e. cut off, hidden), display an ellipsis ('…', Unicode Range Value U+2026).

Note that text-overflow only occurs when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap;.

Text overflow can only happen on block or inline-block level elements, because the element needs to have a width in order to be overflow-ed. The overflow happens in the direction as determined by the direction property or related attributes.

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

How can I get the line number which threw exception?

Simple way, use the Exception.ToString() function, it will return the line after the exception description.

You can also check the program debug database as it contains debug info/logs about the whole application.

How to read embedded resource text file

For users that are using VB.Net

Imports System.IO
Imports System.Reflection

Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js" 
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()

where MyApplicationName is namespace of my application. It is not the assembly name. This name is define in project's properties (Application tab).

If you don't find correct resource name, you can use GetManifestResourceNames() function

Dim resourceName() As String = ass.GetManifestResourceNames()

or

Dim sName As String 
    = ass.GetManifestResourceNames()
        .Single(Function(x) x.EndsWith("JavaScript.js"))

or

Dim sNameList 
    = ass.GetManifestResourceNames()
        .Where(Function(x As String) x.EndsWith(".js"))

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Follow these steps- 1.go to config.inc.php file and find - $cfg['Servers'][$i]['auth_type']

2.change the value of $cfg['Servers'][$i]['auth_type'] to 'cookie' or 'http'.

3.find $cfg['Servers'][$i]['AllowNoPassword'] and change it's value to true.

Now whenever you want to login, enter root as your username,skip the password and go ahead pressing the submit button..

Note- if you choose authentication type as cookie then whenever you will close the browser and reopen it ,again you have to login.

Maven Error: Could not find or load main class

specify the main class location in pom under plugins

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifest>
                            <mainClass>com.example.hadoop.wordCount.WordCountApp</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

How do I update the GUI from another thread?

Simplest way is invoking as follows:

 Application.Current.Dispatcher.Invoke(new Action(() =>
             {
                    try
                    {
                        ///
                    }
                    catch (Exception)
                    {
                      //
                    }


                    }
     ));

How to sort pandas data frame using values from several columns?

Use of sort can result in warning message. See github discussion. So you might wanna use sort_values, docs here

Then your code can look like this:

df = df.sort_values(by=['c1','c2'], ascending=[False,True])

Debugging Stored Procedure in SQL Server 2008

One requirement for remote debugging is that the windows account used to run SSMS be part of the sysadmin role. See this MSDN link: http://msdn.microsoft.com/en-us/library/cc646024%28v=sql.105%29.aspx

Check if String contains only letters

Check this,i guess this is help you because it's work in my project so once you check this code

if(! Pattern.matches(".*[a-zA-Z]+.*[a-zA-Z]", str1))
 {
   String not contain only character;
 }
else 
{
  String contain only character;
}

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;
    }
}

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();
}

State transition[][] = {
    //  A               B               C
    {
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error
    }
};

Newline character in StringBuilder

Just create an extension for the StringBuilder class:

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module

Enable remote connections for SQL Server Express 2012

The correct way to connect to remote SQL Server (without opening UDP port 1434 and enabling SQL Server Browser) is to use ip and port instead of named instance.

Using ip and port instead of named instance is also safer, as it reduces the attack surface area.

Perhaps 2 pictures speak 2000 words...

This method uses the specified port (this is what most people want I believe)..

enter image description here

This method requires opening UDP port 1434 and SQL Server Browser running..

enter image description here

Java regex capturing groups indexes

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

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

And group(0) contains whole matched string.

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

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

How to remove unused dependencies from composer?

In fact, it is very easy.

composer update

will do all this for you, but it will also update the other packages.

To remove a package without updating the others, specifiy that package in the command, for instance:

composer update monolog/monolog

will remove the monolog/monolog package.

Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

How to make in CSS an overlay over an image?

A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.

You could simply use a background-blend-mode

.foo {
    background-image: url(images/image1.png), url(images/image2.png);
    background-color: violet;
    background-blend-mode: screen multiply;
}

What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.

multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

To swap characters in a string a of position l and r

def swap(a, l, r):
    a = a[0:l] + a[r] + a[l+1:r] + a[l] + a[r+1:]
    return a

Example: swap("aaabcccdeee", 3, 7) returns "aaadcccbeee"

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

Error inflating class android.support.design.widget.NavigationView

Following below steps will surely remove this error.

  • Find the widget causing the error.
  • Go the layout file where that widget is declared.
  • Check for all the resources (drawables etc.) used in that file.
  • Then make sure that resource is there in all versions of drawables (drawable-v21,drawable etc.)

Cheers!!

Is it possible to set an object to null?

While it is true that an object cannot be "empty/null" in C++, in C++17, we got std::optional to express that intent.

Example use:

std::optional<int> v1;      // "empty" int
std::optional<int> v2(3);   // Not empty, "contains a 3"

You can then check if the optional contains a value with

v1.has_value(); // false

or

if(v2) {
    // You get here if v2 is not empty
}

A plain int (or any type), however, can never be "null" or "empty" (by your definition of those words) in any useful sense. Think of std::optional as a container in this regard.

If you don't have a C++17 compliant compiler at hand, you can use boost.optional instead. Some pre-C++17 compilers also offer std::experimental::optional, which will behave at least close to the actual std::optional afaik. Check your compiler's manual for details.

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

How to generate random colors in matplotlib?

elaborating @john-mee 's answer, if you have arbitrarily long data but don't need strictly unique colors:

for python 2:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=cycol.next())

for python 3:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=next(cycol))

this has the advantage that the colors are easy to control and that it's short.

Spring .properties file: get element as an Array

If you need to pass the asterisk symbol, you have to wrap it with quotes.

In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.

In yml file I have:

websocket:
  cors: "*"

In Config class I have:

@Value("${websocket.cors}")
private String[] cors;

Value cannot be null. Parameter name: source

I had the same issue with XUnit. The problem was with my database connection. Check your connection string is correct or not.

Change background of LinearLayout in Android

If your using a background resource and wish to change the resource out you can use setBackgroundResource() function.

ui_item.setBackgroundResource(R.drawable.myResource)

A background resource in XML would look like:

<LinearLayout
                android:id="@+id/ui_item"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/background_01"
                android:orientation="vertical">

How to show math equations in general github's markdown(not github's blog)

It ’s 2020 now, let me summarize the progress of the mathematical formula rendering support of source code repository hosts.

GitHub & Bitbucket

GitHub and Bitbucket still do not support the rendering of mathematical formulas, whether it is the default delimiters or other.

Bitbucket Cloud / BCLOUD-11192 -- Add LaTeX Support in MarkDown Documents (BB-12552)

GitHub / markup -- Rendering math equations

GitHub / markup -- Support latex

GitHub Community Forum -- [FEATURE REQUEST] LaTeX Math in Markdown

talk.commonmark.org -- Can math formula added to the markdown

GitHub has hardly made any substantial progress in recent years.

GitLab

GitLab is already supported, but not the most common way. It uses its own delimiter.

This math is inline $`a^2+b^2=c^2`$.

This is on a separate line

```math
a^2+b^2=c^2
```

GitLab Flavored Markdown -- Math

Who supports the universal delimiters?

A Markdown parser used by Hugo

Other ways to render

Pandas KeyError: value not in index

Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])

So, your entire code example should look like this:

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)

Clear form fields with jQuery

I've written a universal jQuery plugin:

_x000D_
_x000D_
/**_x000D_
 * Resets any input field or form_x000D_
 */_x000D_
$.fn.uReset = function () {_x000D_
    return this.filter('form, :input').each(function () {_x000D_
        var input = $(this);_x000D_
        _x000D_
        // Reset the form._x000D_
        if (input.is('form')) {_x000D_
            input[0].reset();_x000D_
            return;_x000D_
        }_x000D_
_x000D_
        // Reset any form field._x000D_
        if (input.is(':radio, :checkbox')) {_x000D_
            input.prop('checked', this.defaultChecked);_x000D_
        } else if (input.is('select')) {_x000D_
            input.find('option').each(function () {_x000D_
                $(this).prop('selected', this.defaultSelected);_x000D_
            });_x000D_
        } else if (this.defaultValue) {_x000D_
            input.val(this.defaultValue);_x000D_
        } else {_x000D_
            console.log('Cannot reset to default value');_x000D_
        }_x000D_
    });_x000D_
};_x000D_
_x000D_
$(function () {_x000D_
    // Test jQuery plugin._x000D_
    $('button').click(function (e) {_x000D_
        e.preventDefault();_x000D_
        _x000D_
        var button = $(this),_x000D_
            inputType = button.val(),_x000D_
            form = button.closest('form');_x000D_
        _x000D_
        if (inputType === 'form') {_x000D_
            form.uReset()_x000D_
        } else {_x000D_
            $('input[type=' + inputType + '], ' + inputType, form).uReset();_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>Form</h3>_x000D_
<form>_x000D_
    <input type="text" value="default"/><br /><br />_x000D_
    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" /><br />_x000D_
    Ch 2 <input type="checkbox" name="color" value="2" /><br />_x000D_
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" /><br /><br />_x000D_
    <select name="time"><br />_x000D_
        <option value="15">15</option>_x000D_
        <option selected="selected" value="30">30</option>_x000D_
        <option value="45">45</option>_x000D_
    </select><br /><br />_x000D_
    R 1 <input type="radio" name="color" value="1" /><br />_x000D_
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" /><br />_x000D_
    R 3 <input type="radio" name="color" value="3" /><br /><br />_x000D_
    <textarea>Default text</textarea><br /><br />_x000D_
    _x000D_
    <p>Play with form values and then try to reset them</p>_x000D_
    _x000D_
    <button type="button" value="text">Reset text input</button>_x000D_
    <button type="button" value="checkbox">Reset checkboxes</button>_x000D_
    <button type="button" value="select">Reset select</button>_x000D_
    <button type="button" value="radio">Reset radios</button>_x000D_
    <button type="button" value="textarea">Reset textarea</button>_x000D_
    <button type="button" value="form">Reset the Form</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Ruby, Difference between exec, system and %x() or Backticks

system

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

As of Ruby 2.6, passing exception: true will raise an exception instead of returning false or nil:

>> system('invalid')
=> nil

>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013   

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

%x()

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

exec

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Open3.popen3

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

Delete duplicate elements from an array

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];

function squash(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
        tmp.push(arr[i]);
        }
    }
    return tmp;
}

console.log(squash(arr));

Working Example http://jsfiddle.net/7Utn7/

Compatibility for indexOf on old browsers

What is a handle in C++?

This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".

It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.

How to hide a mobile browser's address bar?

Have a look at this HTML5 rocks post - http://www.html5rocks.com/en/mobile/fullscreen/ basically you can use JS, or the Fullscreen API (better option IMO) or add some metadata to the head to indicate that the page is a webapp

How to get a specific output iterating a hash in Ruby?

Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:

puts h.sort.map {|k,v| ["#{k}----"] + v}

And if you don't actually need the "----" part, it can be just:

puts h.sort

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

$(this).val() not working to get text from span using jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

open link of google play store in mobile version android

Below code may helps you for display application link of google play sore in mobile version.

For Application link :

Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

  try {
        startActivity(myAppLinkToMarket);

      } catch (ActivityNotFoundException e) {

        //the device hasn't installed Google Play
        Toast.makeText(Setting.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();
              }

For Developer link :

Uri uri = Uri.parse("market://search?q=pub:" + YourDeveloperName);
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

            try {

                startActivity(myAppLinkToMarket);

            } catch (ActivityNotFoundException e) {

                //the device hasn't installed Google Play
                Toast.makeText(Settings.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();

            } 

Change select box option background color

$htmlIngressCss='<style>';
$multiOptions = array("" => "All");
$resIn = $this->commonDB->getIngressTrunk();
while ($row = $resIn->fetch()) {
    if($row['IsActive']==0){
        $htmlIngressCss .= '.ingressClass select, option[value="'.$row['TrunkInfoID'].'"] {color:red;font-weight:bold;}';
    }
    $multiOptions[$row['TrunkInfoID']] = $row['IngressTrunkName'];
}
$htmlIngressCss.='</style>';

add $htmlIngressCss in your html portion :)

The most efficient way to implement an integer based power function pow(int, int)

I have implemented algorithm that memorizes all computed powers and then uses them when need. So for example x^13 is equal to (x^2)^2^2 * x^2^2 * x where x^2^2 it taken from the table instead of computing it once again. This is basically implementation of @Pramod answer (but in C#). The number of multiplication needed is Ceil(Log n)

public static int Power(int base, int exp)
{
    int tab[] = new int[exp + 1];
    tab[0] = 1;
    tab[1] = base;
    return Power(base, exp, tab);
}

public static int Power(int base, int exp, int tab[])
    {
         if(exp == 0) return 1;
         if(exp == 1) return base;
         int i = 1;
         while(i < exp/2)
         {  
            if(tab[2 * i] <= 0)
                tab[2 * i] = tab[i] * tab[i];
            i = i << 1;
          }
    if(exp <=  i)
        return tab[i];
     else return tab[i] * Power(base, exp - i, tab);
}

How to use DISTINCT and ORDER BY in same SELECT statement?

Distinct will sort records in ascending order. If you want to sort in desc order use:

SELECT DISTINCT Category
FROM MonitoringJob
ORDER BY Category DESC

If you want to sort records based on CreationDate field then this field must be in the select statement:

SELECT DISTINCT Category, creationDate
FROM MonitoringJob
ORDER BY CreationDate DESC

What is the first character in the sort order used by Windows Explorer?

I know it's an old question, but it's easy to check this out. Just create a folder with a bunch of dummy files whose names are each character on the keyboard. Of course, you can't really use \ | / : * ? " < > and leading and trailing blanks are a terrible idea.

If you do this, and it looks like no one did, you find that the Windows sort order for the FIRST character is 1. Special characters 2. Numbers 3. Letters

But for subsequent characters, it seems to be 1. Numbers 2. Special characters 3. Letters

Numbers are kind of weird, thanks to the "Improvements" made after the Y2K non-event. Special characters you would think would sort in ASCII order, but there are exceptions, notably the first two, apostrophe and dash, and the last two, plus and equals. Also, I have heard but not actually seen something about dashes being ignored. That is, in fact, NOT my experience.

So, ShxFee, I assume you meant the sort should be ascending, not descending, and the top-most (first) character in the sort order for the first character of the name is the apostrophe.

As NigelTouch said, special characters do not sort to ASCII, but my notes above specify exactly what does and does not sort in normal ASCII order. But he is certainly wrong about special characters always sorting first. As I noted above, that only appears to be true for the first character of the name.

How to use boolean datatype in C?

C99 introduced _Bool as intrinsic pure boolean type. No #includes needed:

int main(void)
{
  _Bool b = 1;
  b = 0;
}

On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

How to convert enum value to int?

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(I've changed the names to be a bit more conventional and readable, btw.)

This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.

moving committed (but not pushed) changes to a new branch after pull

Alternatively, right after you commit to the wrong branch, perform these steps:

  1. git log
  2. git diff {previous to last commit} {latest commit} > your_changes.patch
  3. git reset --hard origin/{your current branch}
  4. git checkout -b {new branch}
  5. git apply your_changes.patch

I can imagine that there is a simpler approach for steps one and two.

Take multiple lists into dataframe

There are several ways to create a dataframe from multiple lists.

list1=[1,2,3,4]
list2=[5,6,7,8]
list3=[9,10,11,12]
  1. pd.DataFrame({'list1':list1, 'list2':list2, 'list3'=list3})

  2. pd.DataFrame(data=zip(list1,list2,list3),columns=['list1','list2','list3'])

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

To solve this issue you need to run your application by increasing the memory limit by using the option --max_old_space_size. By default the memory limit of Node.js is 512 mb.

node --max_old_space_size=2000  server.js 

Maven Could not resolve dependencies, artifacts could not be resolved

This kind of problems are caused by two reasons:

  1. the spell of a dependency is wrong
  2. the config of mvn setting (ie. ~/.m2/settings.xml) is wrong

If most of dependencies can be downloaded, then the reason 1 may be the most likely bug. On the contrary, if most of dependencies have the problem, then u should take a look at settings.xml.

Well, I have tried to fix my problem the whole afternoon, and finally I got it. My problem occurs in settings.xml, not the lose or wrong spelling of settings.xml, but the lose of activeProfiles.

Can PHP cURL retrieve response headers AND body in a single request?

If you specifically want the Content-Type, there's a special cURL option to retrieve it:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

How to calculate the difference between two dates using PHP?

You can also use following code to return date diff by round fractions up $date1 = $duedate; // assign due date echo $date2 = date("Y-m-d"); // current date $ts1 = strtotime($date1); $ts2 = strtotime($date2); $seconds_diff = $ts1 - $ts2; echo $datediff = ceil(($seconds_diff/3600)/24); // return in days

If you use floor method of php instead of ceil it will return you the round fraction down. Please check the difference here, some times if your staging servers timezone is different then the live site time zone in that case you may get different results so change the conditions accordingly.

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

Are you using express?

Check your path(note the "/" after /public/):

app.use(express.static(__dirname + "/public/"));

//note: you do not need the "/" before "css" because its already included above:

rel="stylesheet" href="css/style.css

Hope this helps

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

Using intents to pass data between activities

In FirstActivity:

Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);

In SecondActivity

In onCreate()

String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");

Combine two data frames by rows (rbind) when they have different sets of columns

You can use smartbind from the gtools package.

Example:

library(gtools)
df1 <- data.frame(a = c(1:5), b = c(6:10))
df2 <- data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
smartbind(df1, df2)
# result
     a  b    c
1.1  1  6 <NA>
1.2  2  7 <NA>
1.3  3  8 <NA>
1.4  4  9 <NA>
1.5  5 10 <NA>
2.1 11 16    A
2.2 12 17    B
2.3 13 18    C
2.4 14 19    D
2.5 15 20    E

How to parse month full form string using DateFormat in Java?

Just to top this up to the new Java 8 API:

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));

A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.

Calculate average in java

 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

simply "CUT" project folder and move it out of workspace directory and do the following

file=>import=>(select new directory)=> mark (copy to my workspace) checkbox 

and you done !

Failed to load resource: the server responded with a status of 404 (Not Found) css

Use the following Code:-

../css/main.css

Note: The "../" is shorthand for "The containing directory", or "Up one directory".

If you don't know the previous folder this will be very helpful..

How do I enable EF migrations for multiple contexts to separate databases?

In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like

class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
   ...
}

then just issue the command

Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName

and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:

Update-Database -ConfigurationTypeName MyNewContextConfiguration 

Done.

You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.

You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.

Volatile vs Static in Java

If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).

If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.

So, in both cases, the main point is that the value of the variable is same across all threads.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case I don't have issues with ~/.composer.
So being inside Laravel app root folder, I did sudo chown -R $USER composer.lock and it was helpful.

Interface vs Base class

I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.

In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.

So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.

If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.

I recommend this pattern even in multiple-inheritence languages.

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

Passing an array of parameters to a stored procedure

this is the best source:

http://www.sommarskog.se/arrays-in-sql.html

create a split function using the link, and use it like:

DELETE YourTable
    FROM YourTable                           d
    LEFT OUTER JOIN dbo.splitFunction(@Parameter) s ON d.ID=s.Value
    WHERE s.Value IS NULL

I prefer the number table approach

This is code based on the above link that should do it for you...

Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

CREATE TABLE Numbers
(Number int  NOT NULL,
    CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
    SET @x=@x+1
    INSERT INTO Numbers VALUES (@x)
END

use this function to split your string, which does not loop and is very fast:

CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn              char(1)              --REQUIRED, the character to split the @List string on
    ,@List                 varchar(8000)        --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
    ListValue varchar(500)
)
AS
BEGIN

/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.


Returns a table, one row per item in the list, with a column name "ListValue"

EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')

    returns:
        ListValue  
        -----------
        1
        12
        123
        1234
        54321
        6
        A
        *
        |||
        B

        (10 row(s) affected)

**/



----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
        (ListValue)
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''



RETURN

END --Function FN_ListToTable

you can use this function as a table in a join:

SELECT
    Col1, COl2, Col3...
    FROM  YourTable
        INNER JOIN dbo.FN_ListToTable(',',@YourString) s ON  YourTable.ID = s.ListValue

here is your delete:

DELETE YourTable
    FROM YourTable                                d
    LEFT OUTER JOIN dbo.FN_ListToTable(',',@Parameter) s ON d.ID=s.ListValue
    WHERE s.ListValue IS NULL

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

How to change title of Activity in Android?

The code helped me change the title.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);
    ActivityName.this.setTitle("Your Activity Title");}

Call Python function from MATLAB

I had a similar requirement on my system and this was my solution:

In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like

C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m

Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.

Example

A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.

import sys

def squared(x):
    y = x * x
    return y

if __name__ == '__main__':
    x = float(sys.argv[1])
    sys.stdout.write(str(squared(x)))

Then in MATLAB

>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>

History or log of commands executed in Git

I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.

Here's my workflow:

  1. before exiting bash type "history >> history.txt" [ENTER]
  2. exit the bash prompt
  3. hold Win+R to open the Run command box
  4. enter shell:profile
  5. open "history.txt" to confirm that my text was added
  6. On a new line press [F5] to enter a timestamp
  7. save and close the history textfile
  8. Delete the ".bash-history" file so the next session will create a new history

If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Difference between onStart() and onResume()

onStart() called when the activity is becoming visible to the user. onResume() called when the activity will start interacting with the user. You may want to do different things in this cases.

See this link for reference.

How to submit http form using C#

Here is a sample script that I recently used in a Gateway POST transaction that receives a GET response. Are you using this in a custom C# form? Whatever your purpose, just replace the String fields (username, password, etc.) with the parameters from your form.

private String readHtmlPage(string url)
   {

    //setup some variables

    String username  = "demo";
    String password  = "password";
    String firstname = "John";
    String lastname  = "Smith";

    //setup some variables end

      String result = "";
      String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
      StreamWriter myWriter = null;

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";

      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e) 
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr = 
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   } 

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

define('SECONDS_PER_DAY', 86400);
$days_ago = date('Y-m-d', time() - 5 * SECONDS_PER_DAY);

Other than that, you can use strtotime for any date:

$days_ago = date('Y-m-d', strtotime('January 18, 2034') - 5 * SECONDS_PER_DAY);

Or, as you used, mktime:

$days_ago = date('Y-m-d', mktime(0, 0, 0, 12, 2, 2008) - 5 * SECONDS_PER_DAY);

Well, you get it. The key is to remove enough seconds from the timestamp.

show dbs gives "Not Authorized to execute command" error

Copy of answer OP posted in question:

Solution

After the update from the previous edit, I looked a bit about the connection between client and server and I found out that even when mongod.exe was not running, there was still something listening on port 27017 with netstat -a

So I tried to launch the server with a random port using

[dir]mongod.exe --port 2000

Then the shell with

[dir]mongo.exe --port 2000

And this time, the server printed a message saying there is a new connection. I typed few commands and everything was working perfectly fine, I started the basic tutorial from the documentation to check if it was ok and for now it is.

Why do I get access denied to data folder when using adb?

There are two things to remember if you want to browse everything on your device.

  1. You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (ADP1 or an ION from Google I/O) or you've found a way to 'root' your phone some other way.
  2. You need to be running ADB in root mode, do this by executing: adb root

How to write an XPath query to match two attributes?

or //div[@id='id-74385'][@class='guest clearfix']

How to check if activity is in foreground or in visible background?

This can achieve this by a efficient way by using Application.ActivityLifecycleCallbacks

For example lets take Activity class name as ProfileActivity lets find whether its is in foreground or background

first we need to create our application class by extending Application Class

which implements

Application.ActivityLifecycleCallbacks

Lets be my Application class as follows

Application class

public class AppController extends Application implements Application.ActivityLifecycleCallbacks {


private boolean activityInForeground;

@Override
public void onCreate() {
    super.onCreate();

//register ActivityLifecycleCallbacks  

    registerActivityLifecycleCallbacks(this);

}



public static boolean isActivityVisible() {
    return activityVisible;
}

public static void activityResumed() {
    activityVisible = true;
}

public static void activityPaused() {
    activityVisible = false;
}

private static boolean activityVisible;

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {
    //Here you can add all Activity class you need to check whether its on screen or not

    activityInForeground = activity instanceof ProfileActivity;
}

@Override
public void onActivityPaused(Activity activity) {

}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}

public boolean isActivityInForeground() {
    return activityInForeground;
}
}

in the above class there is a override methord onActivityResumed of ActivityLifecycleCallbacks

 @Override
public void onActivityResumed(Activity activity) {
    //Here you can add all Activity class you need to check whether its on screen or not

    activityInForeground = activity instanceof ProfileActivity;
}

where all activity instance which is currently displayed on screen can be found, just check whether Your Activity is on Screen or not by the above method.

Register your Application class in manifest.xml

<application
    android:name=".AppController" />

To check weather Activity is Foreground or background as per the above solution call the following method on places you need to check

AppController applicationControl = (AppController) getApplicationContext();
    if(applicationControl.isActivityInForeground()){
     Log.d("TAG","Activity is in foreground")
    }
    else
    {
      Log.d("TAG","Activity is in background")
    }

Round number to nearest integer

Your solution is calling round without specifying the second argument (number of decimal places)

>>> round(0.44)
0
>>> round(0.64)
1

which is a much better result than

>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0

From the Python documentation at https://docs.python.org/3/library/functions.html#round

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Render Partial View Using jQuery in ASP.NET MVC

If you need to reference a dynamically generated value you can also append query string paramters after the @URL.Action like so:

    var id = $(this).attr('id');
    var value = $(this).attr('value');
    $('#user_content').load('@Url.Action("UserDetails","User")?Param1=' + id + "&Param2=" + value);


    public ActionResult Details( int id, string value )
    {
        var model = GetFooModel();
        if (Request.IsAjaxRequest())
        {
            return PartialView( "UserDetails", model );
        }
        return View(model);
    }

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

How to update Ruby with Homebrew?

Adding to the selected answer (as I haven't enough rep to add comment), one way to see the list of available versions (from ref) try:

$ rbenv install -l

Where to put Gradle configuration (i.e. credentials) that should not be committed?

You could put the credentials in a properties file and read it using something like this:

Properties props = new Properties() 
props.load(new FileInputStream("yourPath/credentials.properties")) 
project.setProperty('props', props)

Another approach is to define environment variables at the OS level and read them using:

System.getenv()['YOUR_ENV_VARIABLE']

How do I open a new fragment from another fragment?

Using Kotlin to replace a Fragment with another to the container , you can do

button.setOnClickListener {
    activity!!
        .supportFragmentManager
        .beginTransaction()
        .replace(R.id.container, NewFragment.newInstance())
        .commitNow()
}

How to overcome the CORS issue in ReactJS

Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

A simpler way is to use express-http-proxy

  1. run npm run build to create the bundle.

    var proxy = require('express-http-proxy');
    
    var app = require('express')();
    
    //define the path of build
    
    var staticFilesPath = path.resolve(__dirname, '..', 'build');
    
    app.use(express.static(staticFilesPath));
    
    app.use('/api/api-server', proxy('www.api-server.com'));
    

Use "/api/api-server" from react code to call the API.

So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

How might I find the largest number contained in a JavaScript array?

Don't forget that the wrap can be done with Function.prototype.bind, giving you an "all-native" function.

var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5

How to select option in drop down using Capybara

If you take a look at the source of the select method, you can see that what it does when you pass a from key is essentially:

find(:select, from, options).find(:option, value, options).select_option

In other words, it finds the <select> you're interested in, then finds the <option> within that, then calls select_option on the <option> node.

You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option method on the end:

find('#organizationSelect').find(:xpath, 'option[2]').select_option

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Programmatically obtain the phone number of the Android phone

Wouldn't be recommending to use TelephonyManager as it requires the app to require READ_PHONE_STATE permission during runtime.

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

Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.

implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
    val googleApiClient = GoogleApiClient.Builder(context)
        .addApi(Auth.CREDENTIALS_API).build()

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
        googleApiClient, hintRequest
    )

    startIntentSenderForResult(
        hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
    )
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PHONE_NUMBER -> {
            if (requestCode == Activity.RESULT_OK) {
                val credential = data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
                val selectedPhoneNumber = credential?.id
            }
        }
    }
}

Loading all images using imread from a given folder

you can use glob function to do this. see the example

import cv2
import glob
for img in glob.glob("path/to/folder/*.png"):
    cv_img = cv2.imread(img)

Eclipse cannot load SWT libraries

Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk-3740.so
Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk.so

looks like the libraries should be at .swt/lib/linux/x86_64/ if there are not there you can try this command:

locate  libswt-gtk.so

this should find the libraries copy the entire directory to /home/tom/.swt/lib/linux/x86_64

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

Static way to get 'Context' in Android?

Assuming we're talking about getting the Application Context, I implemented it as suggested by @Rohit Ghatol extending Application. What happened then, it's that there's no guarantee that the context retrieved in such a way will always be non-null. At the time you need it, it's usually because you want to initialize an helper, or get a resource, that you cannot delay in time; handling the null case will not help you. So I understood I was basically fighting against the Android architecture, as stated in the docs

Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.

and explained by Dianne Hackborn

The only reason Application exists as something you can derive from is because during the pre-1.0 development one of our application developers was continually bugging me about needing to have a top-level application object they can derive from so they could have a more "normal" to them application model, and I eventually gave in. I will forever regret giving in on that one. :)

She is also suggesting the solution to this problem:

If what you want is some global state that can be shared across different parts of your app, use a singleton. [...] And this leads more naturally to how you should be managing these things -- initializing them on demand.

so what I did was getting rid of extending Application, and pass the context directly to the singleton helper's getInstance(), while saving a reference to the application context in the private constructor:

private static MyHelper instance;
private final Context mContext;    

private MyHelper(@NonNull Context context) {
    mContext = context.getApplicationContext();
}

public static MyHelper getInstance(@NonNull Context context) {
    synchronized(MyHelper.class) {
        if (instance == null) {
            instance = new MyHelper(context);
        }
        return instance;
    }
}

the caller will then pass a local context to the helper:

Helper.getInstance(myCtx).doSomething();

So, to answer this question properly: there are ways to access the Application Context statically, but they all should be discouraged, and you should prefer passing a local context to the singleton's getInstance().


For anyone interested, you can read a more detailed version at fwd blog

Adjust table column width to content size

The problem was the table width. I had used width: 100% for the table. The table columns are adjusted automatically after removing the width tag.

Find the closest ancestor element that has a specific class

Use element.closest()

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

See this example DOM:

<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>

This is how you would use element.closest:

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");  
// returns the element with the id=div-02

var r2 = el.closest("div div");  
// returns the closest ancestor which is a div in div, here is div-03 itself

var r3 = el.closest("article > div");  
// returns the closest ancestor which is a div and has a parent article, here is div-01

var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here is the outmost article

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

Waiting for HOME ('android.process.acore') to be launched

Options:

  • Click on the HOME Button on the Emulator. Wait for may be 2 seconds.... This always works for me!!!

or

  • Go with Shreya's suggestion (one with most suggestions and edited by Gray).

Apache won't start in wamp

That is what I did and it helped me to find out what my Apache-PHP needed:

C:\Users\Admin>cd C:\wamp\bin\apache\apache2.4.9\bin

C:\wamp\bin\apache\apache2.4.9\bin>httpd -t
Syntax OK

C:\wamp\bin\apache\apache2.4.9\bin>httpd -k start
[Thu Apr 23 14:14:52.150189 2015] [mpm_winnt:error] [pid 3184:tid 112] 
(OS 2)The system cannot find the file specified.  : AH00436: 
No installed service named "Apache2.4".

C:\wamp\bin\apache\apache2.4.9\bin>

The most simple solution:

Uninstall and reinstall WAMP (do not even try to set it up on top of existing installation - it would not help)

P.S.

If you wonder how did I get to this situation, here is the answer: I was trying to install WAMP and it throws me an error in the middle of installation saying:

httpd.exe - System Error

The program can't start because MSVCR110.dll is missing from your computer. 
Try reinstalling the program to fix this problem.

OK

I got and installed Microsoft Visual C++ 2012 Redistributable from here http://www.microsoft.com/en-us/download/details.aspx?id=30679#

And it gave me the "dll" and the MYSQL started working, but not Apache. To make Apache to work I uninstalled and reinstalled WAMP.

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I had the same problem with something like

@foreach (var item in Model)
{
    @Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
}

I solved this just by doing

@foreach (var item in Model)
{
    var active = !item.IsIdle;
    @Html.DisplayFor(m => active , "BoolIcon")
}

When you know the trick, it's simple.

The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.

Convert decimal to binary in python

You can also use a function from the numpy module

from numpy import binary_repr

which can also handle leading zeros:

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.

How can I scale an entire web page with CSS?

Scale is not the best option

It will need some other adjustments, like margins paddings etc ..

but the right option is

zoom: 75%

Checking for a null int value from a Java ResultSet

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

e.g for an Oracle database, use NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

log4j:WARN No appenders could be found for logger in web.xml

I had the same problem . Same configuration settings and same warning message . What worked for me was : Changing the order of the entries .

  • I put the entries for the log configuration [ the context param and the listener ] on the top of the file [ before the entry for the applicationContext.xml ] and it worked .

The Order matters , i guess .

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

convert float into varchar in SQL server without scientific notation

Try this:

SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(CAST(CAST(YOUR_FLOAT_COLUMN_NAME AS DECIMAL(18,9)) AS VARCHAR(20)),'0',' ')),' ','0'),'.',' ')),' ','.') FROM YOUR_TABLE_NAME
  1. Casting as DECIMAL will put decimal point on every value, whether it had one before or not.
  2. Casting as VARCHAR allows you to use the REPLACE function
  3. First REPLACE zeros with spaces, then RTRIM to get rid of all trailing spaces (formerly zeros), then REPLACE remaining spaces with zeros.
  4. Then do the same for the period to get rid of it for numbers with no decimal values.

CSS show div background image on top of other contained elements

If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.

Try increasing the padding of the main div style:

#mainWrapperDivWithBGImage 
{   
    background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;   
    height: 248px;   
    margin: 0;   
    overflow: hidden;   
    padding: 10px 10px;   
    width: 996px; 
}

P.S: I assume the rounded corners have a radius of 10px.

HTML5 iFrame Seamless Attribute

I thought this might be useful to someone:

in chrome version 32, a 2-pixels border automatically appears around iframes without the seamless attribute. It can be easily removed by adding this CSS rule:

iframe:not([seamless]) { border:none; }

Chrome uses the same selector with these default user-agent styles:

iframe:not([seamless]) {
  border: 2px inset;
  border-image-source: initial;
  border-image-slice: initial;
  border-image-width: initial;
  border-image-outset: initial;
  border-image-repeat: initial;
}

Call and receive output from Python script in Java?

You can try using groovy. It runs on the JVM and it comes with great support for running external processes and extracting the output:

http://groovy.codehaus.org/Executing+External+Processes+From+Groovy

You can see in this code taken from the same link how groovy makes it easy to get the status of the process:

println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

How do I use disk caching in Picasso?

For caching, I would use OkHttp interceptors to gain control over caching policy. Check out this sample that's included in the OkHttp library.

RewriteResponseCacheControl.java

Here's how I'd use it with Picasso -

OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
        }
    });

    okHttpClient.setCache(new Cache(mainActivity.getCacheDir(), Integer.MAX_VALUE));
    OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
    Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
    picasso.load(imageURL).into(viewHolder.image);

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

What is the shortcut in IntelliJ IDEA to find method / functions?

I tried SHIFT + SHIFT and ALT + CMD + O

But I think the most powerful and easy to use feature is find in all files CMD + SHIFT + F.

Choose regex and write .*partOfMethodName.*\( and it shows all places and can see the actual source code in place without going to that specific file.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How do I run Redis on Windows?

The Redis project does not officially support Windows. However, the Microsoft Open Tech group develops and maintains this Windows port targeting Win64.

http://redis.io/download

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

Convert object string to JSON

I hope this little function converts invalid JSON string to valid one.

function JSONize(str) {
  return str
    // wrap keys without quote with valid double quote
    .replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":'})    
    // replacing single quote wrapped ones to double quote 
    .replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"'})         
}

Result

let invalidJSON = "{ hello: 'world',foo:1,  bar  : '2', foo1: 1, _bar : 2, $2: 3, 'xxx': 5, \"fuz\": 4, places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.parse(invalidJSON) 
//Result: Uncaught SyntaxError: Unexpected token h VM1058:2
JSON.parse(JSONize(invalidJSON)) 
//Result: Object {hello: "world", foo: 1, bar: "2", foo1: 1, _bar: 2…}

ASP.NET MVC View Engine Comparison

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


System.Web.Mvc.WebFormViewEngine

Design Goals:

A view engine that is used to render a Web Forms page to the response.

Pros:

  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views

Cons:

  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates

Example:

<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

System.Web.Razor

Design Goals:

Pros:

  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC

Cons:

  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API, http://msdn.microsoft.com/en-us/library/system.web.razor.aspx

Con Example #1 (notice the placement of "string[]..."):

@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Bellevue

Design goals:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
  • Enforce strict Model-View separation

Brail

Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.

Pros:

  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)

Cons:

  • designed to be written in the language Boo

Example:

<html>    
<head>        
<title>${title}</title>
</head>    
<body>        
     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    
</body>
</html>

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable

Cons:

  • Performance: Builds the whole DOM before sending it to client.

Example:

Protected Overrides Function Body() As XElement
    Return _
    <body>
        <h1>Hello, World</h1>
    </body>
End Function

NDjango

Design Goals:

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.

Pros:


NHaml

Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.

Pros:

  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)

Cons:

  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010

Example:

@type=IEnumerable<Product>
- if(model.Any())
  %ul
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.

Pros:

  • easy to read/write
  • concise view code

Cons:

  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)

Example:

#foreach ($p in $viewdata.Model)
#beforeall
    <ul>
#each
    <li>$p.Name</li>
#afterall
    </ul>
#nodata 
    <p>No products available</p>
#end

SharpTiles

Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Pros:

  • familiar to Java developers
  • XML-style code blocks

Cons:

  • ...

Example:

<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>
  </p>
</c:if>

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Pros:

  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags

Cons:

  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)

Example:

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
</ul>
<else>
    <p>No products available</p>
</else>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />
</Form>

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.

Pros:

  • familiar to StringTemplate Java developers

Cons:

  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable

Cons:

  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT

Pros:

  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.

Cons:

  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

Format datetime in asp.net mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407


Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

Model:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to add a border just on the top side of a UIView

The best way for me is a category on UIView, but adding views instead of CALayers, so we can take advantage of AutoresizingMasks to make sure borders resize along with the superview.

Objective C

- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
    [self addSubview:border];
}

- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
    border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
    [self addSubview:border];
}

Swift 5

func addTopBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
    border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addLeftBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.frame = CGRect(x: 0, y: 0, width: borderWidth, height: frame.size.height)
    border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
    addSubview(border)
}

func addRightBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
    border.frame = CGRect(x: frame.size.width - borderWidth, y: 0, width: borderWidth, height: frame.size.height)
    addSubview(border)
}

Python urllib2 Basic Auth Problem

Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.

import urllib2
import base64

chimpConfig = {
    "headers" : {
    "Content-Type": "application/json",
    "Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
    },
    "url": 'https://us12.api.mailchimp.com/3.0/'}

#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files\PostgreSQL\8.4\data\postgresql.conf

Collections.emptyList() returns a List<Object>?

The issue you're encountering is that even though the method emptyList() returns List<T>, you haven't provided it with the type, so it defaults to returning List<Object>. You can supply the type parameter, and have your code behave as expected, like this:

public Person(String name) {
  this(name,Collections.<String>emptyList());
}

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

public Person(String name) {
  List<String> emptyList = Collections.emptyList();
  this(name, emptyList);
}

then the emptyList() call would correctly return a List<String>.

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Open Source HTML to PDF Renderer with Full CSS Support

Try ABCpdf from webSupergoo. It's a commercial solution, not open source, but the standard edition can be obtained free of charge and will do what you are asking.

ABCpdf fully supports HTML and CSS, live forms and live links. It also uses Microsoft XML Core Services (MSXML) while rendering, so the results should match exactly what you see in Internet Explorer.

The on-line demo can be used to test HTML to PDF rendering without needing to install any software. See: http://www.abcpdfeditor.com/

The following C# code example shows how to render a single page HTML document.

Doc theDoc = new Doc();
theDoc.AddImageUrl("http://www.example.com/");
theDoc.Save("htmlimport.pdf");
theDoc.Clear();

To render multiple pages you'll need the AddImageToChain function, documented here: http://www.websupergoo.com/helppdf7net/source/5-abcpdf6/doc/1-methods/addimagetochain.htm

Javascript string replace with regex to strip off illegal characters

I tend to look at it from the inverse perspective which may be what you intended:

What characters do I want to allow?

This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.

For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:

"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

It's very old problem with cashed content. MS planning to remove diagrams from SSMS, so they don't care about this. Anyway, solution exists.

Just close Diagrams tab and open it again. Works with SSMS 18.2.

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

Program does not contain a static 'Main' method suitable for an entry point

Just in case anyone is having the same problem... I was getting this error, and it turned out to be my <Application.Resources> in my App.xaml file. I had a resource outside my resource dictionary tags, and that caused this error.

What's the difference between jquery.js and jquery.min.js?

Both contain the same functionality but the .min.js equivalent has been optimized in size. You can open both files and take a look at them. In the .min.js file you'll notice that all variables names have been reduced to short names and that most whitespace & comments have been taken out.