Programs & Examples On #Jquery corner

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

How to write a PHP ternary operator

You wouldn’t: it’s messy and hard to read.

You’re looking for the switch statement in the first case. The second is fine as it is but still could be converted for consistency

Ternary statements are much more suited to boolean values and alternating logic.

SELECT FOR UPDATE with SQL Server

You cannot have snapshot isolation and blocking reads at the same time. The purpose of snapshot isolation is to prevent blocking reads.

How to print a two dimensional array?

you can use the Utility mettod. Arrays.deeptoString();

 public static void main(String[] args) {
    int twoD[][] = new int[4][]; 
    twoD[0] = new int[1]; 
    twoD[1] = new int[2]; 
    twoD[2] = new int[3]; 
    twoD[3] = new int[4]; 

    System.out.println(Arrays.deepToString(twoD));

}

Uninstall Django completely

I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.

How to easily initialize a list of Tuples?

Yes! This is possible.

The { } syntax of the collection initializer works on any IEnumerable type which has an Add method with the correct amount of arguments. Without bothering how that works under the covers, that means you can simply extend from List<T>, add a custom Add method to initialize your T, and you are done!

public class TupleList<T1, T2> : List<Tuple<T1, T2>>
{
    public void Add( T1 item, T2 item2 )
    {
        Add( new Tuple<T1, T2>( item, item2 ) );
    }
}

This allows you to do the following:

var groceryList = new TupleList<int, string>
{
    { 1, "kiwi" },
    { 5, "apples" },
    { 3, "potatoes" },
    { 1, "tomato" }
};

How to use the IEqualityComparer

If you want a generic solution without boxing:

public class KeyBasedEqualityComparer<T, TKey> : IEqualityComparer<T>
{
    private readonly Func<T, TKey> _keyGetter;

    public KeyBasedEqualityComparer(Func<T, TKey> keyGetter)
    {
        _keyGetter = keyGetter;
    }

    public bool Equals(T x, T y)
    {
        return EqualityComparer<TKey>.Default.Equals(_keyGetter(x), _keyGetter(y));
    }

    public int GetHashCode(T obj)
    {
        TKey key = _keyGetter(obj);

        return key == null ? 0 : key.GetHashCode();
    }
}

public static class KeyBasedEqualityComparer<T>
{
    public static KeyBasedEqualityComparer<T, TKey> Create<TKey>(Func<T, TKey> keyGetter)
    {
        return new KeyBasedEqualityComparer<T, TKey>(keyGetter);
    }
}

usage:

KeyBasedEqualityComparer<Class_reglement>.Create(x => x.Numf)

Cannot drop database because it is currently in use

First check the connected databases

SP_WHO

Second Disconnect your database

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'your_database_name'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)

FINALLY DROP IT

drop database your_database

How to store a list in a column of a database table

Simple answer: If, and only if, you're certain that the list will always be used as a list, then join the list together on your end with a character (such as '\0') that will not be used in the text ever, and store that. Then when you retrieve it, you can split by '\0'. There are of course other ways of going about this stuff, but those are dependent on your specific database vendor.

As an example, you can store JSON in a Postgres database. If your list is text, and you just want the list without further hassle, that's a reasonable compromise.

Others have ventured suggestions of serializing, but I don't really think that serializing is a good idea: Part of the neat thing about databases is that several programs written in different languages can talk to one another. And programs serialized using Java's format would not do all that well if a Lisp program wanted to load it.

If you want a good way to do this sort of thing there are usually array-or-similar types available. Postgres for instance, offers array as a type, and lets you store an array of text, if that's what you want, and there are similar tricks for MySql and MS SQL using JSON, and IBM's DB2 offer an array type as well (in their own helpful documentation). This would not be so common if there wasn't a need for this.

What you do lose by going that road is the notion of the list as a bunch of things in sequence. At least nominally, databases treat fields as single values. But if that's all you want, then you should go for it. It's a value judgement you have to make for yourself.

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

How can I check for IsPostBack in JavaScript?

Here is one way (put this in Page_Load):

if (this.IsPostBack)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>");
}

Then just check that variable in the JS.

Upload video files via PHP and save them in appropriate folder and have a database entry

sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

How to send a "multipart/form-data" with requests in python?

import requests
# assume sending two files
url = "put ur url here"
f1 = open("file 1 path", 'rb')
f2 = open("file 2 path", 'rb')
response = requests.post(url,files={"file1 name": f1, "file2 name":f2})
print(response)

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

You need to run these two commands

php artisan cache:clear
php artisan config:cache

How can I obfuscate (protect) JavaScript?

There are a number of JavaScript obfuscation tools that are freely available; however, I think it's important to note that it is difficult to obfuscate JavaScript to the point where it cannot be reverse-engineered.

To that end, there are several options that I've used to some degree overtime:

  • YUI Compressor. Yahoo!'s JavaScript compressor does a good job of condensing the code that will improve its load time. There is a small level of obfuscation that works relatively well. Essentially, Compressor will change function names, remove white space, and modify local variables. This is what I use most often. This is an open-source Java-based tool.

  • JSMin is a tool written by Douglas Crockford that seeks to minify your JavaScript source. In Crockford's own words, "JSMin does not obfuscate, but it does uglify." It's primary goal is to minify the size of your source for faster loading in browsers.

  • Free JavaScript Obfuscator. This is a web-based tool that attempts to obfuscate your code by actually encoding it. I think that the trade-offs of its form of encoding (or obfuscation) could come at the cost of filesize; however, that's a matter of personal preference.

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

What is the instanceof operator in JavaScript?

instanceof is just syntactic sugar for isPrototypeOf:

function Ctor() {}
var o = new Ctor();

o instanceof Ctor; // true
Ctor.prototype.isPrototypeOf(o); // true

o instanceof Ctor === Ctor.prototype.isPrototypeOf(o); // equivalent

instanceof just depends on the prototype of a constructor of an object.

A constructor is just a normal function. Strictly speaking it is a function object, since everything is an object in Javascript. And this function object has a prototype, because every function has a prototype.

A prototype is just a normal object, which is located within the prototype chain of another object. That means being in the prototype chain of another object makes an object to a prototype:

function f() {} //  ordinary function
var o = {}, // ordinary object
 p;

f.prototype = o; // oops, o is a prototype now
p = new f(); // oops, f is a constructor now

o.isPrototypeOf(p); // true
p instanceof f; // true

The instanceof operator should be avoided because it fakes classes, which do not exist in Javascript. Despite the class keyword not in ES2015 either, since class is again just syntactic sugar for...but that's another story.

Is there a Java API that can create rich Word documents?

In 2007 my project successfully used OpenOffice.org's Universal Network Objects (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).

OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables.

We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival.

You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools.

UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An OpenOffice Software Development Kit (SDK) is available containing example applications and the UNO Developer's Guide.

I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.

The important things about OpenOffice UNO are:

  1. It is freeware
  2. It supports multiple languages (e.g. Visual Basic, Java, C++, and others).
  3. It is platform-independent (Windows, Linux, Unix, etc.).

Here are some useful web sites:

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml

<java.version>7</java.version>

to

<java.version>11</java.version>

Later to realise the property was used with a dash insteal of a dot:

  <source>${java-version}</source>
  <target>${java-version}</target>

(swearings), I replaced the dot with a dash and the error went away:

<java-version>11</javaversion>

How to find Control in TemplateField of GridView?

If your GridView is databond, make an index column in the resultset you retrive like this:

select row_number() over(order by YourIdentityColumn asc)-1 as RowIndex, * from YourTable where [Expresion]

In the command control you want to use make the value of CommandArgument property equal to the row index of the DataSet table RowIndex like this:

<asp:LinkButton ID="lbnMsgSubj" runat="server" Text='<%# Eval("MsgSubj") %>' Font-Underline="false" CommandArgument='<%#Eval("RowIndex") %>' />

Use the OnRowCommand event to fire on clicking the link button like this:

<asp:GridView ID="gvwStuMsgBoard" runat="server" AutoGenerateColumns="false" GridLines="Horizontal" BorderColor="Transparent" Width="100%" OnRowCommand="gvwStuMsgBoard_RowCommand">

Finally the code behind you can then do whatever you like when the event is triggered like this:

protected void gvwStuMsgBoard_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Panel pnlMsgBody = (Panel)gvwStuMsgBoard.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("pnlMsgBody");
    if(pnlMsgBody.Visible == false)
    {
        pnlMsgBody.Visible = true;
    }
    else
    {
        pnlMsgBody.Visible = false;
    }
}

How to check if field is null or empty in MySQL?

SELECT * FROM ( 
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION 
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID) 
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)  
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

fatal error: mpi.h: No such file or directory #include <mpi.h>

As suggested above the inclusion of

/usr/lib/openmpi/include 

in the include path takes care of this (in my case)

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

The Package is missing. Open Package Manager Console and execute the code below:

Install-Package Microsoft.EntityFrameworkCore.SqlServer 

How to pass a variable from Activity to Fragment, and pass it back?

You can simply instantiate your fragment with a bundle:

Fragment fragment = Fragment.instantiate(this, RolesTeamsListFragment.class.getName(), bundle);

Doing HTTP requests FROM Laravel to an external API

As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:

use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');

You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response instance returned.

$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

Please note that you will, of course, need to install Guzzle like so:

composer require guzzlehttp/guzzle

There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client

This is definitely now the easiest way to make external API calls within Laravel.

How to push JSON object in to array using javascript

can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data

 var my_json;
    $.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
    console.log(json1);
        var data = [];
    json1.feeds.forEach(function(feed,i){
        console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
        my_json = feed;
        console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
        data.push(my_json);
    }); 

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I got this error when running Visual Studio. By running Visual Studio as Administrator the application was able to access the Security logs as it then had sufficient permissions (thus preventing the error).

How to install a specific version of Node on Ubuntu?

It is possible to install specific version of nodejs from nodejs official distribution with using dpkg.

For example, currently recent 4.x version is 4.2.4, but you can install previous 4.2.3 version.

curl -s -O https://deb.nodesource.com/node_4.x/pool/main/n/nodejs/nodejs_4.2.3-1nodesource1~trusty1_amd64.deb
sudo apt-get install rlwrap
sudo dpkg -i nodejs_4.2.3-1nodesource1~trusty1_amd64.deb

How to download image using requests

You can either use the response.raw file object, or iterate over the response.

To use the response.raw file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting the decode_content attribute to True (requests sets it to False to control decoding itself). You can then use shutil.copyfileobj() to have Python stream the data to a file object:

import requests
import shutil

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)        

To iterate over the response use a loop; iterating like this ensures that data is decompressed by this stage:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r:
            f.write(chunk)

This'll read the data in 128 byte chunks; if you feel another chunk size works better, use the Response.iter_content() method with a custom chunk size:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r.iter_content(1024):
            f.write(chunk)

Note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. We also set stream=True so that requests doesn't download the whole image into memory first.

String comparison technique used by Python

A pure Python equivalent for string comparisons would be:

def less(string1, string2):
    # Compare character by character
    for idx in range(min(len(string1), len(string2))):
        # Get the "value" of the character
        ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
        # If the "value" is identical check the next characters
        if ordinal1 == ordinal2:
            continue
        # It's not equal so we're finished at this index and can evaluate which is smaller.
        else:
            return ordinal1 < ordinal2
    # We're out of characters and all were equal, so the result depends on the length
    # of the strings.
    return len(string1) < len(string2)

This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for < comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.

A more general variant would be:

from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

This problem is generally caused by the website/intranet URL being placed in one of:

  • Compatibility Mode List
  • Internet Explorer Intranet Zone
    (with Display intranet sites in Compatibility View setting enabled)
  • Enterprise Mode List

On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.

IE 11 Enterprise Mode

Unfortunately setting META X-UA-Compatible will not override this.

For End-Users

Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.

You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.

To see the list of domains that belong to the Intranet zone, go to:

Tools -> Internet Options -> Security -> Sites -> Advanced

If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.

You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.

For Network Admins

Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.

All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.

If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:

Detect and exclude outliers in Pandas data frame

Deleting and dropping outliers I believe is wrong statistically. It makes the data different from original data. Also makes data unequally shaped and hence best way is to reduce or avoid the effect of outliers by log transform the data. This worked for me:

np.log(data.iloc[:, :])

Java dynamic array sizes?

In java array length is fixed.

You can use a List to hold the values and invoke the toArray method if needed See the following sample:

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class A  {

    public static void main( String [] args ) {
        // dynamically hold the instances
        List<xClass> list = new ArrayList<xClass>();

        // fill it with a random number between 0 and 100
        int elements = new Random().nextInt(100);  
        for( int i = 0 ; i < elements ; i++ ) {
            list.add( new xClass() );
        }

        // convert it to array
        xClass [] array = list.toArray( new xClass[ list.size() ] );


        System.out.println( "size of array = " + array.length );
    }
}
class xClass {}

What is the correct way to declare a boolean variable in Java?

First of all, you should use none of them. You are using wrapper type, which should rarely be used in case you have a primitive type. So, you should use boolean rather.

Further, we initialize the boolean variable to false to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false.

But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.

But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default value.

So, in your case I would use it like this: -

boolean isMatch = email1.equals (email2);

How to initialize an array in angular2 and typescript

In order to make more concise you can declare constructor parameters as public which automatically create properties with same names and these properties are available via this:

export class Environment {

  constructor(public id:number, public name:string) {}

  getProperties() {
    return `${this.id} : ${this.name}`;
  }
}

let serverEnv = new Environment(80, 'port');
console.log(serverEnv);

 ---result---
// Environment { id: 80, name: 'port' }

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

I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc.

So source /etc/bash.bashrc did the trick for me!

update

When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.

It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/

Now, you will edit and (and "source") the ~/.bashrc file.

On my server, this was located at /home/your_username/.bashrc
(where your_username is actually the new username you created above, and now login with)

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

Parsing a JSON string in Ruby

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

How can you print multiple variables inside a string using printf?

Change the line where you print the output to:

printf("\nmaximum of %d and %d is = %d",a,b,c);

See the docs here

Check if the file exists using VBA

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:\InitialPath\"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you'll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you'll need to find the correct help for the version you're using).

Access event to call preventdefault from custom function originating from onclick attribute of tag

I think when we use onClick we want to do something different than default. So, for all your links with onClick:

$("a[onClick]").on("click", function(e) {
  return e.preventDefault();
});

Filter object properties by key in ES6

const filteredObject = Object.fromEntries(Object.entries(originalObject).filter(([key, value]) => key !== uuid))

How to test if a DataSet is empty?

Don't forget to set table name da.Fill(ds,"tablename");

So you return data using table name instead of 0

if (ds.Tables["tablename"].Rows.Count == 0)
 {
  MessageBox.Show("No result found");
 }

SQL Server 2008: How to query all databases sizes?

SELECT
    DB.name,
    SUM(CASE WHEN type = 0 THEN MF.size * 8 / 1024 ELSE 0 END) AS DataFileSizeMB,
    SUM(CASE WHEN type = 1 THEN MF.size * 8 / 1024 ELSE 0 END) AS LogFileSizeMB
FROM
    sys.master_files MF
    JOIN sys.databases DB ON DB.database_id = MF.database_id
GROUP BY DB.name
ORDER BY DataFileSizeMB DESC

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

This is a simple solution that worked for me with the same problem (I think): mv /var/lib/mongodb /var/lib/mongodb_backup mkdir /var/lib/mongodb chmod 700 /var/lib/mongodb chown mongodb:daemon /var/lib/mongodb systemctl restart mongodb or service mongod restart

how to run python files in windows command prompt?

You have to install Python and add it to PATH on Windows. After that you can try:

python `C:/pathToFolder/prog.py`

or go to the files directory and execute:

python prog.py

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

How to implement drop down list in flutter?

When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:

dropdown_string_button.dart

import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage: 
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
  DropdownStringButton({
    Key key, @required List<String> items, value, hint, disabledHint,
    @required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
    isExpanded = false, }) : 
    assert(items == null || value == null || items.where((String item) => item == value).length == 1),
        super(
          key: key,
          items: items.map((String item) {
            return DropdownMenuItem<String>(child: Text(item), value: item);
          }).toList(),
        value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
        elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
        isExpanded: isExpanded,
        );
    }

not-null property references a null or transient value

Make that variable as transient.Your problem will get solved..

@Column(name="emp_name", nullable=false, length=30)
    private transient String empName;

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

Auto-Submit Form using JavaScript

You need to specify a frame, a target otherwise your script will vanish on first submit!

Change document.myForm with document.forms["myForm"]:

<form name="myForm" id="myForm" target="_myFrame" action="test.php" method="POST">
    <p>
        <input name="test" value="test" />
    </p>
    <p>
        <input type="submit" value="Submit" />
    </p>
</form>

<script type="text/javascript">
    window.onload=function(){
        var auto = setTimeout(function(){ autoRefresh(); }, 100);

        function submitform(){
          alert('test');
          document.forms["myForm"].submit();
        }

        function autoRefresh(){
           clearTimeout(auto);
           auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
        }
    }
</script>

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

This is what I ended up using. Temporarily sets target to _blank, then sets it back.

OnClientClick="var originalTarget = document.forms[0].target; document.forms[0].target = '_blank'; setTimeout(function () { document.forms[0].target = originalTarget; }, 3000);"

Angular 2 Dropdown Options Default Value

Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.

HTML template:

<select (change)="onValueChanged($event.target)">
    <option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>

Component:

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';    
export class UifDropdownComponent implements OnInit {
    @Input() uifOptions: {value: string, text: string}[];
    @Input() uifSelectedValue: string = '';
    @Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
    uifSelected: {value: string, text: string} = {'value':'', 'text':''};

    constructor() { }

    onValueChanged(target: HTMLSelectElement):void {
        this.uifSelectedValue = target.value;
        this.uifSelectedValueChange.emit(this.uifSelectedValue);
    }

    ngOnInit() {
        this.uifSelected = this.uifOptions.filter(o => o.value == 
        this.uifSelectedValue)[0];
    }
}

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

changing the project to use java 1.7: For this to work follow those steps :

  • Change Compiler Compliance Level
  • Change your projects JRE/JDK to something of the same level(1.7 in my case)
  • Do the same change in all the projects referenced by your project
  • Change your run/debug configuration to use the JRE/JDK (or of the same level)

Not working?

  • delete projects Bin directory
  • Clean
  • reBuild

Still not working?

in your project's directory: edit .settings/org.eclipse.jdt.core.prefs > make sure your target level is applied

Good Luck!

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

This works fine

public class DateDemo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
        String date = "16-08-2018 12:10";
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("VALUE="+localDate);

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        LocalDateTime parse = LocalDateTime.parse(date, formatter1);
        System.out.println("VALUE1="+parse);
    }
}

output:

VALUE=2018-08-16
VALUE1=2018-08-16T12:10

The performance impact of using instanceof in Java

I just made a simple test to see how instanceOf performance is comparing to a simple s.equals() call to a string object with only one letter.

in a 10.000.000 loop the instanceOf gave me 63-96ms, and the string equals gave me 106-230ms

I used java jvm 6.

So in my simple test is faster to do a instanceOf instead of a one character string comparison.

using Integer's .equals() instead of string's gave me the same result, only when I used the == i was faster than instanceOf by 20ms (in a 10.000.000 loop)

What's better at freeing memory with PHP: unset() or $var = null

<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds\r\n";



$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    unset($a);
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds\r\n";
?>

Per that it seems like "= null" is faster.

PHP 5.4 results:

  • took 0.88389301300049 seconds
  • took 2.1757180690765 seconds

PHP 5.3 results:

  • took 1.7235369682312 seconds
  • took 2.9490959644318 seconds

PHP 5.2 results:

  • took 3.0069220066071 seconds
  • took 4.7002630233765 seconds

PHP 5.1 results:

  • took 2.6272349357605 seconds
  • took 5.0403649806976 seconds

Things start to look different with PHP 5.0 and 4.4.

5.0:

  • took 10.038941144943 seconds
  • took 7.0874409675598 seconds

4.4:

  • took 7.5352551937103 seconds
  • took 6.6245851516724 seconds

Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.

How can I introduce multiple conditions in LIKE operator?

If your parameter value is not fixed or your value can be null based on business you can try the following approach.

DECLARE @DrugClassstring VARCHAR(MAX);
SET @DrugClassstring = 'C3,C2'; -- You can pass null also

---------------------------------------------

IF @DrugClassstring IS NULL 
    SET @DrugClassstring = 'C3,C2,C4,C5,RX,OT'; -- If null you can set your all conditional case that will return for all
SELECT dn.drugclass_FK , dn.cdrugname
FROM drugname AS dn
INNER JOIN dbo.SplitString(@DrugClassstring, ',') class ON dn.drugclass_FK = class.[Name] -- SplitString is a a function

SplitString function

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER FUNCTION [dbo].[SplitString](@stringToSplit VARCHAR(MAX),
                                   @delimeter     CHAR(1)      = ',')
RETURNS @returnList TABLE([Name] [NVARCHAR](500))
AS
     BEGIN

         --It's use in report sql, before any change concern to everyone

         DECLARE @name NVARCHAR(255);
         DECLARE @pos INT;
         WHILE CHARINDEX(@delimeter, @stringToSplit) > 0
             BEGIN
                 SELECT @pos = CHARINDEX(@delimeter, @stringToSplit);
                 SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1);
                 INSERT INTO @returnList
                        SELECT @name;
                 SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos);
             END;
         INSERT INTO @returnList
                SELECT @stringToSplit;
         RETURN;
     END;

Can I underline text in an Android layout?

It can be achieved if you are using a string resource xml file, which supports HTML tags like <b></b>, <i></i> and <u></u>.

<resources>
    <string name="your_string_here">This is an <u>underline</u>.</string>
</resources>

If you want to underline something from code use:

TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);

What's the difference between a temp table and table variable in SQL Server?

There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.

As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)

Some points to consider when choosing between them:

  • Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.

  • Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) SQL 2014 has non-unique indexes too.

  • Table variables don't participate in transactions and SELECTs are implicitly with NOLOCK. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!

  • Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.

  • You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.

  • You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).

  • Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.

  • Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.

  • Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

Some further reading:

Error: No module named psycopg2.extensions

pip3 install django-psycopg2-extension

I know i am late and there's lot of answers up here which also solves the problem. But today i also faced this problem and none of this helps me. Then i found the above magical command which solves my problem :-P . so i am posting this as it might be case for you too.
Happy coding.

PG::ConnectionBad - could not connect to server: Connection refused

I got the same problem after updating my mac on Osx Movaje.

i found this solution :

Try first the bellow command line in your terminal :

brew services restart postgresql

If nothing change :

ps aux | grep postgres

If still nothing change :

ls -ls | grep post

Last command to fix it, removed the postgres lock file by executing from root :

rm /usr/local/var/postgres/postmaster.pid

and then :

brew services restart postgresql

From berziiii : https://github.com/ga-wdi-boston/capstone-project/issues/325

Hope that will help :)

Regards !!

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

SQL Server 2005 How Create a Unique Constraint?

I also found you can do this via, the database diagrams.

By right clicking the table and selecting Indexes/Keys...

Click the 'Add' button, and change the columns to the column(s) you wish make unique.

Change Is Unique to Yes.

Click close and save the diagram, and it will add it to the table.

How do I concatenate strings?

I think that concat method and + should be mentioned here as well:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

Cookies vs. sessions

Actually, session and cookies are not always separate things. Often, but not always, session uses cookies.

There are some good answers to your question in these other questions here. Since your question is specifically about saving the user's IDU (or ID), I don't think it is quite a duplicate of those other questions, but their answers should help you.

cookies vs session

Cache VS Session VS cookies?

What is the difference between a Session and a Cookie?

Why are Python lambdas useful?

I've been using Python for a few years and I've never run in to a case where I've needed lambda. Really, as the tutorial states, it's just for syntactic sugar.

How to mock location on device?

What Dr1Ku posted works. Used the code today but needed to add more locs. So here are some improvements:

Optional: Instead of using the LocationManager.GPS_PROVIDER String, you might want to define your own constat PROVIDER_NAME and use it. When registering for location updates, pick a provider via criteria instead of directly specifying it in as a string.

First: Instead of calling removeTestProvider, first check if there is a provider to be removed (to avoid IllegalArgumentException):

if (mLocationManager.getProvider(PROVIDER_NAME) != null) {
  mLocationManager.removeTestProvider(PROVIDER_NAME);
}

Second: To publish more than one location, you have to set the time for the location:

newLocation.setTime(System.currentTimeMillis());
...
mLocationManager.setTestProviderLocation(PROVIDER_NAME, newLocation);

There also seems to be a google Test that uses MockLocationProviders: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/location/LocationManagerProximityTest.java

Another good working example can be found at: http://pedroassuncao.com/blog/2009/11/12/android-location-provider-mock/

Another good article is: http://ballardhack.wordpress.com/2010/09/23/location-gps-and-automated-testing-on-android/#comment-1358 You'll also find some code that actually works for me on the emulator.

Showing the stack trace from a running Python application

You can use the hypno package, like so:

hypno <pid> "import traceback; traceback.print_stack()"

This would print a stack trace into the program's stdout.

Alternatively, if you don't want to print anything to stdout, or you don't have access to it (a daemon for example), you could use the madbg package, which is a python debugger that allows you to attach to a running python program and debug it in your current terminal. It is similar to pyrasite and pyringe, but newer, doesn't require gdb, and uses IPython for the debugger (which means colors and autocomplete).

To see the stack trace of a running program, you could run:

madbg attach <pid>

And in the debugger shell, enter: bt

Disclaimer - I wrote both packages

Finding Key associated with max Value in a Java Map

Java 8 way to get all keys with max value.

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

Also you can parallelize it by using parallelStream() instead of stream()

Given a URL to a text file, what is the simplest way to read the contents of the text file?

There's really no need to read line-by-line. You can get the whole thing like this:

import urllib
txt = urllib.urlopen(target_url).read()

How to get file extension from string in C++

I'd go with boost::filesystem::extension (std::filesystem::path::extension with C++17) but if you cannot use Boost and you just have to verify the extension, a simple solution is:

bool ends_with(const std::string &filename, const std::string &ext)
{
  return ext.length() <= filename.length() &&
         std::equal(ext.rbegin(), ext.rend(), filename.rbegin());
}

if (ends_with(filename, ".conf"))
{ /* ... */ }

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

Indent multiple lines quickly in vi

A quick way to do this using VISUAL MODE uses the same process as commenting a block of code.

This is useful if you would prefer not to change your shiftwidth or use any set directives and is flexible enough to work with TABS or SPACES or any other character.

  1. Position cursor at the beginning on the block
  2. v to switch to -- VISUAL MODE --
  3. Select the text to be indented
  4. Type : to switch to the prompt
  5. Replacing with 3 leading spaces:

    :'<,'>s/^/ /g

  6. Or replacing with leading tabs:

    :'<,'>s/^/\t/g

  7. Brief Explanation:

    '<,'> - Within the Visually Selected Range

    s/^/ /g - Insert 3 spaces at the beginning of every line within the whole range

    (or)

    s/^/\t/g - Insert Tab at the beginning of every line within the whole range

How can I extract a number from a string in JavaScript?

For a string such as #box2, this should work:

var thenum = thestring.replace(/^.*?(\d+).*/,'$1');

jsFiddle:

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144

so, I look up the column charset in every table

show create table company;

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

 ALTER TABLE company CONVERT TO CHARACTER SET utf8;

That might help you. :)

How do I get unique elements in this array?

This should work for you:

Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.

#An array of multiple data entries
@table1 = Table1.find(:all) 

#extracts **activity** for each entry in the array @table1, and returns only the ones which are unique 

@unique_activities = @table1.map{|t| t.activity}.uniq 

What does ellipsize mean in android?

An ellipsis is three periods in a row...

The TextView will use an ellipsis when it cannot expand to show all of its text. The attribute ellipsized sets the position of the three dots if it is necessary.

How to redirect back to form with input - Laravel 5

You can use any of these two:

return redirect()->back()->withInput(Input::all())->with('message', 'Some message');

Or,

return redirect('url_goes_here')->withInput(Input::all())->with('message', 'Some message');

Check if an array is empty or exists

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

if(arrayName && arrayName.length > 0){
    //do something.
}

or thanks to tsemer's comment I added a second version

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

_x000D_
_x000D_
var array1;_x000D_
var array2 = [];_x000D_
var array3 = ["one", "two", "three"];_x000D_
var array4 = null;_x000D_
_x000D_
console.log(array1);_x000D_
console.log(array2);_x000D_
console.log(array3);_x000D_
console.log(array4);_x000D_
_x000D_
if (array1 && array1.length) {_x000D_
  console.log("array1! has a value!");_x000D_
}_x000D_
_x000D_
if (array2 && array2.length) {_x000D_
  console.log("array2! has a value!");_x000D_
}_x000D_
_x000D_
if (array3 && array3.length) {_x000D_
  console.log("array3! has a value!");_x000D_
}_x000D_
_x000D_
if (array4 && array4.length) {_x000D_
  console.log("array4! has a value!");_x000D_
}
_x000D_
_x000D_
_x000D_

which also proves that if(array2 && array2.length) and if(array2 && array2.length > 0) are exactly doing the same

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

Customize UITableView header section

Swift 4.2

In Swift 4.2 the name of table is a little changed.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
        let label = UILabel(frame: CGRect(x: 10, y: 5, width: tableView.frame.size.width, height: 18))
        label.font = UIFont.systemFont(ofSize: 14)
        label.text = list.objectAtIndex(section) as! String
        view.addSubview(label)
        view.backgroundColor = UIColor.gray // Set your background color

        return view
    }

String replace a Backslash

Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").

The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.

Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

Can Windows' built-in ZIP compression be scripted?

to create a compressed archive you can use the utility MAKECAB.EXE

Is there any difference between GROUP BY and DISTINCT

In terms of usage, GROUP BY is used for grouping those rows you want to calculate. DISTINCT will not do any calculation. It will show no duplicate rows.

I always used DISTINCT if I want to present data without duplicates.

If I want to do calculations like summing up the total quantity of mangoes, I will use GROUP BY

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

ORA-01843 not a valid month- Comparing Dates

Just in case this helps, I solved this by checking the server date format:

SELECT * FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT';

then by using the following comparison (the left field is a date+time):

AND EV_DTTM >= ('01-DEC-16')

I was trying this with TO_DATE but kept getting an error. But when I matched my string with the NLS_DATE_FORMAT and removed TO_DATE, it worked...

How do I unbind "hover" in jQuery?

Unbind the mouseenter and mouseleave events individually or unbind all events on the element(s).

$(this).unbind('mouseenter').unbind('mouseleave');

or

$(this).unbind();  // assuming you have no other handlers you want to keep

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

JavaScript open in a new window, not tab

Try:

window.open("", [window name], "height=XXX,width=XXX,modal=yes,alwaysRaised=yes");

I have some code that does what your say, but there is a lot of parameters in it. I think these are the bare minimum, let me know if it doesn't work, I'll post the rest.

GridView sorting: SortDirection always Ascending

This is another way of solving the issue:

protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)
{
    List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
    items.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e);
    grdHeader.DataSource = items;
    grdHeader.DataBind();
}

private string ConvertSortDirectionToSql(GridViewSortEventArgs e)
{
    ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? "ASC";
    ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == "ASC") ? "DESC" : "ASC";
    return ViewState[e.SortExpression].ToString();
}

Space between two divs

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

How can I add a space in between two outputs?

code:

class Main
{
    public static void main(String[] args)  
    {
        int a=10, b=20;
        System.out.println(a + " " + b);
    }
}

Input: none

Output: 10 20

Increment a database field by 1

Updating an entry:

A simple increment should do the trick.

UPDATE mytable 
  SET logins = logins + 1 
  WHERE id = 12

Insert new row, or Update if already present:

If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE syntax or the INSERT...ON DUPLICATE KEY UPDATE option (As Rob Van Dam demonstrated in his answer).

Inserting a new entry:

Or perhaps you're looking for something like INSERT...MAX(logins)+1? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:

INSERT into mytable (logins) 
  SELECT max(logins) + 1 
  FROM mytable

Auto-fit TextView for Android

Since Android O, it's possible to auto resize text in xml:

https://developer.android.com/preview/features/autosizing-textview.html

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="12sp"
    app:autoSizeMaxTextSize="100sp"
    app:autoSizeStepGranularity="2sp"
  />

Android O allows you to instruct a TextView to let the text size expand or contract automatically to fill its layout based on the TextView's characteristics and boundaries. This setting makes it easier to optimize the text size on different screens with dynamic content.

The Support Library 26.0 Beta provides full support to the autosizing TextView feature on devices running Android versions prior to Android O. The library provides support to Android 4.0 (API level 14) and higher. The android.support.v4.widget package contains the TextViewCompat class to access features in a backward-compatible fashion.

Export data from Chrome developer tool

To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.

How to order citations by appearance using BibTeX?

with unsrt the problem is the format. use \bibliographystyle{ieeetr} to get refences in order of citation in document.

Gradient text color

You can achieve that effect using a combination of CSS linear-gradient and mix-blend-mode.

HTML

<p>
    Enter your message here... 
    To be or not to be, 
    that is the question...
    maybe, I think, 
    I'm not sure
    wait, you're still reading this?
    Type a good message already!
</p>

CSS

p {
    width: 300px;
    position: relative;
}

p::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, red, orange, yellow, green, blue, purple);
    mix-blend-mode: screen;
}

What this does is add a linear gradient on the paragraph's ::after pseudo-element and make it cover the whole paragraph element. But with mix-blend-mode: screen, the gradient will only show on parts where there is text.

Here's a jsfiddle to show this at work. Just modify the linear-gradient values to achieve what you want.

How do I compare strings in Java?

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

The equals() method will check whether the contents or the states of 2 objects are the same.

Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.

Definitely the use of the equals() method is recommended.

Don't worry about the performance. Some things to encourage using String.equals():

  1. Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed!
  2. If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal.
  3. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.

When all is said and done, even if we have a guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want an efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

How can I find where Python is installed on Windows?

In the sys package, you can find a lot of useful information about your installation:

import sys
print sys.executable
print sys.exec_prefix

I'm not sure what this will give on your Windows system, but on my Mac executable points to the Python binary and exec_prefix to the installation root.

You could also try this for inspecting your sys module:

import sys
for k,v in sys.__dict__.items():
    if not callable(v):
        print "%20s: %s" % (k,repr(v))

How to start anonymous thread class

You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();

... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:

Thread t = new Thread() {
    public void run() {
        System.out.println("blah");
    }
};
t.start();

How to open the terminal in Atom?

In current versions of Mac Catalina

  1. go to packages tab --> Settings View ---> Install Packages/Themes ---> +Install button --> add "platformio-ide-terminal"

  2. control ~ to get the terminal

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

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

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

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

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

mongo - couldn't connect to server 127.0.0.1:27017

Simply create a folder named "data" in C drive and inside data folder create another folder named "db". Then execute mongod.exe :)

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

How to Determine the Screen Height and Width in Flutter

You can use:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.of(context).padding;
  • double newheight = height - padding.top - padding.bottom;

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

Checking if an object is a given type in Swift

myObject as? String returns nil if myObject is not a String. Otherwise, it returns a String?, so you can access the string itself with myObject!, or cast it with myObject! as String safely.

Dynamic Height Issue for UITableView Cells (Swift)

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0

And don't forget to add botton constraints for label

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

Disable button in angular with two conditions?

In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.

Your problem started like this:

enabled  = A and B
disabled = not ( A and B )

So far so good, but you went one step further and tried to remove the braces. And that's a little tricky, because you have to replace the and/&& with an or/||.

not ( A and B ) = not(A) OR not(B)

Or in a more mathematical notation:

enter image description here

I always keep this law in mind whenever I simplify conditions or work with probabilities.

Removing duplicate rows in Notepad++

In version 7.8, you can accomplish this without any plugins - Edit -> Line Operations -> Remove Consecutive Duplicate Lines. You will have to sort the file to place duplicate lines in consecutive order before this works, but it does work like a charm.

Sorting options are available under Edit -> Line Operations -> Sort By ...

How to make a JSON call to a url?

A standard http GET request should do it. Then you can use JSON.parse() to make it into a json object.

function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}

then

var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);

that's basically it

Is there a /dev/null on Windows?

You have to use start and $NUL for this in Windows PowerShell:

Type in this command assuming mySum is the name of your application and 5 10 are command line arguments you are sending.

start .\mySum  5 10 > $NUL 2>&1

The start command will start a detached process, a similar effect to &. The /B option prevents start from opening a new terminal window if the program you are running is a console application. and NUL is Windows' equivalent of /dev/null. The 2>&1 at the end will redirect stderr to stdout, which will all go to NUL.

Why am I getting tree conflicts in Subversion?

I don't know if this is happening to you, but sometimes I choose the wrong directory to merge and I get this error even though all the files appear completely fine.

Example:

Merge /svn/Project/branches/some-branch/Sources to /svn/Project/trunk ---> Tree conflict

Merge /svn/Project/branches/some-branch to /svn/Project/trunk ---> OK

This might be a stupid mistake, but it's not always obvious because you think it's something more complicated.

Can't find file executable in your configured search path for gnc gcc compiler

Here's an easy way for Windows users.

  1. Uninstall the existing codeblocks from your system.
  2. Restart system.
  3. Go to http://www.codeblocks.org/downloads/26
  4. Download the codeblocks-16.01mingw-setup.exe file. It includes the GCC/G++ compiler and GDB debugger from TDM-GCC (version 4.9.2, 32 bit, SJLJ).

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Inline functions in C#?

The statement "its best to leave these things alone and let the compiler do the work.." (Cody Brocious) is complete rubish. I have been programming high performance game code for 20 years, and I have yet to come across a compiler that is 'smart enough' to know which code should be inlined (functions) or not. It would be useful to have a "inline" statement in c#, truth is that the compiler just doesnt have all the information it needs to determine which function should be always inlined or not without the "inline" hint. Sure if the function is small (accessor) then it might be automatically inlined, but what if it is a few lines of code? Nonesense, the compiler has no way of knowing, you cant just leave that up to the compiler for optimized code (beyond algorithims).

How to format an inline code in Confluence?

To insert inline monospace font in Confluence, surround the text in double curly-braces.

This is an {{example}}.

If you're using Confluence 4.x or higher, you can also just select the "Preformatted" option from the paragraph style menu. Please note that will apply to the entire line.

Full reference here.

How to display list items as columns?

Thank you for this example, SPRBRN. It helped me. And I can suggest the mixin, which I've used based on the code given above:

//multi-column-list( fixed columns width)
  @mixin multi-column-list($column-width, $column-rule-style) {
  -webkit-column-width: $column-width;
  -moz-column-width: $column-width;
  -o-column-width: $column-width;
  -ms-column-width: $column-width;
  column-width: $column-width;

  -webkit-column-rule-style: $column-rule-style;
  -moz-column-rule-style: $column-rule-style;
  -o-column-rule-style: $column-rule-style;
  -ms-column-rule-style: $column-rule-style;
  column-rule-style: $column-rule-style;
 }

Using:

   @include multi-column-list(250px, solid);

make an ID in a mysql table auto_increment (after the fact)

As long as you have unique integers (or some unique value) in the current PK, you could create a new table, and insert into it with IDENTITY INSERT ON. Then drop the old table, and rename the new table.

Don't forget to recreate any indexes.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

How to get week numbers from dates?

if you try with lubridate:

library(lubridate)
lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))

[1] 11 11 12  1

The pattern is the same. Try isoweek

lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))
[1] 11 12 12  1

Why maven? What are the benefits?

This should have been a comment, but it wasn't fitting in a comment length, so I posted it as an answer.

All the benefits mentioned in other answers are achievable by simpler means than using maven. If, for-example, you are new to a project, you'll anyway spend more time creating project architecture, joining components, coding than downloading jars and copying them to lib folder. If you are experienced in your domain, then you already know how to start off the project with what libraries. I don't see any benefit of using maven, especially when it poses a lot of problems while automatically doing the "dependency management".

I only have intermediate level knowledge of maven, but I tell you, I have done large projects(like ERPs) without using maven.

"Proxy server connection failed" in google chrome

Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.

Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en

Android get image path from drawable as string

These all are ways:

String imageUri = "drawable://" + R.drawable.image;

Other ways I tested

Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");

String path = path.toString();
String path = otherPath .toString();

How to run .jar file by double click on Windows 7 64-bit?

This is my way:

  1. Create file bat (example openJar.bat).

    @echo off
    start javaw -jar "%1" %*
    exit
    
  2. Cut it and paste to C:\Program Files\Java\\bin (this step is unnecessary, but you should it).

  3. Right click jar file > Properties > Choose open with (Change button ) and select your file bat.
  4. Double click your jar file to test it.

Two Decimal places using c#

Your question is asking to display two decimal places. Using the following String.format will help:

String.Format("{0:.##}", Debitvalue)

this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue)

Cannot find Microsoft.Office.Interop Visual Studio

If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

How to log request and response body with Retrofit-Android?

If you are using Retrofit2 and okhttp3 then you need to know that Interceptor works by queue. So add loggingInterceptor at the end, after your other Interceptors:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG)
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

 new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new CatalogInterceptor(context))
                .addInterceptor(new OAuthInterceptor(context))
                .authenticator(new BearerTokenAuthenticator(context))
                .addInterceptor(loggingInterceptor)//at the end
                .build();

How to find if div with specific id exists in jQuery?

Try to check the length of the selector, if it returns you something then the element must exists else not.

if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

Use the first if condition for id and the 2nd one for class.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

(This works at least up to version 1.52.0, 10 Dec 2020)


On macOS Visual Studio Code version 1.36.1 (2019)

Visual Studio Code version 1.36.1 (2019)

To auto-format the selection, use ?K ?F (the trick is that this is to be done in sequence, ?K first, followed by ?F).

Auto-format selection or document

To just indent (shift right) without auto-formatting, use ?]

Indent options

As in Keyboard Shortcuts (?K ?S, or from the menu as shown below)

Keyboard shortcuts

How can I have linebreaks in my long LaTeX equations?

To solve this issue, I used the array environment inside the equation environment like this:

\begin{equation}
    \begin{array}{r c l}
       first Term&=&Second Term\\
                 &=&Third Term
    \end{array}
\end{equation}

Multiple try codes in one block

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

Transparent background on winforms?

What works for me is using a specific color instead of the real ability of .png to represent transparency.

So, what you can do is take your background image, and paint the transparent area with a specific color (Magenta always seemed appropriate to me...).

Set the image as the Form's BackgrounImage property, and set the color as the Form's TransparencyKey. No need for changes in the Control's style, and no need for BackColor.

I've tryed it right now and it worked for me...

Forward X11 failed: Network error: Connection refused

I had the same problem, but it's solved now. Finally, Putty does work with Cigwin-X, and Xming is not an obligatory app for MS-Windows X-server.

Nowadays it's xlaunch, who controls the run of X-window. Certainly, xlaunch.exe must be installed in Cigwin. When run in interactive mode it asks for "extra settings". You should add "-listen tcp" to additional param field, since Cigwin-X does not listen TCP by default.

In order to not repeat these steps, you may save settings to the file. And run xlaunch.exe via its shortcut with modified CLI inside. Something like

C:\cygwin64\bin\xlaunch.exe -run C:\cygwin64\config.xlaunch

How to remove an HTML element using Javascript?

This works. Just remove the button from the "dummy" div if you want to keep the button.

_x000D_
_x000D_
function removeDummy() {_x000D_
  var elem = document.getElementById('dummy');_x000D_
  elem.parentNode.removeChild(elem);_x000D_
  return false;_x000D_
}
_x000D_
#dummy {_x000D_
  min-width: 200px;_x000D_
  min-height: 200px;_x000D_
  max-width: 200px;_x000D_
  max-height: 200px;_x000D_
  background-color: #fff000;_x000D_
}
_x000D_
<div id="dummy">_x000D_
  <button onclick="removeDummy()">Remove</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

Get domain name from given url

try this one : java.net.URL;
JOptionPane.showMessageDialog(null, getDomainName(new URL("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")));

public String getDomainName(URL url){
String strDomain;
String[] strhost = url.getHost().split(Pattern.quote("."));
String[] strTLD = {"com","org","net","int","edu","gov","mil","arpa"};

if(Arrays.asList(strTLD).indexOf(strhost[strhost.length-1])>=0)
    strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else if(strhost.length>2)
    strDomain = strhost[strhost.length-3]+"."+strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else
    strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
return strDomain;}

How to make CSS3 rounded corners hide overflow in Chrome/Opera

As for me none of the solutions worked well, only using:

-webkit-mask-image: -webkit-radial-gradient(circle, white, black);

on the wrapper element did the job.

Here the example: http://jsfiddle.net/gpawlik/qWdf6/74/

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

How do I select elements of an array given condition?

For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

HTTP Status 404 - The requested resource (/) is not available

For me, my Eclipse installation was hosed - I think because I'd installed struts. After trying a dozen remedies for this error, I re-installed Eclipse, made a new workspace and it was OK. Using Kepler-64-Windows, Tomcat 7, Windows 7.

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

how to set background image in submit button?

Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.

A tutorial on the subject.

HTTP Request in Kotlin

Maybe the simplest GET

For everybody stuck with NetworkOnMainThreadException for the other solutions: use AsyncTask or, even shorter, (yet still experimental) Coroutines:

launch {

    val jsonStr = URL("url").readText()

}

If you need to test with plain http don't forget to add to your manifest: android:usesCleartextTraffic="true"


For the experimental Coroutines you have to add to build.gradle as of 10/10/2018:

kotlin {
    experimental {
        coroutines 'enable'
    }
}
dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.24.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.24.0"
    ...

How to make a script wait for a pressed key?

The python manual provides the following:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

which can be rolled into your use case.

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

Convert the values in a column into row names in an existing data frame

This should do:

samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]

So in short, no there is no alternative to reassigning.

Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:

R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
   b c
a  1 A
b  2 B
c  3 C
d  4 D
e  5 E
f  6 F
g  7 G
h  8 H
i  9 I
j 10 J
R> 

How to clear the cache in NetBeans

Close NetBeans before deleting the cache.

NetBeans 7.2+, Windows 7

Cache is located in C:\Users\<username>\AppData\Local\NetBeans\Cache\.

Clear the cache using the %USERPROFILE% Windows variable:

del /s /q %USERPROFILE%\AppData\Local\NetBeans\Cache\

If it is set, you can also use the environment variable %LOCALAPPDATA%:

del /s /q %LOCALAPPDATA%\NetBeans\Cache\

NetBeans 7.2+, Linux

Cache is at: ~/.cache/netbeans/${netbeans_version}/index/

Mac OS X

Cache is at: ~/Library/Caches/NetBeans/${netbeans_version}/

See also http://wiki.netbeans.org/FaqWhatIsUserdir.

Help Menu

On Windows, selecting the Help » About menu will display a dialog that contains the following text:

Product Version: NetBeans IDE 8.0.2 (Build 201411181905)
Java: 1.7.0_80; Java HotSpot(TM) 64-Bit Server VM 24.80-b11
Runtime: Java(TM) SE Runtime Environment 1.7.0_80-b15
System: Windows 7 version 6.1 running on amd64; Cp1252; en_CA (nb)
User directory: C:\Users\Username\AppData\Roaming\NetBeans\8.0.2
Cache directory: C:\Users\Username\AppData\Local\NetBeans\Cache\8.0.2

Regardless of operating system, the About dialog will contain the correct path to the cache directory.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

You need to make sure all of your assemblies are compiling for the correct architecture. Try changing the architecture for x86 if reinstalling the COM component doesn't work.

How to get the process ID to kill a nohup process?

You could try

kill -9 `pgrep [command name]`

TSQL: How to convert local time to UTC? (SQL Server 2008)

SQL Server 2008 has a type called datetimeoffset. It's really useful for this type of stuff.

http://msdn.microsoft.com/en-us/library/bb630289.aspx

Then you can use the function SWITCHOFFSET to move it from one timezone to another, but still keeping the same UTC value.

http://msdn.microsoft.com/en-us/library/bb677244.aspx

Rob

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

How to set background color of HTML element using css properties in JavaScript

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

How to change collation of database, table, column?

I used the following shell script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).

#!/bin/bash

# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
CHARSET="$2"
COLL="$3"

[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql

echo "USE $DB; SHOW TABLES;" | mysql -s | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
    done
)

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.

IDENTITY_INSERT is set to OFF - How to turn it ON?

Should you instead be setting the identity insert to on within the stored procedure? It looks like you're setting it to on only when changing the stored procedure, not when actually calling it. Try:

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 

SET IDENTITY_INSERT tbl_content ON

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

What is a JavaBean exactly?

To understand JavaBean you need to notice the following:

JavaBean is conceptual stuff and can not represent a class of specific things

JavaBean is a development tool can be visualized in the operation of reusable software components

JavaBean is based on the Sun JavaBeans specification and can be reusable components. Its biggest feature is the re-usability.

Convert RGBA PNG to RGB with PIL

import Image

def fig2img ( fig ): """ @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image """ # put the figure pixmap into a numpy array buf = fig2data ( fig ) w, h, d = buf.shape return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )

def fig2data ( fig ): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw ( )

# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )

# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf

def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True): if not is_already_saved: background = Image.new("RGB", img.size, c) background.paste(img, mask=img.split()[3]) # 3 is the alpha channel

    background.save(path, 'JPEG', quality=100)   
    is_already_saved = True
if if_load:
    if is_already_saved:
        im = Image.open(path)
        return np.array(im)
    else:
        raise ValueError('No image to load.')

SQL: Alias Column Name for Use in CASE Statement

I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

With localView1 as (
 select c1,
        c2,
        c3,
        c4,
        ((c2-c4)*(3))+c1 as "complex"
   from realTable1) 
   , localView2 as (
 select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
        complex * complex as formula2    
   from localView1)
select *
from localView2

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

if you think you followed everything good but still unlucky, just make sure you/capistrano run touch tmp/restart.txt or equivalent at the end. I was in the unlucky list but now :)

When would you use the different git merge strategies?

With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").

git merge -s ort

This comes from this thread from Elijah Newren:

For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).

But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch $GIT_WORK_TREE or $GIT_INDEX_FILE will allow for some fun new features.
That's the hope anyway.

Problem:

In the ideal world, we should:

  • ask unpack_trees() to do "read-tree -m" without "-u";

  • do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;

  • compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
    E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
    And then finally

  • carry out the working tree update to make it match what the resulting in-core index says it should look like.

Result:

See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit a1f9595, 18 Nov 2020)

merge-ort: barebones API of new merge strategy with empty implementation

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for merge-recursive.c.

However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)

The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.

Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.

And:

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

The "recursive" backend relies on unpack_trees() to check if unstaged changes would be overwritten by a merge, but unpack_trees() does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.

The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the :FILENAME piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).

However, there were cases where the :FILENAME annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.

t6404, t6423: expect improved rename/delete handling in ort backend

Signed-off-by: Elijah Newren

When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.

Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually 'git rm '(man) the old version as well as 'git add'(man) the new one).

rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive" or "ort" merge strategies are in use.


With Git 2.30 (Q1 2021), Preparation for a new merge strategy.

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

merge tests: expect improved directory/file conflict handling in ort

Signed-off-by: Elijah Newren

merge-recursive.c is built on the idea of running unpack_trees() and then "doing minor touch-ups" to get the result.
Unfortunately, unpack_trees() was run in an update-as-it-goes mode, leading merge-recursive.c to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.

Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.

And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a 'git merge --abort'(man) or 'git rebase --abort'(man).

It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changing merge-recursive.c to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.

I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).


With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:

See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit f9d29da, 06 Jan 2021)

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

After checkout(), the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.

We do this by looping over the conflicted entries, marking the existing index entry for the path with CE_REMOVE, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the CE_REMOVED-marked cache entries and sorting the index.


With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.

See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 2856089, 25 Jan 2021)

Example:

merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

Implement handling of normal renames.
This code replaces the following from merge-recurisve.c:

  • the code relevant to RENAME_NORMAL in process_renames()
  • the RENAME_NORMAL case of process_entry()

Also, there is some shared code from merge-recursive.c for multiple different rename cases which we will no longer need for this case (or other rename cases):

  • handle_rename_normal()
  • setup_rename_conflict_info()

The consolidation of four separate codepaths into one is made possible by a change in design: process_renames() tweaks the conflict_info entries within opt->priv->paths such that process_entry() can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.

This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).

That, together with letting worktree/index updating be handled orthogonally in the merge_switch_to_result() function, dramatically simplifies the code for various special rename cases.

(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)

And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.

See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit b65b9ff, 05 Feb 2021)

merge-ort: add handling for different types of files at same path

Signed-off-by: Elijah Newren

Add some handling that explicitly considers collisions of the following types:

  • file/submodule
  • file/symlink
  • submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.

Note that in the case of recursive handling (i.e.
call_depth > 0), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.

Application Installation Failed in Android Studio

If you use MIUI ROM

Go to the developer option and in that disable MIUI optimization.You will be asked to reboot your phone. Reboot it and then run the app.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

Same issue as in Error in launching AVD:

1) Install the Intel x86 Emulator Accelerator (HAXM installer) from the Android SDK Manager;

enter image description here

2) Run (for Windows):

{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe

or (for OSX):

{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\IntelHAXM_1.1.1_for_10_9_and_above.dmg

3) Start the emulator.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

How do you reverse a string in place in C or C++?

#include <cstdio>
#include <cstdlib>
#include <string>

void strrev(char *str)
{
        if( str == NULL )
                return;

        char *end_ptr = &str[strlen(str) - 1];
        char temp;
        while( end_ptr > str )
        {
                temp = *str;
                *str++ = *end_ptr;
                *end_ptr-- = temp;
        }
}

int main(int argc, char *argv[])
{
        char buffer[32];

        strcpy(buffer, "testing");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "a");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "abc");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "");
        strrev(buffer);
        printf("%s\n", buffer);

        strrev(NULL);

        return 0;
}

This code produces this output:

gnitset
a
cba

Argument Exception "Item with Same Key has already been added"

To illustrate the problem you are having, let's look at some code...

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("Key1", "Value1");  // Works fine
test.Add("Key2", "Value2");  // Works fine
test.Add("Key1", "Value3");  // Fails because of duplicate key

The reason that a dictionary has a key/value pair is a feature so you can do this...

var myString = test["Key2"];  // myString is now Value2.

If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.

Remove special symbols and extra spaces and replace with underscore using the replace method

Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

Conditional WHERE clause in SQL Server

Try this

SELECT 
    DateAppr,
    TimeAppr,
    TAT,
    LaserLTR,
    Permit,
    LtrPrinter,
    JobName,
    JobNumber,
    JobDesc,
    ActQty,
    (ActQty-LtrPrinted) AS L,
    (ActQty-QtyInserted) AS M,
    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM 
    [test].[dbo].[MM]
WHERE 
    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    OR 
    (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

You can read more about conditional WHERE here.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

error while loading shared libraries: libncurses.so.5:

To install ncurses-compat-libs on Fedora 24 helped me on this issue (unable to start adb error while loading shared libraries: libncurses.so.5)

Postgresql query between date ranges

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

How to load npm modules in AWS Lambda?

Hope this helps, with Serverless framework you can do something like this:

  1. Add these things in your serverless.yml file:

plugins: - serverless-webpack custom: webpackIncludeModules: forceInclude: - <your package name> (for example: node-fetch) 2. Then create your Lambda function, deploy it by serverless deploy, the package that included in serverless.yml will be there for you.

For more information about serverless: https://serverless.com/framework/docs/providers/aws/guide/quick-start/

Creating a copy of a database in PostgreSQL

Try this:

CREATE DATABASE newdb WITH ENCODING='UTF8' OWNER=owner TEMPLATE=templatedb LC_COLLATE='en_US.UTF-8' LC_CTYPE='en_US.UTF-8' CONNECTION LIMIT=-1;

gl XD

Angular - ng: command not found

It may has not helped OP, but it solved my problem. This answer is to help others who have not tried the command mentioned in OP's question.

Just use npm install -g @angular/cli@latest. It did the trick for me.

What does @media screen and (max-width: 1024px) mean in CSS?

It's limiting the styles defined there to the screen (e.g. not print or some other media) and is further limiting the scope to viewports which are 1024px or less in width.

http://www.css3.info/preview/media-queries/

How to extract text from a PDF?

For image extraction, pdfimages is a free command line tool for Linux or Windows (win32):

pdfimages: Extract and Save Images From A Portable Document Format ( PDF ) File

CSS flexbox not working in IE10

IE10 has uses the old syntax. So:

display: -ms-flexbox; /* will work on IE10 */
display: flex; /* is new syntax, will not work on IE10 */

see css-tricks.com/snippets/css/a-guide-to-flexbox:

(tweener) means an odd unofficial syntax from [2012] (e.g. display: flexbox;)

How to use "Share image using" sharing Intent to share images in android?

First add permission

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

using Bitmap from resources

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri =  Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));

Tested via bluetooth and other messengers

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

How do I check if a string contains a specific word?

Look at strpos():

<?php
    $mystring = 'abc';
    $findme   = 'a';
    $pos = strpos($mystring, $findme);

    // Note our use of ===. Simply, == would not work as expected
    // because the position of 'a' was the 0th (first) character.
    if ($pos === false) {
        echo "The string '$findme' was not found in the string '$mystring'.";
    }
    else {
        echo "The string '$findme' was found in the string '$mystring',";
        echo " and exists at position $pos.";
    }
?>

What are the differences between normal and slim package of jquery?

At this time, the most authoritative answer appears to be in this issue, which states "it is a custom build of jQuery that excludes effects, ajax, and deprecated code." Details will be announced with jQuery 3.0.

I suspect that the rationale for excluding these components of the jQuery library is in recognition of the increasingly common scenario of jQuery being used in conjunction with another JS framework like Angular or React. In these cases, the usage of jQuery is primarily for DOM traversal and manipulation, so leaving out those components that are either obsolete or are provided by the framework gains about a 20% reduction in file size.

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

Count number of objects in list

Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10)
> length (mylist)
[1] 1

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]])
[1] 10

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df)
[1] 30
> nrow (df)
[1] 2

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df)
[1] 30
> length (df[[1]])
[1] 2