Programs & Examples On #Html to jpeg

Android Activity without ActionBar

You may also change inheritance from ActionBarActivity to Activity as written here.

UPDATE

A good solution is here:

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
}

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Why Would I Ever Need to Use C# Nested Classes

There are times when it's useful to implement an interface that will be returned from within the class, but the implementation of that interface should be completely hidden from the outside world.

As an example - prior to the addition of yield to C#, one way to implement enumerators was to put the implementation of the enumerator as a private class within a collection. This would provide easy access to the members of the collection, but the outside world would not need/see the details of how this is implemented.

What is the C# Using block and why should I use it?

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

How do I get the serial key for Visual Studio Express?

I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.

Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".

Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.

how to check the version of jar file?

For Linux, try following:

find . -name "YOUR_JAR_FILE.jar" -exec zipgrep "Implementation-Version:" '{}' \;|awk -F ': ' '{print $2}'

AND/OR in Python?

or is not exclusive (e.g. xor) so or is the same thing as and/or.

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

Why is document.body null in my javascript?

The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head section that uses body. Not cool.

You want to wrap this code in a window.onload handler or place it after the <body> tag (as mentioned by e-bacho 2.0).

<head>
    <title>Javascript Tests</title>

    <script type="text/javascript">
      window.onload = function() {
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");
      }

    </script>
</head>

See demo.

Get the index of a certain value in an array in PHP

$find="Topsite";
$list=array("Tope","Ajayi","Topsite","Infotech");
$list_count=count($list);
sort($list);
for($i=0;$i<$list_count;$i++)
{
    if($list[$i]==$find){
         $position=$i;
    }

}
echo $position;

django - get() returned more than one topic

To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

def updateUserCollection(request):
    data = json.loads(request.body)
    card_id = data['card_id']
    action = data['action']

    user = request.user
    card = Cards.objects.get(card_id=card_id)

    if data-action == 'add':
        collection = Collection.objects.get_or_create(user=user, card=card)
        collection.quantity + 1
        collection.save()

    elif data-action == 'remove':
        collection = Cards.objects.filter(user=user, card=card)
        collection.quantity = 0
        collection.update()

Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

How can I declare a global variable in Angular 2 / Typescript?

I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.

First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}

export let globalVariables: Object = {
 version: '1.3.3.7',
 author: '0x1ad2',
 everything: 42
};

After that import it

import {globalVariables} from "path/to/your/globals.ts"

And use it

console.log(globalVariables);

Which passwordchar shows a black dot (•) in a winforms textbox?

Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:

this.txtPassword.UseSystemPasswordChar = true;

Javascript - removing undefined fields from an object

Mhh.. I think @Damian asks for remove undefined field (property) from an JS object. Then, I would simply do :

for (const i in myObj)  
   if (typeof myObj[i] === 'undefined')   
     delete myObj[i]; 

Short and efficient solution, in (vanilla) JS ! Example :

_x000D_
_x000D_
const myObj = {_x000D_
  a: 1,_x000D_
  b: undefined,_x000D_
  c: null, _x000D_
  d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj)  _x000D_
  if (typeof myObj[i] === 'undefined')   _x000D_
    delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
_x000D_
_x000D_

How to select count with Laravel's fluent query builder?

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();

Why are C++ inline functions in the header?

The c++ inline keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline to be a real function that is called instead of getting code inlined at the point where it's called.

Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar() function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar() must be visible.

Deserialize JSON into C# dynamic object?

I made a new version of the DynamicJsonConverter that uses Expando Objects. I used expando objects, because I wanted to Serialize the dynamic back into JSON using Json.NET.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Web.Script.Serialization;

public static class DynamicJson
{
    public static dynamic Parse(string json)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

        dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic;
        return glossaryEntry;
    }

    class DynamicJsonConverter : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            var result = ToExpando(dictionary);

            return type == typeof(object) ? result : null;
        }

        private static ExpandoObject ToExpando(IDictionary<string, object> dictionary)
        {
            var result = new ExpandoObject();
            var dic = result as IDictionary<String, object>;

            foreach (var item in dictionary)
            {
                var valueAsDic = item.Value as IDictionary<string, object>;
                if (valueAsDic != null)
                {
                    dic.Add(item.Key, ToExpando(valueAsDic));
                    continue;
                }
                var arrayList = item.Value as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    dic.Add(item.Key, ToExpando(arrayList));
                    continue;
                }

                dic.Add(item.Key, item.Value);
            }
            return result;
        }

        private static ArrayList ToExpando(ArrayList obj)
        {
            ArrayList result = new ArrayList();

            foreach (var item in obj)
            {
                var valueAsDic = item as IDictionary<string, object>;
                if (valueAsDic != null)
                {
                    result.Add(ToExpando(valueAsDic));
                    continue;
                }

                var arrayList = item as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    result.Add(ToExpando(arrayList));
                    continue;
                }

                result.Add(item);
            }
            return result;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
        }
    }
}

Android: Rotate image in imageview by an angle

For Kotlin,

mImageView.rotation = 90f //angle in float

This will rotate the imageView rather than rotating the image

Also, though its a method in View class. So you can pretty much rotate any view using it.

What is the difference between the dot (.) operator and -> in C++?

foo->bar() is the same as (*foo).bar().

The parenthesizes above are necessary because of the binding strength of the * and . operators.

*foo.bar() wouldn't work because Dot (.) operator is evaluated first (see operator precedence)

The Dot (.) operator can't be overloaded, arrow (->) operator can be overloaded.

The Dot (.) operator can't be applied to pointers.

Also see: What is the arrow operator (->) synonym for in C++?

Combine or merge JSON on node.js without jQuery

If you need special behaviors like nested object extension or array replacement you can use Node.js's extendify.

var extendify = require('extendify');

_.extend = extendify({
    inPlace: false,
    arrays : 'replace',
    isDeep: true
});

obj1 = {
    a:{
        arr: [1,2]
    },
    b: 4
};

obj2 = {
    a:{
        arr: [3]
    }
};

res = _.extend(obj1,obj2);
console.log(JSON.stringify(res)); //{'a':{'arr':[3]},'b':4}

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

Jquery submit form

Try this :

$('#form1').submit();

or

document.form1.submit();

To get total number of columns in a table in sql

This query gets the columns name

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

And this one gets the count

SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

How to convert object to Dictionary<TKey, TValue> in C#?

This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):

    private static Dictionary<TKey, TValue> ObjectToDictionary<TKey, TValue>(object source)
    {
        Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();

        TKey[] keys = { };
        TValue[] values = { };

        bool outLoopingKeys = false, outLoopingValues = false;

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
        {
            object value = property.GetValue(source);
            if (value is Dictionary<TKey, TValue>.KeyCollection)
            {
                keys = ((Dictionary<TKey, TValue>.KeyCollection)value).ToArray();
                outLoopingKeys = true;
            }
            if (value is Dictionary<TKey, TValue>.ValueCollection)
            {
                values = ((Dictionary<TKey, TValue>.ValueCollection)value).ToArray();
                outLoopingValues = true;
            }
            if(outLoopingKeys & outLoopingValues)
            {
                break;
            }
        }

        for (int i = 0; i < keys.Length; i++)
        {
            result.Add(keys[i], values[i]);
        }

        return result;
    }

Docker: How to delete all local Docker images

To simple clear everything do:

$ docker system prune --all

Everything means:

  • all stopped containers
  • all networks not used by at least one container
  • all images without at least one container associated to them
  • all build cache

anaconda - graphviz - can't import after installation

Remeber! If you are using jupyter notebook, please restart it after the installing. That's work for me.

Because the condition before is a static variate as below:

enter image description here

enter image description here

enter image description here

Bootstrap modal z-index

ok, so if you are using bootstrap-rtl.css, what you can do is go to the following class .modal-backdrop and remove the z-index attribute. after that all should be fine

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Is it better to use path() or url() in urls.py for django 2.0?

From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows

from django.contrib import admin
from django.urls import path

from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^posts/$', post_home, name='post_home'),

]

where posts is an application & post_home is a function in views.py

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

You can just turn on Github Pages. ^_^

Click on "Settings", than go to "GitHub Pages" and click on dropdown under "Source" and choose branch which you want to public (where main html file is located) aaaand vualaa. ^_^

Unable to find valid certification path to requested target - error even after cert imported

Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.

Short of truss-ing - I'd try:

java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...

to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.

Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.

all            turn on all debugging
ssl            turn on ssl debugging

The   following can be used with ssl:
    record       enable per-record tracing
    handshake    print each handshake message
    keygen       print key generation data
    session      print session activity
    defaultctx   print default SSL initialization
    sslctx       print SSLContext tracing
    sessioncache print session cache tracing
    keymanager   print key manager tracing
    trustmanager print trust manager tracing
    pluggability print pluggability tracing

    handshake debugging can be widened with:
    data         hex dump of each handshake message
    verbose      verbose handshake message printing

    record debugging can be widened with:
    plaintext    hex dump of record plaintext
    packet       print raw SSL/TLS packets

Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug

Why I've got no crontab entry on OS X when using vim?

As the previous posts didn't work for me because of some permissions issues, I found that creating a separate crontab file and adding it to the user's crontab with the -u parameter while root worked for me.

sudo crontab -u {USERNAME} ~/{PATH_TO_CRONTAB_FILE}

How do I translate an ISO 8601 datetime string into a Python datetime object?

Both ways:

Epoch to ISO time:

isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))

ISO time to Epoch:

epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Show whitespace characters in Visual Studio Code

The option to make whitespace visible now appears as an option on the View menu, as "Toggle Render Whitespace" in version 1.15.1 of Visual Studio Code.

jQuery .get error response function?

You can chain .fail() callback for error response.

$.get('http://example.com/page/2/', function(data){ 
   $(data).find('#reviews .card').appendTo('#reviews');
})
.fail(function() {
  //Error logic
})

How can I turn a DataTable to a CSV?

The following shorter version opens fine in Excel, maybe your issue was the trailing comma

.net = 3.5

StringBuilder sb = new StringBuilder(); 

string[] columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());

.net >= 4.0

And as Tim pointed out, if you are on .net>=4, you can make it even shorter:

StringBuilder sb = new StringBuilder(); 

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());

As suggested by Christian, if you want to handle special characters escaping in fields, replace the loop block by:

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => 
      string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
    sb.AppendLine(string.Join(",", fields));
}

And last suggestion, you could write the csv content line by line instead of as a whole document, to avoid having a big document in memory.

How to call javascript from a href?

another way is :

<a href="javascript:void(0);" onclick="alert('testing')">

How do I format a String in an email so Outlook will print the line breaks?

RESOLVED IN MY APPLICATION

In my application, I was trying to send an email whose message body was typed by the user in text area. When mail was send, outlook automatically removed line break entered by user.

e.g if user entered
Yadav
Mahesh

outlook displayed it as
YadavMahesh

Resolution: I changed the line break character "\r\n" with "\par " ( remember to hit space at the end of RTF code "\par" )and line breaks are restrored.

Cheers,
Mahesh

How do I edit $PATH (.bash_profile) on OSX?

In Macbook, step by step:

  1. First of all open terminal and write it: cd ~/
  2. Create your bash file: touch .bash_profile

You created your ".bash_profile" file but if you would like to edit it, you should write it;

  1. Edit your bash profile: open -e .bash_profile

After you can save from top-left corner of screen: File > Save

@canerkaseler

Using .htaccess to make all .html pages to run as .php files?

You need to add the following line into your Apache config file:

AddType application/x-httpd-php .htm .html

You also need two other things:

  1. Allow Overridding

    In your_site.conf file (e.g. under /etc/apache2/mods-available in my case), add the following lines:

    <Directory "<path_to_your_html_dir(in my case: /var/www/html)>">
        AllowOverride All
    </Directory>
    
  2. Enable Rewrite Mod

    Run this command on your machine:

    sudo a2enmod rewrite 
    

    After any of those steps, you should restart apache:

    sudo service apache2 restart
    

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

How can I update a single row in a ListView?

This is how I did it:

Your items (rows) must have unique ids so you can update them later. Set the tag of every view when the list is getting the view from adapter. (You can also use key tag if the default tag is used somewhere else)

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View view = super.getView(position, convertView, parent);
    view.setTag(getItemId(position));
    return view;
}

For the update check every element of list, if a view with given id is there it's visible so we perform the update.

private void update(long id)
{

    int c = list.getChildCount();
    for (int i = 0; i < c; i++)
    {
        View view = list.getChildAt(i);
        if ((Long)view.getTag() == id)
        {
            // update view
        }
    }
}

It's actually easier than other methods and better when you dealing with ids not positions! Also you must call update for items which get visible.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

This is probably a more "correct" way of getting it.

Share application "link" in Android

I know this question has been answered, but I would like to share an alternate solution:

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareSubText = "WhatsApp - The Great Chat App";
String shareBodyText = "https://play.google.com/store/apps/details?id=com.whatsapp&hl=en";
shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubText);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(shareIntent, "Share With"));

Convert datetime to Unix timestamp and convert it back in python

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0

How to force Eclipse to ask for default workspace?

Go to Window -- Preferances - General -- Startup and Shutdown -Workspaces

Check box for Prompt for workspace on startup is there . Select it.

Then at start up eclipse will ask for workspace selection.

---- EDIT ----

On OSX the Eclipse(Juno) menu bar path is:

Eclipse - Preferences

In the preferences dialog box, I selected the tree node:

 General - Startup and Shutdown - Workspaces

From that panel, there was a check box labeled

**Prompt for workspace on startup** 

I checked it, then shut down eclipse and restarted it. It prompted me for a new workspace location.

How to install and use "make" in Windows?

Download make.exe from their official site GnuWin32

  • In the Download session, click Complete package, except sources.

  • Follow the installation instructions.

  • Once finished, add the <installation directory>/bin/ to the PATH variable.

Now you will be able to use make in cmd.

how to implement Pagination in reactJs

I recently created this Pagination component that implements paging logic like Google's search results:

import React, { PropTypes } from 'react';
 
const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number   
}
 
const defaultProps = {
    initialPage: 1
}
 
class Pagination extends React.Component {
    constructor(props) {
        super(props);
        this.state = { pager: {} };
    }
 
    componentWillMount() {
        this.setPage(this.props.initialPage);
    }
 
    setPage(page) {
        var items = this.props.items;
        var pager = this.state.pager;
 
        if (page < 1 || page > pager.totalPages) {
            return;
        }
 
        // get new pager object for specified page
        pager = this.getPager(items.length, page);
 
        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
 
        // update state
        this.setState({ pager: pager });
 
        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }
 
    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;
 
        // default page size is 10
        pageSize = pageSize || 10;
 
        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);
 
        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }
 
        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
 
        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);
 
        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
 
    render() {
        var pager = this.state.pager;
 
        return (
            <ul className="pagination">
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(1)}>First</a>
                </li>
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
                </li>
                {pager.pages.map((page, index) =>
                    <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                        <a onClick={() => this.setPage(page)}>{page}</a>
                    </li>
                )}
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
                </li>
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.totalPages)}>Last</a>
                </li>
            </ul>
        );
    }
}
 
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;

And here's an example App component that uses the Pagination component to paginate a list of 150 example items:

import React from 'react';
import Pagination from './Pagination';
 
class App extends React.Component {
    constructor() {
        super();
 
        // an example array of items to be paged
        var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
 
        this.state = {
            exampleItems: exampleItems,
            pageOfItems: []
        };
 
        // bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
        this.onChangePage = this.onChangePage.bind(this);
    }
 
    onChangePage(pageOfItems) {
        // update state with new page of items
        this.setState({ pageOfItems: pageOfItems });
    }
 
    render() {
        return (
            <div>
                <div className="container">
                    <div className="text-center">
                        <h1>React - Pagination Example with logic like Google</h1>
                        {this.state.pageOfItems.map(item =>
                            <div key={item.id}>{item.name}</div>
                        )}
                        <Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
                    </div>
                </div>
                <hr />
                <div className="credits text-center">
                    <p>
                        <a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
                    </p>
                </div>
            </div>
        );
    }
}
 
export default App;

For more details and a live demo you can check out this post

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

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

I'm the one who donated the Ant export filter to Eclipse. I added the auto export feature, but only to my personal plug-in eclipse2ant, which I still maintain to coordinate bug fixes.

Unfortunately I have no time to merge it to the official Eclipse builds.

How to prepend a string to a column value in MySQL?

UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...]

programmatically add column & rows to WPF Datagrid

try this , it works 100 % : add columns and rows programatically : you need to create item class at first :

public class Item
        {
            public int Num { get; set; }
            public string Start { get; set; }
            public string Finich { get; set; }
        }

        private void generate_columns()
        {
            DataGridTextColumn c1 = new DataGridTextColumn();
            c1.Header = "Num";
            c1.Binding = new Binding("Num");
            c1.Width = 110;
            dataGrid1.Columns.Add(c1);
            DataGridTextColumn c2 = new DataGridTextColumn();
            c2.Header = "Start";
            c2.Width = 110;
            c2.Binding = new Binding("Start");
            dataGrid1.Columns.Add(c2);
            DataGridTextColumn c3 = new DataGridTextColumn();
            c3.Header = "Finich";
            c3.Width = 110;
            c3.Binding = new Binding("Finich");
            dataGrid1.Columns.Add(c3);

            dataGrid1.Items.Add(new Item() { Num = 1, Start = "2012, 8, 15", Finich = "2012, 9, 15" });
            dataGrid1.Items.Add(new Item() { Num = 2, Start = "2012, 12, 15", Finich = "2013, 2, 1" });
            dataGrid1.Items.Add(new Item() { Num = 3, Start = "2012, 8, 1", Finich = "2012, 11, 15" });

        }

How to get element by classname or id

If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');
});

Hope this helps. :)

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

converting Java bitmap to byte array

Here is bitmap extension .convertToByteArray wrote in Kotlin.

/**
 * Convert bitmap to byte array using ByteBuffer.
 */
fun Bitmap.convertToByteArray(): ByteArray {
    //minimum number of bytes that can be used to store this bitmap's pixels
    val size = this.byteCount

    //allocate new instances which will hold bitmap
    val buffer = ByteBuffer.allocate(size)
    val bytes = ByteArray(size)

    //copy the bitmap's pixels into the specified buffer
    this.copyPixelsToBuffer(buffer)

    //rewinds buffer (buffer position is set to zero and the mark is discarded)
    buffer.rewind()

    //transfer bytes from buffer into the given destination array
    buffer.get(bytes)

    //return bitmap's pixels
    return bytes
}

DataRow: Select cell value by a given column name

On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

public T GetColumnValue<T>(DataRow row, string columnName)
  {
        T value = default(T);
        if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
        {
            value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
        }

        return value;
  }

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Generating locales

Missing locales are generated with locale-gen:

locale-gen en_US.UTF-8

Alternatively a locale file can be created manually with localedef:[1]

localedef -i en_US -f UTF-8 en_US.UTF-8

Setting Locale Settings

The locale settings can be set (to en_US.UTF-8 in the example) as follows:

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales

The dpkg-reconfigure locales command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.

How do I get list of methods in a Python class?

Python 3.x answer without external libraries

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded result:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

Java generics: multiple generic parameters?

In your function definition you're constraining sets a and b to the same type. You can also write

public <X,Y> void myFunction(Set<X> s1, Set<Y> s2){...}

Escape a string for a sed replace pattern

don't forget all the pleasure that occur with the shell limitation around " and '

so (in ksh)

Var=">New version of \"content' here <"
printf "%s" "${Var}" | sed "s/[&\/\\\\*\\"']/\\&/g' | read -r EscVar

echo "Here is your \"text\" to change" | sed "s/text/${EscVar}/g"

C# List<> Sort by x then y

Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:

 public void SortList() {
     MyList.Sort(delegate(MyClass a, MyClass b)
     {
         int xdiff = a.x.CompareTo(b.x);
         if (xdiff != 0) return xdiff;
         else return a.y.CompareTo(b.y);
     });
 }

Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

For an easy fix, you could

echo 1 > /proc/sys/vm/overcommit_memory

if your're sure that your system has enough memory. See Linux over commit heuristic.

Get properties and values from unknown object

Yes, Reflection would be the way to go. First, you would get the Type that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType method on Object. Because it is on the Object class, it's callable by every object in .NET, as all types derive from Object (well, technically, not everything, but that's not important here).

Once you have the Type instance, you can call the GetProperties method to get the PropertyInfo instances which represent the run-time informationa about the properties on the Type.

Note, you can use the overloads of GetProperties to help classify which properties you retrieve.

From there, you would just write the information out to a file.

Your code above, translated, would be:

// The instance, it can be of any type.
object o = <some object>;

// Get the type.
Type type = o.GetType();

// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
    // Do something with the property info.
    DoSomething(info);
}

Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods or GetFields methods respectively.

Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.

Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as or is operator to help determine which base class/interface you are working with at runtime).

However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.

How can I plot separate Pandas DataFrames as subplots?

You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.

Working code:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes 
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
    for c in range(ncol):
        df_list[count].plot(ax=axes[r,c])
        count=+1

enter image description here

Using this code you can plot subplots in any configuration. You need to just define number of rows nrow and number of columns ncol. Also, you need to make list of data frames df_list which you wanted to plot.

Swift 3: Display Image from URL

Use extension for UIImageView to Load URL Images.

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func imageURLLoad(url: URL) {

        DispatchQueue.global().async { [weak self] in
            func setImage(image:UIImage?) {
                DispatchQueue.main.async {
                    self?.image = image
                }
            }
            let urlToString = url.absoluteString as NSString
            if let cachedImage = imageCache.object(forKey: urlToString) {
                setImage(image: cachedImage)
            } else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    imageCache.setObject(image, forKey: urlToString)
                    setImage(image: image)
                }
            }else {
                setImage(image: nil)
            }
        }
    }
}

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Shortcut to exit scale mode in VirtualBox

If Right Ctrl (Host Key) + C does not work (there have been some issues on Ubuntu), do the following:

1) File > Preferences > Input on the Virtual Machine which is stuck in Scale Mode

2) Change or Reset the Host Key. There's no need to even save after changing the settings

3) Re-open the Virtual Machine and it should be reset!

range() for floats

using itertools: lazily evaluated floating point range:

>>> from itertools import count, takewhile
>>> def frange(start, stop, step):
        return takewhile(lambda x: x< stop, count(start, step))

>>> list(frange(0.5, 5, 1.5))
# [0.5, 2.0, 3.5]

Bring element to front using CSS

Another Note: z-index must be considered when looking at children objects relative to other objects.

For example

<div class="container">
    <div class="branch_1">
        <div class="branch_1__child"></div>
    </div>
    <div class="branch_2">
        <div class="branch_2__child"></div>
    </div>
</div>

If you gave branch_1__child a z-index of 99 and you gave branch_2__child a z-index of 1, but you also gave your branch_2 a z-index of 10 and your branch_1 a z-index of 1, your branch_1__child still will not show up in front of your branch_2__child

Anyways, what I'm trying to say is; if a parent of an element you'd like to be placed in front has a lower z-index than its relative, that element will not be placed higher.

The z-index is relative to its containers. A z-index placed on a container farther up in the hierarchy basically starts a new "layer"

Incep[inception]tion

Here's a fiddle to play around:

https://jsfiddle.net/orkLx6o8/

Should we pass a shared_ptr by reference or by value?

I ran the code below, once with foo taking the shared_ptr by const& and again with foo taking the shared_ptr by value.

void foo(const std::shared_ptr<int>& p)
{
    static int x = 0;
    *p = ++x;
}

int main()
{
    auto p = std::make_shared<int>();
    auto start = clock();
    for (int i = 0; i < 10000000; ++i)
    {
        foo(p);
    }    
    std::cout << "Took " << clock() - start << " ms" << std::endl;
}

Using VS2015, x86 release build, on my intel core 2 quad (2.4GHz) processor

const shared_ptr&     - 10ms  
shared_ptr            - 281ms 

The copy by value version was an order of magnitude slower.
If you are calling a function synchronously from the current thread, prefer the const& version.

How to pass data from child component to its parent in ReactJS?

Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component

in Parent Function Component we will have :

import React, { useState, useEffect } from "react";

then

const [childData, setChildData] = useState("");

and passing setChildData (which do a job similar to this.setState in Class Components) to Child

return( <ChildComponent passChildData={setChildData} /> )

in Child Component first we get the receiving props

function ChildComponent(props){ return (...) }

then you can pass data anyhow like using a handler function

const functionHandler = (data) => {

props.passChildData(data);

}

How to capture UIView to UIImage without loss of quality on retina display

I have created a Swift extension based on @Dima solution:

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

EDIT: Swift 4 improved version

extension UIImage {
    class func imageWithView(_ view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
        defer { UIGraphicsEndImageContext() }
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
}

Usage:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))  
let image = UIImage.imageWithView(view)

sql server Get the FULL month name from a date

SELECT DATENAME(MONTH, GETDATE()) 
         + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]

OR Date without Comma Between date and year, you can use the following

SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
           + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]

How to dismiss the dialog with click on outside of the dialog?

This method should completely avoid activities below the grey area retrieving click events.

Remove this line if you have it:

window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

Put this on your activity created

getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

then override the touch event with this

@Override
public boolean onTouchEvent(MotionEvent ev)
{
    if(MotionEvent.ACTION_DOWN == ev.getAction())
    {
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
        if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
            // You have clicked the grey area
            displayYourDialog();
            return false; // stop activity closing
        }
    }

    // Touch events inside are fine.
    return super.onTouchEvent(ev);
}

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

Set today's date as default date in jQuery UI datepicker

Note: When you pass setDate, you are calling a method which assumes the datepicker has already been initialized on that object.

$(function() {    
   $('#date').datepicker();
   $('#date').datepicker('setDate', '04/23/2014');
});

Test: http://jsfiddle.net/wimarbueno/hQkec/1/

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

In my case, I had to setup the public key for another user, as I already had one for my main user. once I switched users and performed the commands in the link above I was able to perform the setup for my test server without a problem.

javascript: Disable Text Select

Simple Copy this text and put on the before </body>

function disableselect(e) {
  return false
}

function reEnable() {
  return true
}

document.onselectstart = new Function ("return false")

if (window.sidebar) {
  document.onmousedown = disableselect
  document.onclick = reEnable
}

DynamoDB vs MongoDB NoSQL

Short answer: Start with SQL and add NoSQL only when/if needed. (unless you don't need anything beyond very simple queries)

My personal experience: I haven't used MongoDB for queries but as of April 2015 DynamoDB is still very crippled when it comes to anything beyond the most basic key/value queries. I love it for the basic stuff but if you want query language then look to a real SQL database solution.

In DynamoDB you can query on a hash or on a hash and range key, and you can have multiple secondary global indexes. I'm doing queries on a single table with 4 possible filter parameters and sorting the results, this is supported (barely) through the use of the global secondary indexes with filter expressions. The problem comes in when you try to get the total results matching the filter, you can't just search for the first 10 items matching the filter, but rather it checks 10 items and you may get 0 valid results forcing you to keep re-scanning from the continue key - pain in the neck and consumes too much of your table read quota for a simple scenario.

To be specific about the limit problem with filters in the query, this is from the docs (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#ScanQueryLimit):

In a response, DynamoDB returns all the matching results within
the scope of the Limit value. For example, if you issue a Query 
or a Scan request with a Limit value of 6 and without a filter
expression, the operation returns the first six items in the 
table that match the request parameters. If you also supply a
FilterExpression, the operation returns the items within the 
first six items in the table that match the filter requirements.

My conclusion is that queries involving FilterExpressions are only usable on very rare occasions and are not scalable because each query can easily read most or all of your of your table which consumes far too many DynamoDB read units. Once you use too many read units you'll get throttled and see poor performance.

Expert opinion: In the AWS summit on Apr 9, 2015 Brett Hollman, Manager, Solutions Architecture, AWS in his talk on scalling to your first 10 million users advocates starting with a SQL database and then using NoSQL only when and if it makes sense. Because sooner or later you'll probably need a SQL server somewhere in your stack. His slides are here: http://www.slideshare.net/AmazonWebServices/deep-dive-scaling-up-to-your-first-10-million-users See slide 28.

SQL query for a carriage return in a string and ultimately removing carriage return

You can also use regular expressions:

SELECT * FROM Parameters WHERE Name REGEXP '\n';

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

close fancy box from function from within open 'fancybox'

to close fancybox by funciton its necessary to make setTimtout to the function that will close the fancybox Fancybox needs some time to acept the close function If you call the function directly will not work

function close_fancybox(){
$.fancybox.close();
                     }
setTimeout(close_fancybox, 50);

How to add a new project to Github using VS Code

  1. create a new github repository.
  2. Goto the command line in VS code.(ctrl+`)
  3. Type following commands.

git init

git commit -m "first commit"

git remote add origin https://github.com/userName/repoName.git

git push -u origin master

-

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

Make footer stick to bottom of page using Twitter Bootstrap

just add the class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

Update for Bootstrap 4 -

as mentioned by Sara Tibbetts - class is fixed-bottom

<div class="footer fixed-bottom">

Android WebView progress bar

I have just found a really good example of how to do this here: http://developer.android.com/reference/android/webkit/WebView.html . You just need to change the setprogress from:

activity.setProgress(progress * 1000);

to

activity.setProgress(progress * 100);

Removing App ID from Developer Connection

As @AlexanderN pointed out, you can now delete App IDs.

  1. In your Member Center go to the Certificates, Identifiers & Profiles section.
  2. Go to Identifiers folder.
  3. Select the App ID you want to delete and click Settings
  4. Scroll down and click Delete.

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

How to change password using TortoiseSVN?

On the server.. In our environment, we're running Apache2 on Windows Server 2003.
Suppose Apache is serving our repository from C:\repo\MyProject

The actual repository is in C:\repo\MyProject\db

and the configuration is in C:\repo\MyProject\conf

So the passwords are in: C:\repo\MyProject.htaccess

They're encrypted, a tool similar to this: http://tools.dynamicdrive.com/password/

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Not all at once. But you can press

Alt + Enter

People assume it only works when you are at the particular item. But it actually works for "next missing type". So if you keep pressing Alt + Enter, IDEA fixes one after another until all are fixed.

How to set background color of a View

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

Type or namespace name does not exist

I am referencing Microsoft.CommerceServer.Runtime.Orders and experienced this error. This project is old and has Target framework .NET 2.0. In output I had this error:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3268: The primary reference "Microsoft.CommerceServer.Runtime" could not be resolved because it has an indirect dependency on the framework assembly "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v2.0". To resolve this problem, either remove the reference "Microsoft.CommerceServer.Runtime" or retarget your application to a framework version which contains "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

I simply changed the target framework to .NET 4 and now it builds.

Bash script to check running process

Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.

#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if  ${#result}> 0 
then
        echo " Working!"
else
        echo "Not Working.....Restarting"
        /usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

Good Linux (Ubuntu) SVN client

kdesvn is probably the best you'll find.

Last I checked it may hook in with konqueror, but its been a while, I've moved on to git :)

How to write string literals in python without having to escape them?

There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.

Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.

That is, there's no way to have the string

 '   ''' """  " \

properly stored in any Python string literal without internal escaping of some sort.

How can I verify a Google authentication API access token?

Ok, most answers are valid but not quite right. The idea of JWT is that you can validate the token without the need to contact the issuer everytime. You must check the id and verify the signature of the token with the known public key of the certificate google used to sign the token.

See the next post why and how to do this.

http://ncona.com/2015/02/consuming-a-google-id-token-from-a-server/

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

PHP form send email to multiple recipients

Use comma separated values as below.

$email_to = 'Mary <[email protected]>, Kelly <[email protected]>';
@mail($email_to, $email_subject, $email_message, $headers);

or run a foreach for email address

//list of emails in array format and each one will see their own to email address
$arrEmail = array('Mary <[email protected]>', 'Kelly <[email protected]>');

foreach($arrEmail as $key => $email_to)
    @mail($email_to, $email_subject, $email_message, $headers);

Is it possible to Turn page programmatically in UIPageViewController?

Here is a solution using UIPageViewControllerDataSource methods:

The code keeps track of the current displayed view controller in the UIPageViewController.

...
@property (nonatomic, strong) UIViewController *currentViewController;
@property (nonatomic, strong) UIViewController *nextViewController;
...

First initialize currentViewController to the initial view controller set for the UIPageViewController.

- (void) viewDidLoad {
    [super viewDidLoad];
    ...
    self.currentViewController = self.viewControllers[0];
    ...
    [self.pageViewController setViewControllers: @[self.currentViewController] direction: dir animated: YES completion: nil];
}


Then keep track of currentViewController in the UIPageViewControllerDelegate methods: pageViewController: willTransitionToViewControllers: and pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted:.


- (nullable UIViewController *) pageViewController: (UIPageViewController *) pageViewController viewControllerBeforeViewController: (UIViewController *) viewController {
    NSInteger idx = [self.viewControllers indexOfObject: viewController];
    if (idx > 0) {
        return self.viewControllers[idx - 1];
    } else {
        return nil;
    }
}

- (nullable UIViewController *) pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController: (UIViewController *) viewController {
    NSInteger idx = [self.viewControllers indexOfObject: viewController];
    if (idx == NSNotFound) {
        return nil;
    } else {
        if (idx + 1 < self.viewControllers.count) {
            return self.viewControllers[idx + 1];
        } else {
            return nil;
        }
    }
}

- (void) pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    self.nextViewController = [pendingViewControllers firstObject];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        self.currentViewController = self.nextViewController;
    }
}

Finally, in the method of your choice (in the example below it's - (IBAction) onNext: (id) sender), you can programmatically switch to the next or previous controller using UIPageViewControllerDataSouce methods pageViewController:viewControllerBeforeViewController: , pageViewController:viewControllerAfterViewController: to get the next or prev view controller and navigate to it by calling [self.pageViewController setViewControllers: @[vc] direction: UIPageViewControllerNavigationDirectionForward animated: YES completion: nil];


- (void) onNext {
    UIViewController *vc = [self pageViewController: self.tutorialViewController viewControllerAfterViewController: self.currentViewController];
    if (vc != nil) {
        self.currentViewController = vc;
        [self.tutorialViewController setViewControllers: @[vc] direction: UIPageViewControllerNavigationDirectionForward animated: YES completion: nil];
    }
}

Getting MAC Address

Alternatively,

import uuid
mac_id=(':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)

How to extract text from a string using sed?

sed doesn't recognize \d, use [[:digit:]] instead. You will also need to escape the + or use the -r switch (-E on OS X).

Note that [0-9] works as well for Arabic-Hindu numerals.

Can't specify the 'async' modifier on the 'Main' method of a console app

As you discovered, in VS11 the compiler will disallow an async Main method. This was allowed (but never recommended) in VS2010 with the Async CTP.

I have recent blog posts about async/await and asynchronous console programs in particular. Here's some background info from the intro post:

If "await" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method. Await will also capture the current context when it passes the remainder of the method to the awaitable.

Later on, when the awaitable completes, it will execute the remainder of the async method (within the captured context).

Here's why this is a problem in Console programs with an async Main:

Remember from our intro post that an async method will return to its caller before it is complete. This works perfectly in UI applications (the method just returns to the UI event loop) and ASP.NET applications (the method returns off the thread but keeps the request alive). It doesn't work out so well for Console programs: Main returns to the OS - so your program exits.

One solution is to provide your own context - a "main loop" for your console program that is async-compatible.

If you have a machine with the Async CTP, you can use GeneralThreadAffineContext from My Documents\Microsoft Visual Studio Async CTP\Samples(C# Testing) Unit Testing\AsyncTestUtilities. Alternatively, you can use AsyncContext from my Nito.AsyncEx NuGet package.

Here's an example using AsyncContext; GeneralThreadAffineContext has almost identical usage:

using Nito.AsyncEx;
class Program
{
    static void Main(string[] args)
    {
        AsyncContext.Run(() => MainAsync(args));
    }

    static async void MainAsync(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

Alternatively, you can just block the main Console thread until your asynchronous work has completed:

class Program
{
    static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();
    }

    static async Task MainAsync(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

Note the use of GetAwaiter().GetResult(); this avoids the AggregateException wrapping that happens if you use Wait() or Result.

Update, 2017-11-30: As of Visual Studio 2017 Update 3 (15.3), the language now supports an async Main - as long as it returns Task or Task<T>. So you can now do this:

class Program
{
    static async Task Main(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

The semantics appear to be the same as the GetAwaiter().GetResult() style of blocking the main thread. However, there's no language spec for C# 7.1 yet, so this is only an assumption.

rand() returns the same number each time the program is run

You need to change the seed.

int main() {

    srand(time(NULL));
    cout << (rand() % 101);
    return 0;
}

the srand seeding thing is true also for a c language code.


See also: http://xkcd.com/221/

How to get the ActionBar height?

While @birdy's answer is an option if you want to explicitly control the ActionBar size, there is a way to pull it up without locking the size that I found in support documentation. It's a little awkward but it's worked for me. You'll need a context, this example would be valid in an Activity.

// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
    Int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}

Kotlin:

val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}

How to echo shell commands as they are executed

I use a function to echo and run the command:

#!/bin/bash
# Function to display commands
exe() { echo "\$ $@" ; "$@" ; }

exe echo hello world

Which outputs

$ echo hello world
hello world

For more complicated commands pipes, etc., you can use eval:

#!/bin/bash
# Function to display commands
exe() { echo "\$ ${@/eval/}" ; "$@" ; }

exe eval "echo 'Hello, World!' | cut -d ' ' -f1"

Which outputs

$  echo 'Hello, World!' | cut -d ' ' -f1
Hello

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Twitter Bootstrap: div in container with 100% height

you need to add padding-top to "fill" element, plus add box-sizing:border-box - sample here bootply

How do I detect a click outside an element?

Subscribe capturing phase of click to handle click on elements which call preventDefault.
Retrigger it on document element using the other name click-anywhere.

document.addEventListener('click', function (event) {
  event = $.event.fix(event);
  event.type = 'click-anywhere';
  $document.trigger(event);
}, true);

Then where you need click outside functionality subscribe on click-anywhere event on document and check if the click was outside of the element you are interested in:

$(document).on('click-anywhere', function (event) {
  if (!$(event.target).closest('#smth').length) {
    // Do anything you need here
  }
});

Some notes:

  • You have to use document as it would be a perfomance fault to trigger event on all elements outside of which the click occured.

  • This functionality can be wrapped into special plugin, which calls some callback on outside click.

  • You can't subscribe capturing phase using jQuery itself.

  • You don't need document load to subscribe as subscription is on document, even not on its body, so it exists always independently ???? script placement and load status.

MySQL - Using COUNT(*) in the WHERE clause

SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;

EDIT (if you just want the gids):

SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC

Smooth scroll without the use of jQuery

Native browser smooth scrolling in JavaScript is like this:

// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

// scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // negative value acceptable
  left: 0, 
  behavior: 'smooth' 
});

// scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

C++ deprecated conversion from string constant to 'char*'

For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to char *:

class StringWrapper {
    std::vector<char> vec;
public:
    StringWrapper(const std::string &str) : vec(str.begin(), str.end()) {
    }

    char *getChars() {
        return &vec[0];
    }
};

What are some resources for getting started in operating system development?

There are a lot of links after this brief overview of what is involved in writing an OS for the X86 platform.

The link that appears to be most promising (www.nondot.org/sabre/os/articles) is no longer available, so you'll need to poke through the Archive.org version to read it.

At the end of the day the bootloader takes the machine code of the kernel, puts it in memory, and jumps to it. You can put any machine code in the kernel that you want, but most C programs expect an OS so you'll need to tell your compiler that it won't have all that, or the bootloader has to create some of it.

The kernel then does all the heavy lifting, and I suspect it's the example kernel you want. But there's a long way to go between having a kernel that says, "Hello world" to having a kernel that loads a command interpretor, provides disk services, and loads and manages programs.

You might want to consider subscribing to ACM to get access to their older literature - there are lots of articles in the late 80's and early 90's in early computing magazines about how to create alternative OSs. There are likely books that are out of print from this era as well. You might be able to get the same information for free by looking up the indexes of those magazines (which are available on that site - click "index" near the magazine name) and then asking around for people with a copy.

Lastly, I know that usenet is dead (for so sayeth the prophets of internet doom) but you'll find that many of the craggy old experts from that era still live there. You should search google groups (they have dejanews's old repository) and I expect you'll find many people asking the same questions a decade or 1.5 ago that you're asking now. You may even run across Linus Torvalds' many queries for help as he was developing linux originally. If searches don't bring anything up, ask in the appropriate newsgroup (probably starts with comp.arch, but search for ones with OS in the name).

How to jump back to NERDTree from file in tab?

You can focus on a split window using # ctrl-ww.

for example, pressing:

1 ctrl-ww

would focus on the first window, usually being NERDTree.

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

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

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

update one table with data from another

For MySql:

UPDATE table1 JOIN table2 
    ON table1.id = table2.id
SET table1.name = table2.name,
    table1.`desc` = table2.`desc`

For Sql Server:

UPDATE   table1
SET table1.name = table2.name,
    table1.[desc] = table2.[desc]
FROM table1 JOIN table2 
   ON table1.id = table2.id

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Is it possible to set a custom font for entire of application?

I would also suggest extending TextView and other controls, but it would be better I consider to set up font in constructs.

public FontTextView(Context context) {
    super(context);
    init();
}

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

protected void init() {
    setTypeface(Typeface.createFromAsset(getContext().getAssets(), AppConst.FONT));
}

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

Removing multiple keys from a dictionary safely

I have no problem with any of the existing answers, but I was surprised to not find this solution:

keys_to_remove = ['a', 'b', 'c']
my_dict = {k: v for k, v in zip("a b c d e f g".split(' '), [0, 1, 2, 3, 4, 5, 6])}

for k in keys_to_remove:
    try:
        del my_dict[k]
    except KeyError:
        pass

assert my_dict == {'d': 3, 'e': 4, 'f': 5, 'g': 6}

Note: I stumbled across this question coming from here. And my answer is related to this answer.

How do you echo a 4-digit Unicode character in Bash?

Any of these three commands will print the character you want in a console, provided the console do accept UTF-8 characters (most current ones do):

echo -e "SKULL AND CROSSBONES (U+2620) \U02620"
echo $'SKULL AND CROSSBONES (U+2620) \U02620'
printf "%b" "SKULL AND CROSSBONES (U+2620) \U02620\n"

SKULL AND CROSSBONES (U+2620) ?

After, you could copy and paste the actual glyph (image, character) to any (UTF-8 enabled) text editor.

If you need to see how such Unicode Code Point is encoded in UTF-8, use xxd (much better hex viewer than od):

echo $'(U+2620) \U02620' | xxd
0000000: 2855 2b32 3632 3029 20e2 98a0 0a         (U+2620) ....

That means that the UTF8 encoding is: e2 98 a0

Or, in HEX to avoid errors: 0xE2 0x98 0xA0. That is, the values between the space (HEX 20) and the Line-Feed (Hex 0A).

If you want a deep dive into converting numbers to chars: look here to see an article from Greg's wiki (BashFAQ) about ASCII encoding in Bash!

Git: Cannot see new remote branch

I used brute force and removed the remote and then added it

git remote rm <remote>
git remote add <url or ssh>

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

Delete topic in Kafka 0.8.1.1

Step 1: Make sure you are connected to zookeeper and Kafka running

Step 2: To delele the Kafka topic run Kafka-topic (Mac) or Kafka-topic.sh if use (linux/Mac) add the port and --topic with name of your topic and --delete it just delete the topic with success.

# Delete the kafka topic
# it will delete the kafka topic
kafka-topics --zookeeper 127.0.0.1:2181 --topic name_of_topic --delete
# or
kafka-topics.sh --zookeeper 127.0.0.1:2181 --topic name_of_topic --delete

Android Fragment onAttach() deprecated

Download newest Support library with the sdk manager and include

compile 'com.android.support:appcompat-v7:23.1.1'

in gradle.app and set compile version to api 23

Exception: Can't bind to 'ngFor' since it isn't a known native property

In my case I made the mistake of copying *ng-for= from the docs.

https://angular.io/guide/user-input

Correct me if I am wrong. But it seems *ng-for= has been changed to *ngFor=

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You may take a look at intellij code folding shortcuts.

For Windows/Linux do: Ctrl+Shift+-

For mac use Command+Shift+-

To unfold again do Ctrl+Shift++ or Command+Shift++ respectivley.

An invalid form control with name='' is not focusable

In my case..

ng-show was being used.
ng-if was put in its place and fixed my error.

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Another neat option is to use the Directive as an element and not as an attribute.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

And this directive can be used like that:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

Simple, neat and powerful.

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How can I use regex to get all the characters after a specific character, e.g. comma (",")

[^,]*$

might do. (Matches everything after the last comma).

Explanation: [^,] matches every character except for ,. The * denotes that the regexp matches any number of repetition of [^,]. The $ sign matches the end of the line.

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

What is the difference between the | and || or operators?

By their mathematical definition, OR and AND are binary operators; they verify the LHS and RHS conditions regardless, similarly to | and &.

|| and && alter the properties of the OR and AND operators by stopping them when the LHS condition isn't fulfilled.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

How to convert an array to object in PHP?

I use the following to parse Yaml files associative arrays into an object state.

This checks all supplied arrays if there are objects hiding there, and turns them also in objects.

    /**
     * Makes a config object from an array, making the first level keys properties a new object.
     * Property values are converted to camelCase and are not set if one already exists.
     * @param array $configArray Config array.
     * @param boolean $strict To return an empty object if $configArray is not an array
     * @return stdObject The config object
     */
    public function makeConfigFromArray($configArray = [],$strict = true)
    {
        $object = new stdClass();

        if (!is_array($configArray)) {
            if(!$strict && !is_null($configArray)) {
                return $configArray;
            }
            return $object;
        }

        foreach ($configArray as $name => $value) {
            $_name = camel_case($name);
            if(is_array($value)) {
                $makeobject = true;
                foreach($value as $key => $val) {
                    if(is_numeric(substr($key,0,1))) {
                        $makeobject = false;
                    }
                    if(is_array($val)) {
                        $value[$key] = $this->makeConfigFromArray($val,false);
                    }
                }
                if($makeobject) {
                    $object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
                }
                else {
                    $object->{$name} = $object->{$_name} = $value;
                }

            }
            else {
                $object->{$name} = $object->{$_name} = $value;
            }
        }

        return $object;
    }

This turns a yaml configured as

fields:
    abc:
        type: formfield
        something:
            - a
            - b
            - c
            - d:
                foo: 
                   bar

to an array consisting of:

array:1 [
  "fields" => array:1 [
    "abc" => array:2 [
      "type" => "formfield"
      "something" => array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => array:1 [
          "d" => array:1 [
            "foo" => "bar"
          ]
        ]
      ]
    ]
  ]
]

to an object of:

{#325
  +"fields": {#326
    +"abc": {#324
      +"type": "formfield"
      +"something": array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => {#328
          +"d": {#327
            +"foo": "bar"
          }
        }
      ]
    }
  }
}

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

angular2: how to copy object into another object

Loadsh is the universal standard library for coping any object deepcopy. It's a recursive algorithm. It's check everything and does copy for the given object. Writing this kind of algorithm will take longer time. It's better to leverage the same.

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Convert a date format in epoch

tl;dr

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

How do I install TensorFlow's tensorboard?

I have a local install of tensorflow 1.15.0 (with tensorboard obviously included) on MacOS.

For me, the path to the relevant file within my user directory is Library/Python/3.7/lib/python/site-packages/tensorboard/main.py. So, which does not work for me, but you have to look for the file named main.py, which is weird since it apparently is named something else for other users.

Understanding Python super() with __init__() methods

It's been noted that in Python 3.0+ you can use

super().__init__()

to make your call, which is concise and does not require you to reference the parent OR class names explicitly, which can be handy. I just want to add that for Python 2.7 or under, some people implement a name-insensitive behaviour by writing self.__class__ instead of the class name, i.e.

super(self.__class__, self).__init__()  # DON'T DO THIS!

HOWEVER, this breaks calls to super for any classes that inherit from your class, where self.__class__ could return a child class. For example:

class Polygon(object):
    def __init__(self, id):
        self.id = id

class Rectangle(Polygon):
    def __init__(self, id, width, height):
        super(self.__class__, self).__init__(id)
        self.shape = (width, height)

class Square(Rectangle):
    pass

Here I have a class Square, which is a sub-class of Rectangle. Say I don't want to write a separate constructor for Square because the constructor for Rectangle is good enough, but for whatever reason I want to implement a Square so I can reimplement some other method.

When I create a Square using mSquare = Square('a', 10,10), Python calls the constructor for Rectangle because I haven't given Square its own constructor. However, in the constructor for Rectangle, the call super(self.__class__,self) is going to return the superclass of mSquare, so it calls the constructor for Rectangle again. This is how the infinite loop happens, as was mentioned by @S_C. In this case, when I run super(...).__init__() I am calling the constructor for Rectangle but since I give it no arguments, I will get an error.

List of IP Space used by Facebook

# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
  iptables -A FORWARD -p all -d $ip -j REJECT
done

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs

shows the position where to change the view

How to add multiple font files for the same font?

As of CSS3, the spec has changed, allowing for only a single font-style. A comma-separated list (per CSS2) will be treated as if it were normal and override any earlier (default) entry. This will make fonts defined in this way appear italic permanently.

@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Bold.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: italic;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: oblique;
}

In most cases, italic will probably be sufficient and oblique rules won't be necessary if you take care to define whichever you will use and stick to it.

FTP/SFTP access to an Amazon S3 Bucket

Answer from 2014 for the people who are down-voting me:

Well, S3 isn't FTP. There are lots and lots of clients that support S3, however.

Pretty much every notable FTP client on OS X has support, including Transmit and Cyberduck.

If you're on Windows, take a look at Cyberduck or CloudBerry.

Updated answer for 2019:

AWS has recently released the AWS Transfer for SFTP service, which may do what you're looking for.

C# RSA encryption/decryption with transmission

public static string Encryption(string strText)
        {
            var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    // client encrypting data with public key issued by server                    
                    rsa.FromXmlString(publicKey.ToString());

                    var encryptedData = rsa.Encrypt(testData, true);

                    var base64Encrypted = Convert.ToBase64String(encryptedData);

                    return base64Encrypted;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

        public static string Decryption(string strText)
        {
            var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {                    
                    var base64Encrypted = strText;

                    // server decrypting data with private key                    
                    rsa.FromXmlString(privateKey);

                    var resultBytes = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, true);
                    var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                    return decryptedData.ToString();
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

How to return a resolved promise from an AngularJS Service using $q?

Here's the correct code for your service:

myApp.service('userService', [
  '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {

    var user = {
      access: false
    };

    var me = this;

    this.initialized = false;
    this.isAuthenticated = function() {

      var deferred = $q.defer();
      user = {
        first_name: 'First',
        last_name: 'Last',
        email: '[email protected]',
        access: 'institution'
      };
      deferred.resolve(user);
      me.initialized = true;

      return deferred.promise;
    };
  }
]);

Then you controller should align accordingly:

myApp.run([
  '$rootScope', 'userService', function($rootScope, userService) {
    return userService.isAuthenticated().then(function(user) {
      if (user) {
        // You have access to the object you passed in the service, not to the response.
        // You should either put response.data on the user or use a different property.
        return $rootScope.$broadcast('login', user.email);  
      } else {
        return userService.logout();
      }
    });
  }
]);

Few points to note about the service:

  • Expose in a service only what needs to be exposed. User should be kept internally and be accessed by getters only.

  • When in functions, use 'me' which is the service to avoid edge cases of this with javascript.

  • I guessed what initialized was meant to do, feel free to correct me if I guessed wrong.

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Why is the minidlna database not being refreshed?

MiniDLNA uses inotify, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.

The notify_interval (notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval (ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify functionality.

This is how it looks in my /etc/minidlna.conf:

# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes

Make sure that inotify is enabled in your kernel.

If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.

How and where are Annotations used in Java?

There are 2 views of annotations

  1. user view, most of the time, annotations work like a shortcut, save you some key strokes, or make your program more readable

  2. vendor view, the processor's view of annotation is more of light weighted 'interface', your program DOES confront to SOMETHING but without explicitly "implements" the particular interface(here aka the annotation)

e.g. in jpa you define something like

@Entity class Foo {...}

instead of

class Foo implements Entity {...}

both speak the same thing "Foo is an Entity class"

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

Recommendation for compressing JPG files with ImageMagick

I'm using the Google Pagespeed Insights image optimization guidelines, and for ImageMagick they recommend the following:

-sampling-factor 4:2:0
-strip
-quality 85 [it can vary, I use range 60-80, lower number here means smaller file]
-interlace
-colorspace RGB

Command in ImageMagick:

convert image.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB image_converted.jpg

With these options I get up to 40% savings in JPEG size without much visible loss.

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

Passing Parameters JavaFX FXML

Yes you can.
You need to add in the first controller:

YourController controller = loader.getController();     
controller.setclient(client);

Then in the second one declare a client, then at the bottom of your controller:

public void setclien(Client c) {
    this.client = c;
}

Where to place the 'assets' folder in Android Studio?

When upgrading to the release version of Android Studio, you may be automatically switched to the new Android project View (see here for more info). If you swap back to either the Project or Packages view, you should see the standard folder hierarchy of a Gradle-based project. Then refer to CommonsWare's answer for the appropriate location.

ng is not recognized as an internal or external command

execute following lines in order to solve the issue for both not found and undefined version of ng

npm uninstall -g angular-cli

npm uninstall --save-dev angular-cli

npm cache clean

npm install -g @angular/cli@latest

How to enable cURL in PHP / XAMPP

Actually I did it by uncommenting extension=php_curl.dll in the xampp\apache\bin\php.ini file.

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

WCF timeout exception detailed investigation

If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.

If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.

Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.

Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com - this will reduce the amount of irrelevant traffic.

If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.

When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.

Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this CodeProject article/project: LINQ TO CSV.

It will enable you to create a custom class that is shaped like your .csv file's columns. You'd then consume the CSV and bind to your DataGridView.

Dim cc As new CsvContext()
Dim inputFileDescription As New CsvFileDescription() With { _
    .SeparatorChar = ","C, _
    .FirstLineHasColumnNames = True _
}

Dim products As IEnumerable(Of Product) = _
     cc.Read(Of Product)("products.csv", inputFileDescription)

' query from CSV, load into a new class of your own   
Dim productsByName = From p In products
    Select New CustomDisplayClass With _
       {.Name = p.Name, .SomeDate = p.SomeDate, .Price = p.Price}, _        
    Order By p.Name


myDataGridView1.DataSource = products
myDataGridView1.DataBind()

How to add external library in IntelliJ IDEA?

This question can also be extended if necessary jar file can be found in global library, how can you configure it into your current project.

Process like these: "project structure"-->"modules"-->"click your current project pane at right"-->"dependencies"-->"click little add(+) button"-->"library"-->"select the library you want".

if you are using maven and you can also configure dependency in your pom.xml, but it your chosen version is not like the global library, you will waste memory on storing another version of the same jar file. so i suggest use the first step.

Is there a command to refresh environment variables from the command prompt in Windows?

There is no straight way, as Kev said. In most cases, it is simpler to spawn another CMD box. More annoyingly, running programs are not aware of changes either (although IIRC there might be a broadcast message to watch to be notified of such change).

It have been worse: in older versions of Windows, you had to log off then log back to take in account the changes...

OR is not supported with CASE Statement in SQL Server

select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
else
'No gender'
end
as gender 
from contacts

How to get date and time from server

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; ) Like : ;extension=php_intl.dll. to. extension=php_intl.dll.
  4. Save the xampp/php/php.ini file.
  5. Restart your xampp/wamp.

Short description of the scoping rules?

Where is x found?

x is not found as you haven't defined it. :-) It could be found in code1 (global) or code3 (local) if you put it there.

code2 (class members) aren't visible to code inside methods of the same class — you would usually access them using self. code4/code5 (loops) live in the same scope as code3, so if you wrote to x in there you would be changing the x instance defined in code3, not making a new x.

Python is statically scoped, so if you pass ‘spam’ to another function spam will still have access to globals in the module it came from (defined in code1), and any other containing scopes (see below). code2 members would again be accessed through self.

lambda is no different to def. If you have a lambda used inside a function, it's the same as defining a nested function. In Python 2.2 onwards, nested scopes are available. In this case you can bind x at any level of function nesting and Python will pick up the innermost instance:

x= 0
def fun1():
    x= 1
    def fun2():
        x= 2
        def fun3():
            return x
        return fun3()
    return fun2()
print fun1(), x

2 0

fun3 sees the instance x from the nearest containing scope, which is the function scope associated with fun2. But the other x instances, defined in fun1 and globally, are not affected.

Before nested_scopes — in Python pre-2.1, and in 2.1 unless you specifically ask for the feature using a from-future-import — fun1 and fun2's scopes are not visible to fun3, so S.Lott's answer holds and you would get the global x:

0 0

How do I detect if a user is already logged in Firebase?

https://firebase.google.com/docs/auth/web/manage-users

You have to add an auth state change observer.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

This solution solve my problem: (from: https://msdn.microsoft.com/en-us/library/ms239722.aspx)

To permanently attach a database file (.mdf) from the Data Connections node

  1. Open the shortcut menu for Data Connections and choose Add New Connection.

    The Add Connection dialog box appears.

  2. Choose the Change button.

    The Change Data Source dialog box appears.

  3. Select Microsoft SQL Server and choose the OK button.

    The Add Connection dialog box reappears, with Microsoft SQL Server (SqlClient) displayed in the Data source text box.

  4. In the Server Name box, type or browse to the path to the local instance of SQL Server. You can type the following:

    • "." for the default instance on your computer.
    • "(LocalDB)\v11.0" for the default instance of SQL Server Express LocalDB.
    • ".\SQLEXPRESS" for the default instance of SQL Server Express.

    For information about SQL Server Express LocalDB and SQL Server Express, see Local Data Overview.

  5. Select either Use Windows Authentication or Use SQL Server Authentication.

  6. Choose Attach a database file, Browse, and open an existing .mdf file.

  7. Choose the OK button.

    The new database appears in Server Explorer. It will remain connected to SQL Server until you explicitly detach it.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How to disable or enable viewpager swiping in android

If you want to extend it just because you need Not-Swipeable behaviour, you dont need to do it. ViewPager2 provides nice property called : isUserInputEnabled

Swipe ListView item From right to left show delete button

I just got his working using the ViewSwitcher in a ListItem.

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ViewSwitcher
    android:id="@+id/list_switcher"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right"
    android:measureAllChildren="false" >
    <TextView
        android:id="@+id/tv_item_name"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:maxHeight="50dp"
        android:paddingLeft="10dp" />

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:clickable="false"
        android:gravity="center"
        >

    <Button
        android:id="@+id/b_edit_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"

         />
    <Button
        android:id="@+id/b_delete_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:background="@android:color/holo_red_dark"
        />
    </LinearLayout>
</ViewSwitcher>

In the ListAdapter: Implement OnclickListeners for the Edit and Delete button in the getView() method. The catch here is to get the position of the ListItem clicked inside the onClick methods. setTag() and getTag() methods are used for this.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.list_item, null);
        viewHolder.viewSwitcher=(ViewSwitcher)convertView.findViewById(R.id.list_switcher);
        viewHolder.itemName = (TextView) convertView
                .findViewById(R.id.tv_item_name);
        viewHolder.deleteitem=(Button)convertView.findViewById(R.id.b_delete_in_list);
        viewHolder.deleteItem.setTag(position);
        viewHolder.editItem=(Button)convertView.findViewById(R.id.b_edit_in_list);
        viewHolder.editItem.setTag(position);
        viewHolder.deleteItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.deleteItemList((Integer)v.getTag());
            }
        });

        viewHolder.editItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.editItemList(position);
            }
        });
        convertView.setTag(viewHolder);
} else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.itemName.setText(itemlist[position]);
return convertView;  
}

In the Fragment, Add a Gesture Listener to detect the Fling Gesture:

public class MyGestureListener extends SimpleOnGestureListener {
    private ListView list;

    public MyGestureListener(ListView list) {
        this.list = list;
    }

    // CONDITIONS ARE TYPICALLY VELOCITY OR DISTANCE

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // if (INSERT_CONDITIONS_HERE)

        ltor=(e2.getX()-e1.getX()>DELTA_X);
        if (showDeleteButton(e1))
        {
            return true;
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    private boolean showDeleteButton(MotionEvent e1) {
        int pos = list.pointToPosition((int) e1.getX(), (int) e1.getY());
        return showDeleteButton(pos);
    }

    private boolean showDeleteButton(int pos) {

        View child = list.getChildAt(pos);
        if (child != null) {
            Button delete = (Button) child
                    .findViewById(R.id.b_edit_in_list);
            ViewSwitcher viewSwitcher = (ViewSwitcher) child
                    .findViewById(R.id.host_list_switcher);
            TextView hostName = (TextView) child
                    .findViewById(R.id.tv_host_name);
            if (delete != null) {
                    viewSwitcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_left));
                    viewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_right));
                }

                viewSwitcher.showNext();
                // frameLayout.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return false;
    }
}

In the onCreateView method of the Fragment,

GestureDetector gestureDetector = new GestureDetector(getActivity(),
            new MyGestureListener(hostList));
    hostList.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }

        }
    });

This worked for me. Should refine it more.

How does "make" app know default target to build if no target is specified?

GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.

Ref: The Gnu Make manual - Special Variables

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

What's the reason I can't create generic array types in Java?

It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.

How to enter a series of numbers automatically in Excel

I find it easier using this formula

=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")

Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.

Hope it helps

duplicate 'row.names' are not allowed error

The answer here (https://stackoverflow.com/a/22408965/2236315) by @adrianoesch should help (e.g., solves "If you know of a solution that does not require the awkward workaround mentioned in your comment (shift the column names, copy the data), that would be great." and "...requiring that the data be copied" proposed by @Frank).

Note that if you open in some text editor, you should see that the number of header fields less than number of columns below the header row. In my case, the data set had a "," missing at the end of the last header field.

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.

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.