Programs & Examples On #Boost test

Boost Test Library is a portable test framework for performing unit testing in c++

Comparison of C++ unit test frameworks

API Sanity Checker — test framework for C/C++ libraries:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.

The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

Unique features in comparison with CppUnit, Boost and Google Test:

  • Automatic generation of test data and input arguments (even for complex data types)
  • Modern and highly reusable specialized types instead of fixtures and templates

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) {
   //
}

What does [object Object] mean?

[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:

alert({}); // [object Object]

You can change the default representation by overriding the toString method like so:

var o = {toString: function(){ return "foo" }};
alert(o); // foo

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

Squash my last X commits together using Git

2020 Simple solution without rebase :

git reset --soft HEAD~2

git commit -m "new commit message"

git push -f

2 means the last two commits will be squashed. You can replace it by any number

passing form data to another HTML page

You need the get the values from the query string (since you dont have a method set, your using GET by default)

use the following tutorial.

http://papermashup.com/read-url-get-variables-withjavascript/

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Getting Date or Time only from a DateTime Object

Sometimes you want to have your GridView as simple as:

  <asp:GridView ID="grid" runat="server" />

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

protected void Page_Load(object sender, EventArgs e)
{
  grid.RowDataBound += grid_RowDataBound;
  // Your DB access code here...
  // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  // grid.DataBind();
}

void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType != DataControlRowType.DataRow)
    return;
  var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
  e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}

The results shown here. DateTime Formatting

Enter key in textarea

Simply add this tad to your textarea.

onkeydown="if(event.keyCode == 13) return false;"

What is the difference between linear regression and logistic regression?

Cannot agree more with the above comments. Above that, there are some more differences like

In Linear Regression, residuals are assumed to be normally distributed. In Logistic Regression, residuals need to be independent but not normally distributed.

Linear Regression assumes that a constant change in the value of the explanatory variable results in constant change in the response variable. This assumption does not hold if the value of the response variable represents a probability (in Logistic Regression)

GLM(Generalized linear models) does not assume a linear relationship between dependent and independent variables. However, it assumes a linear relationship between link function and independent variables in logit model.

SQL Server add auto increment primary key to existing table

by the designer you could set identity (1,1) right click on tbl => desing => in part left (right click) => properties => in identity columns select #column

Properties

idendtity column

How to load my app from Eclipse to my Android phone instead of AVD

The USB drivers in \extras\google\usb_driver didn't work for me.

However the official drivers from Samsung did: http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows

Note: I'm using a Samsung Galaxy S2 with Android 4.0 on Windows 7 64bit

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

How do you check for permissions to write to a directory or file?

Since this isn't closed, i would like to submit a new entry for anyone looking to have something working properly for them... using an amalgamation of what i found here, as well as using DirectoryServices to debug the code itself and find the proper code to use, here's what i found that works for me in every situation... note that my solution extends DirectoryInfo object... :

    public static bool IsReadable(this DirectoryInfo me)
    {

        AuthorizationRuleCollection rules;
        WindowsIdentity identity;
        try
        {
            rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            identity = WindowsIdentity.GetCurrent();
        }
        catch (Exception ex)
        { //Posible UnauthorizedAccessException
            return false;
        }

        bool isAllow=false;
        string userSID = identity.User.Value;

        foreach (FileSystemAccessRule rule in rules)
        {
            if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
            {
                if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Deny)
                    return false;
                else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Allow)
                    isAllow = true;
            }
        }

        return isAllow;
    }

    public static bool IsWriteable(this DirectoryInfo me)
    {
        AuthorizationRuleCollection rules;
        WindowsIdentity identity;
        try
        {
            rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            identity = WindowsIdentity.GetCurrent();
        }
        catch (Exception ex)
        { //Posible UnauthorizedAccessException
            return false;
        }

        bool isAllow = false;
        string userSID = identity.User.Value;

        foreach (FileSystemAccessRule rule in rules)
        {
            if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
            {
                if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
                    return false;
                else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
                    rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
                    isAllow = true;
            }
        }

        return me.IsReadable() && isAllow;
    }

How to turn on WCF tracing?

Go to your Microsoft SDKs directory. A path like this:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Open the WCF Configuration Editor (Microsoft Service Configuration Editor) from that directory:

SvcConfigEditor.exe

(another option to open this tool is by navigating in Visual Studio 2017 to "Tools" > "WCF Service Configuration Editor")

wcf configuration editor

Open your .config file or create a new one using the editor and navigate to Diagnostics.

There you can click the "Enable MessageLogging".

enable messagelogging

More info: https://msdn.microsoft.com/en-us/library/ms732009(v=vs.110).aspx

With the trace viewer from the same directory you can open the trace log files:

SvcTraceViewer.exe

You can also enable tracing using WMI. More info: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx

Can comments be used in JSON?

I just encountering this for configuration files. I don't want to use XML (verbose, graphically, ugly, hard to read), or "ini" format (no hierarchy, no real standard, etc.) or Java "Properties" format (like .ini).

JSON can do all they can do, but it is way less verbose and more human readable - and parsers are easy and ubiquitous in many languages. It's just a tree of data. But out-of-band comments are a necessity often to document "default" configurations and the like. Configurations are never to be "full documents", but trees of saved data that can be human readable when needed.

I guess one could use "#": "comment", for "valid" JSON.

What's a good (free) visual merge tool for Git? (on windows)

I've been using P4Merge, it's free and cross platform.

P4Merge

Add params to given URL in Python

I liked Lukasz version, but since urllib and urllparse functions are somewhat awkward to use in this case, I think it's more straightforward to do something like this:

params = urllib.urlencode(params)

if urlparse.urlparse(url)[4]:
    print url + '&' + params
else:
    print url + '?' + params

Nth max salary in Oracle

This will show the 3rd max salary from table employee. If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...

select min(sal) from(select distinct(sal) from emp  where rownum<=3 order by sal desc);

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

How to read fetch(PDO::FETCH_ASSOC);

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.

You can access the name field like this: $user['name'].

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

Importing JSON into an Eclipse project

You should take the json implementation from here : http://code.google.com/p/json-simple/ .

  • Download the *.jar
  • Add it to the classpath (right-click on the project, Properties->Libraries and add new JAR.)

Java, Calculate the number of days between two dates

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();

Read next word in java

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }

How to add an element to Array and shift indexes?

System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.

public static int[] insert(
    int[] array, int elementToInsert, int index) {
  int[] result = new int[array.length + 1];
  // copies first part of the array from the start up until the index
  System.arraycopy(
      array /* src */,
      0 /* srcPos */,
      result /* dest */,
      0 /* destPos */,
      index /* length */);
  // copies second part from the index up until the end shifting by 1 to the right
  System.arraycopy(
      array /* src */,
      index /* srcPos */,
      result /* dest */,
      index + 1 /* destPos */,
      array.length - index /* length */);
  result[index] = elementToInsert;
  return result;
}

And JUnit4 test to check it works as expected.

@Test
public void shouldInsertCorrectly() {
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
  Assert.assertArrayEquals(
      new int[]{1}, insert(new int[]{}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

String variable interpolation Java

You can use Kotlin, the Super (cede of) Java for JVM, it has a nice way of interpolating strings like those of ES5, Ruby and Python.

class Client(val firstName: String, val lastName: String) {
    val fullName = "$firstName $lastName"
}

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

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

The error says that FormGroup is not recognized in this module. So You have to import these(below) modules in every module that uses FormGroup

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Then add FormsModule and ReactiveFormsModule into your Module's imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

You may be thinking that I have already added it in AppModule and it should inherit from it? But it is not. because these modules are exporting required directives that are available only in importing modules. Read more here... https://angular.io/guide/sharing-ngmodules.

Other factors for these errors may be spell error like below...

[FormGroup]="form" Capital F instead of small f

[formsGroup]="form" Extra s after form

Objective-C for Windows

Get GNUStep here

Get MINGW here

Install MINGW Install GNUStep Then Test

ViewPager PagerAdapter not updating the View

ViewPager was not designed to support dynamic view change.

I had confirmation of this while looking for another bug related to this one https://issuetracker.google.com/issues/36956111 and in particular https://issuetracker.google.com/issues/36956111#comment56

This question is a bit old, but Google recently solved this problem with ViewPager2 . It will allow to replace handmade (unmaintained and potentially buggy) solutions by a standard one. It also prevents recreating views needlessly as some answers do.

For ViewPager2 examples, you can check https://github.com/googlesamples/android-viewpager2

If you want to use ViewPager2, you will need to add the following dependency in your build.gradle file :

  dependencies {
     implementation 'androidx.viewpager2:viewpager2:1.0.0-beta02'
  }

Then you can replace your ViewPager in your xml file with :

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

After that, you will need to replace ViewPager by ViewPager2 in your activity

ViewPager2 needs either a RecyclerView.Adapter, or a FragmentStateAdapter, in your case it can be a RecyclerView.Adapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context context;
    private ArrayList<String> arrayList = new ArrayList<>();

    public MyAdapter(Context context, ArrayList<String> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.tvName.setText(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
        }
    }
} 

In the case you were using a TabLayout, you can use a TabLayoutMediator :

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager, true, new TabLayoutMediator.OnConfigureTabCallback() {
            @Override
            public void onConfigureTab(@NotNull TabLayout.Tab tab, int position) {
                // configure your tab here
                tab.setText(tabs.get(position).getTitle());
            }
        });

        tabLayoutMediator.attach();

Then you will be able to refresh your views by modifying your adapter's data and calling notifyDataSetChanged method

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

Keyboard shortcut to clear cell output in Jupyter notebook

For versions less than 5:

Option 1 -- quick hack:

Change the cell type to raw then back to code: EscRY will discard the output.

Option 2 -- custom shortcut (without GUI):

For this, you need to edit the custom.js file which is typically located at ~/.jupyter/custom/custom.js (if it doesn't exist, create it).

In there, you have to add

require(['base/js/namespace']) {
    // setup 'ctrl-l' as shortcut for clearing current output
    Jupyter.keyboard_manager.command_shortcuts
           .add_shortcut('ctrl-l', 'jupyter-notebook:clear-cell-output');
}

You can add shortcut there for all the fancy things you like, since the 2nd argument can be a function (docs)

If you want mappings for other standard commands, you can dump a list of all available commands by running the following in your notebook:

from IPython.core.display import Javascript

js = """
  var jc_html = "";
  var jc_array = Object.keys(IPython.notebook.keyboard_manager.command_shortcuts.actions._actions);
  for (var i=0;i<jc_array.length;i++) {
    jc_html = jc_html + jc_array[i] + "<br >";
  }
  element.html(jc_html);
  """

Javascript(data=js, lib=None, css=None)

How to compare files from two different branches?

There are two scenarios to compare files:

Scenario 1: Compare files at remote branches (both branches should exists on remote repository)

Scenario 2: Compare local files (at local working area copy) to the files at remote repository.

The logic is simple. If you provide two branch names to diff, it will always compare the remote branches, and if you provide only one branch name, it will always compare your local working copy with the remote repo (the one you provided). You can use range to provide remote repositories.

e.g. Checkout a branch

git checkout branch1
git diff branch2 [filename]

in this case, if you provide filename, it will compare your local copy of filename with remote branch named "branch2".

git diff branch1 branch2 [filename]

in this case, it will compare filename from remote branches named "branch1" vs "branch2"

git diff ..branch2 [filename]

in this case also, it will compare filename from remote branches named "branch1" vs "branch2". So, its same as above. However, if you have just created a branch from another branch, say "master" and your current branch doesn't exists on remote repository, it will compare remote "master" vs remote "branch2".

Hope its useful.

Nesting CSS classes

Update 1: There is a CSS3 spec for CSS level 3 nesting. It's currently a draft. https://tabatkins.github.io/specs/css-nesting/

Update 2 (2019): We now have a CSSWG draft https://drafts.csswg.org/css-nesting-1/

If approved, the syntax would look like this:

table.colortable {
  & td {
    text-align:center;
    &.c { text-transform:uppercase }
    &:first-child, &:first-child + td { border:1px solid black }
  }
  & th {
    text-align:center;
    background:black;
    color:white;
  }
}

.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}

Status: The original 2015 spec proposal was not approved by the Working Group.

addEventListener in Internet Explorer

EDIT

I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

OLD ANSWER

this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help

(function (w,d) {  // 
    var
        nc  = "", nu    = "", nr    = "", t,
        a   = "addEventListener",
        n   = a in w,
        c   = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
        u   = n?(nu = "attach", "add"):(nu = "add","attach"),
        r   = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
 * the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
 */
    function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt  ))}}
    w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]

})(window, document)

List all kafka topics

The Kafka clients no longer require zookeeper but the Kafka servers do need it to operate.

You can get a list of topics with the new AdminClient API but the shell command that ship with Kafka have not yet been rewritten to use this new API.

The other way to use Kafka without Zookeeper is to use a SaaS Kafka-as-a-Service provider such as Confluent Cloud so you don’t see or operate the Kafka brokers (and the required backend Zookeeper ensemble).

For example on Confluent Cloud you would just use the following zookeeper free CLI command:

ccloud topic list

How to kill an application with all its activities?

which is stored in the SharesPreferences as long as the application needs it.

Why?

As soon as the user wants to exit, the password in the SharedPreferences should be wiped and of course all activities of the application should be closed (it makes no sense to run them without the known password - they would crash).

Even better: don't put the password in SharedPreferences. Hold onto it in a static data member. The data will naturally go away when all activities in the app are exited (e.g., BACK button) or otherwise destroyed (e.g., kicked out of RAM to make room for other activities sometime after the user pressed HOME).

If you want some sort of proactive "flush password", just set the static data member to null, and have your activities check that member and take appropriate action when it is null.

Rollback transaction after @Test

You need to run your test with a Spring context and a transaction manager, e.g.,

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"/your-applicationContext.xml"})
@TransactionConfiguration(transactionManager="txMgr")
public class StudentSystemTest {

     @Test
     public void testTransactionalService() {
         // test transactional service
     }

     @Test
     @Transactional
     public void testNonTransactionalService() {
         // test non-transactional service
     }
}

See chapter 3.5.8. Transaction Management of the Spring reference for further details.

jQuery Toggle Text?

Why not keep track of the state of through a class without CSS rules on the clickable anchor itself

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow');
        $("#show-background").toggleClass("clicked");
        if ( $("#show-background").hasClass("clicked") ) {
            $(this).text("Show Text");
        }
        else {
            $(this).text("Show Background");
        }
    });
});

Force Java timezone as GMT/UTC

tl;dr

String sql = "SELECT CURRENT_TIMESTAMP ;
…
OffsetDateTime odt = myResultSet.getObject( 1 , OffsetDateTime.class ) ;

Avoid depending on host OS or JVM for default time zone

I recommend you write all your code to explicitly state the desired/expected time zone. You need not depend on the JVM’s current default time zone. And be aware that the JVM’s current default time zone can change at any moment during runtime, with any code in any thread of any app calling TimeZone.setDefault. Such a call affects all apps within that JVM immediately.

java.time

Some of the other Answers were correct, but are now outmoded. The terrible date-time classes bundled with the earliest versions of Java were flawed, written by people who did not understand the complexities and subtleties of date-time handling.

The legacy date-time classes have been supplanted by the java.time classes defined in JSR 310.

To represent a time zone, use ZoneId. To represent an offset-from-UTC, use ZoneOffset. An offset is merely a number of hour-minutes-seconds ahead or behind the prime meridian. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region.

I need to force any time related operations to GMT/UTC

For an offset of zero hours-minutes-seconds, use the constant ZoneOffset.UTC.

Instant

To capture the current moment in UTC, use an Instant. This class represent a moment in UTC, always in UTC by definition.

Instant instant = Instant.now() ;  // Capture current moment in UTC.

ZonedDateTime

To see that same moment through the wall-clock time used by the people of a particular region, adjust into a time zone. Same moment, same point on the timeline, different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Database

You mention a database.

To retrieve a moment from the database, your column should be of a data type akin to the SQL-standard TIMESTAMP WITH TIME ZONE. Retrieve an object rather than a string. In JDBC 4.2 and later, we can exchange java.time objects with the database. The OffsetDateTime is required by JDBC, while Instant & ZonedDateTime are optional.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

In most databases and drivers, I would guess that you will get the moment as seen in UTC. But if not, you can adjust in either of two ways:

  • Extract a Instant: odt.toInstant()
  • Adjust from the given offset to an offset of zero: OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;`.

Table of date-time types in Java (both legacy and modern) and in standard SQL


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?

How to convert jsonString to JSONObject in Java

To anyone still looking for an answer:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

How do you normalize a file path in Bash?

FILEPATH="file.txt"
echo $(realpath $(dirname $FILEPATH))/$(basename $FILEPATH)

This works even if the file doesn't exist. It does require the directory containing the file to exist.

Split list into smaller lists (split in half)

This is similar to other solutions, but a little faster.

# Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5])

def split_half(a):
    half = len(a) >> 1
    return a[:half], a[half:]

What is a vertical tab?

In the medical industry, VT is used as the start of frame character in the MLLP/LLP/HLLP protocols that are used to frame HL-7 data, which has been a standard for medical exchange since the late 80s and is still in wide use.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make command this way:

make CFLAGS=-Dvar=42

And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile.

Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this variable in CFLAGS to avoid completely overriding CFLAGS.

PostgreSQL "DESCRIBE TABLE"

The psql equivalent of DESCRIBE TABLE is \d table.

See the psql portion of the PostgreSQL manual for more details.

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

Padding or margin value in pixels as integer using jQuery

I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...

Getting list of Facebook friends with latest API

in the recent version of facebook sdk , facebook has disabled the feature that let you access some one friends list due to security reasons ... check the documentation to learn more ...

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

I simply needed to update my project's dependencies and then restart the server.

How to force view controller orientation in iOS 8?

If you are using navigationViewController you should create your own superclass for this and override:

- (BOOL)shouldAutorotate {
  id currentViewController = self.topViewController;

  if ([currentViewController isKindOfClass:[SecondViewController class]])
    return NO;

  return YES;
}

this will disable rotation in SecondViewController but if you push your SecondViewController when your device is on portrait orientation then your SecondViewController will appear in portrait mode.

Assume that you are using storyboard. You have to create manual segue (How to) and in your "onClick" method:

- (IBAction)onPlayButtonClicked:(UIBarButtonItem *)sender {
  NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
  [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  [self performSegueWithIdentifier:@"PushPlayerViewController" sender:self];
}

This will force landscape orientation before your superclass disable autorotate feature.

How to convert this var string to URL in Swift

To Convert file path in String to NSURL, observe the following code

var filePathUrl = NSURL.fileURLWithPath(path)

Assign null to a SqlParameter

I use a simple method with a null check.

    public SqlParameter GetNullableParameter(string parameterName, object value)
    {
        if (value != null)
        {
            return new SqlParameter(parameterName, value);
        }
        else
        {
            return new SqlParameter(parameterName, DBNull.Value);
        }
    }

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Python MYSQL update statement

It should be:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

You can also do it with basic string manipulation,

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))

but this way is discouraged because it leaves you open for SQL Injection. As it's so easy (and similar) to do it the right waytm. Do it correctly.

The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).

How do I change a PictureBox's image?

If you have an image imported as a resource in your project there is also this:

picPreview.Image = Properties.Resources.ImageName;

Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.

*Resources are located by going to: Project --> Properties --> Resources

Installing TensorFlow on Windows (Python 3.6.x)

If you are using anaconda distribution, you can do the following to use python 3.5 on the new environnement "tensorflow":

conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
# or
# pip install tensorflow-gpu

It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.

Source: https://github.com/tensorflow/tensorflow/issues/6999#issuecomment-278459224

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

Why does integer division in C# return an integer and not a float?

It's just a basic operation.

Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.

9 / 6 == 1  //true
9 % 6 == 3 // true

The /-operator in combination with the %-operator are used to retrieve those values.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client

gem install jenkins_api_client

require "rubygems"
require "jenkins_api_client"

# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
  :server_ip => "127.0.0.1",
  :username => "awesomeuser",
  :password => "awesomepassword"
)

# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
  client.job.create_freestyle(:name => "test_job_#{num}")
end

# The jobs in Jenkins can be listed using
client.job.list_all

The API client can be used to perform a lot of operations.

How to make Unicode charset in cmd.exe by default?

After I tried algirdas' solution, my Windows crashed (Win 7 Pro 64bit) so I decided to try a different solution:

  1. Start Run (Win+R)
  2. Type cmd /K chcp 65001

You will get mostly what you want. To start it from the taskbar or anywhere else, make a shortcut (you can name it cmd.unicode.exe or whatever you like) and change its Target to C:\Windows\System32\cmd.exe /K chcp 65001.

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

Generate table relationship diagram from existing schema (SQL Server)

Try DBVis - download at https://www.dbvis.com/download - there is a pro version (not needed) and a open version that should suffice.

All you have to do is to get the right JDBC - database driver for SQL Server, the tool shows tables and references orthogonal, hierarchical, in a circle ;-) etc. just by pressing one single button. I use the free version for years now.

disable all form elements inside div

For jquery 1.6+, use .prop() instead of .attr(),

$("#parent-selector :input").prop("disabled", true);

or

$("#parent-selector :input").attr("disabled", "disabled");

How to POST using HTTPclient content type = application/x-www-form-urlencoded

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

Or

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);

Best way to get value from Collection by index

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = World
elem = Hello
myCollection.toArray()[0] = World

whilst:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello

Why do you want to do this? Could you not just iterate over the collection?

Sending JSON to PHP using ajax

just remove:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.

FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment

MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4 package.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

        @Override
        public int getCount() {
            return 5;
        }       
    }
}

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

first_frag.xml

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

    <TextView
        android:id="@+id/tvFragFirst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />
</RelativeLayout>

SecondFragment.java

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

second_frag.xml

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

    <TextView
        android:id="@+id/tvFragSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

ThirdFragment.java

public class ThirdFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragThird);      
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

third_frag.xml

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

    <TextView
        android:id="@+id/tvFragThird"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;

}

/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }
    }

    return hasAllPermissions;

}

And to call it:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.INTERNET,
        });

AngularJS ngClass conditional

Using function with ng-class is a good option when someone has to run complex logic to decide the appropriate CSS class.

http://jsfiddle.net/ms403Ly8/2/

HTML:

<div ng-app>
  <div ng-controller="testCtrl">
        <div ng-class="getCSSClass()">Testing ng-class using function</div>       
    </div>
</div>

CSS:

.testclass { Background: lightBlue}

JavaScript:

function testCtrl($scope) {
    $scope.getCSSClass = function() {
     return "testclass ";
  }     
}

What is the benefit of zerofill in MySQL?

One example in order to understand, where the usage of ZEROFILL might be interesting:

In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337 is a valid zipcode for munic, 01067 is a zipcode of Berlin.

As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067 looks strange.

In order to store those data, you could use a VARCHAR(5) or INT(5) ZEROFILL whereas the zerofilled integer has two big advantages:

  1. Lot lesser storage space on hard disk
  2. If you insert 1067, you still get 01067 back

Maybe this example helps understanding the use of ZEROFILL.

How to make the main content div fill height of screen with css

Not sure exactly what your after, but I think I get it.

A header - stays at the top of the screen? A footer - stays at the bottom of the screen? Content area -> fits the space between the footer and the header?

You can do this by absolute positioning or with fixed positioning.

Here is an example with absolute positioning: http://jsfiddle.net/FMYXY/1/

Markup:

<div class="header">Header</div>
<div class="mainbody">Main Body</div>
<div class="footer">Footer</div>

CSS:

.header {outline:1px solid red; height: 40px; position:absolute; top:0px; width:100%;}
.mainbody {outline:1px solid green; min-height:200px; position:absolute; top:40px; width:100%; height:90%;}
.footer {outline:1px solid blue; height:20px; position:absolute; height:25px;bottom:0; width:100%; } 

To make it work best, I'd suggest using % instead of pixels, as you will run into problems with different screen/device sizes.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I also came across this issue trying to push via https to a repo using a self-signed SSL certificate.

The solution for me was running (from the local repository root):

git config http.sslVerify false

How do I run a VBScript in 32-bit mode on a 64-bit machine?

Alternate method to run 32-bit scripts on 64-bit machine: %windir%\syswow64\cscript.exe vbscriptfile.vbs

Delete specific line number(s) from a text file using sed?

$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

ActivityCompat.requestPermissions not showing dialog box

Here's an example of using requestPermissions():

First, define the permission (as you did in your post) in the manifest, otherwise, your request will automatically be denied:

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

Next, define a value to handle the permission callback, in onRequestPermissionsResult():

private final int REQUEST_PERMISSION_PHONE_STATE=1;

Here's the code to call requestPermissions():

private void showPhoneStatePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.READ_PHONE_STATE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        } else {
            requestPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        }
    } else {
        Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
    }
}

First, you check if you already have permission (remember, even after being granted permission, the user can later revoke the permission in the App Settings.)

And finally, this is how you check if you received permission or not:

@Override
public void onRequestPermissionsResult(
        int requestCode,
        String permissions[],
        int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PERMISSION_PHONE_STATE:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
            }
    }
}

private void showExplanation(String title,
                             String message,
                             final String permission,
                             final int permissionRequestCode) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    requestPermission(permission, permissionRequestCode);
                }
            });
    builder.create().show();
}

private void requestPermission(String permissionName, int permissionRequestCode) {
    ActivityCompat.requestPermissions(this,
            new String[]{permissionName}, permissionRequestCode);
}

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Disable future dates after today in Jquery Ui Datepicker

datepicker doesnot have a maxDate as an option.I used this endDate option.It worked well.

> $('.demo-calendar-default').datepicker({
>                 autoHide: true,
>                 zIndex: 2048,
>                 format: 'dd/mm/yyyy',
>                 endDate: new Date()
>             });

java.lang.IllegalStateException: The specified child already has a parent

This solution can help :

public class FragmentItem extends Android.Support.V4.App.Fragment
{
    View rootView;
    TextView textView;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) 
        {
            ViewGroup parent = (ViewGroup)rootView.Parent;
            parent.RemoveView(rootView);
        } else {
            rootView = inflater.Inflate(Resource.Layout.FragmentItem, container, false);
            textView = rootView.FindViewById<TextView>(Resource.Id.textViewDisplay);            
        }
        return rootView;
    }
}

Element-wise addition of 2 lists?

I haven't timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

Put quotes around a variable string in JavaScript

This can be one of several solutions:

var text = "http://example.com";

JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')

SyntaxError: missing ) after argument list

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

Cycles in an Undirected Graph

By the way, if you happen to know that it is connected, then simply it is a tree (thus no cycles) if and only if |E|=|V|-1. Of course that's not a small amount of information :)

Ordering by specific field value first

Use this:

SELECT * 
FROM tablename 
ORDER BY priority desc, FIELD(name, "core")

What is the best method of handling currency/money?

You can pass some options to number_to_currency (a standard Rails 4 view helper):

number_to_currency(12.0, :precision => 2)
# => "$12.00"

As posted by Dylan Markow

How do I pass a class as a parameter in Java?

This kind of thing is not easy. Here is a method that calls a static method:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

Trying to mock datetime.date.today(), but not working

Several solutions are discussed in http://blog.xelnor.net/python-mocking-datetime/. In summary:

Mock object - Simple and efficient but breaks isinstance() checks:

target = datetime.datetime(2009, 1, 1)
with mock.patch.object(datetime, 'datetime', mock.Mock(wraps=datetime.datetime)) as patched:
    patched.now.return_value = target
    print(datetime.datetime.now())

Mock class

import datetime
import mock

real_datetime_class = datetime.datetime

def mock_datetime_now(target, dt):
    class DatetimeSubclassMeta(type):
        @classmethod
        def __instancecheck__(mcs, obj):
            return isinstance(obj, real_datetime_class)

    class BaseMockedDatetime(real_datetime_class):
        @classmethod
        def now(cls, tz=None):
            return target.replace(tzinfo=tz)

        @classmethod
        def utcnow(cls):
            return target

    # Python2 & Python3 compatible metaclass
    MockedDatetime = DatetimeSubclassMeta('datetime', (BaseMockedDatetime,), {})

    return mock.patch.object(dt, 'datetime', MockedDatetime)

Use as:

with mock_datetime_now(target, datetime):
   ....

Breaking to a new line with inline-block?

Set the items into display: inline and use :after:

.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }

and add the class into your html spans:

<span class="medium break-after">We</span>

Initializing an Array of Structs in C#

Are you using C# 3.0? You can use object initializers like so:

static MyStruct[] myArray = 
            new MyStruct[]{
                new MyStruct() { id = 1, label = "1" },
                new MyStruct() { id = 2, label = "2" },
                new MyStruct() { id = 3, label = "3" }
            };

How to clear the Entry widget after a button is pressed in Tkinter?

After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height=42, width=42)
        self.entry = tk.Entry(self)
        self.entry.focus()
        self.entry.pack()
        self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
        self.clear_button.pack()

    def clear_text(self):
        self.entry.delete(0, 'end')

def main():
    root = tk.Tk()
    App(root).pack(expand=True, fill='both')
    root.mainloop()

if __name__ == "__main__":
    main()

How to validate an Email in PHP?

Stay away from regex and filter_var() solutions for validating email. See this answer: https://stackoverflow.com/a/42037557/953833

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Python 3.4.0 with MySQL database

sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient

that worked for me!

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

How to name variables on the fly?

And this option?

list_name<-list()
for(i in 1:100){
    paste("orca",i,sep="")->list_name[[i]]
}

It works perfectly. In the example you put, first line is missing, and then gives you the error message.

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

In case you're coming from a google search, make sure that you have a .env file in which APP_ENV is set to local. (if you cloned a project from github, the first thing is to run cp .env.example .env. That was actually the problem in my case)

Then run composer install again.

UITextView that expands to text using auto layout

Here's a solution for people who prefer to do it all by auto layout:

In Size Inspector:

  1. Set content compression resistance priority vertical to 1000.

  2. Lower the priority of constraint height by click "Edit" in Constraints. Just make it less than 1000.

enter image description here

In Attributes Inspector:

  1. Uncheck "Scrolling Enabled"

Build a simple HTTP server in C

The HTTP spec and Firebug were very useful for me when I had to do it for my homework.

Good luck with yours. :)

How to get current route

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

Where can I download IntelliJ IDEA Color Schemes?

Blue forrest makes for a very good dark theme, because it has appealing blues with yellows and greens mixed in. Highly recommended.

http://www.decodified.com/misc/2011/06/15/blueforest-a-dark-color-scheme-for-intellij-idea.html

Create a view with ORDER BY clause

From Sql 2012 you can force ordering in views and subqueries with OFFSET

SELECT      C.CustomerID,
            C.CustomerName,
            C.CustomerAge
FROM        dbo.Customer C
ORDER BY    CustomerAge OFFSET 0 ROWS;

Warning: this should only be used on small lists because OFFSET forces the full view to be evaluated even if further joins or filters on the view reduce its size!

There is no good way to force ordering in a view without a side effect really and for good reason.

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

How to draw circle in html page?

You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:

<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;">&nbsp;</div>

(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)

There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.

Connect to sqlplus in a shell script and run SQL scripts

If you want to redirect the output to a log file to look for errors or something. You can do something like this.

sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

To analyze a query you already have entered into the Query editor, you need to choose "Include Actual Execution Plan" (7th toggle button to the right of the "! Execute" button). After executing the query, you need to click on the "Execution Plan" tab in the results pane at the bottom (above the results of the query).

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

This worked with me: Eclipse will not open due to environment variables


Let eclipse use your java vm directly!

Put these lines at the end of eclipse.ini (located in the directory where eclipse.exe is present):

-vm
<your path to jdk|jre>/bin/javaw.exe

Pay attention that there are two lines. Also make sure that the -vm option is before the -vmargs option (and of course after "openFile").

How to calculate the difference between two dates using PHP?

I'd like to bring a slightly different perspective, which seemingly hasn't been mentioned.

You could solve this problem (just like any other) in a declarative way. The point is asking what you need, not how to get there.

Here, you need a difference. But what is that difference? It's an interval, as already mentioned in the most upvoted answer. The thing is how to get it. Instead of explicitly invoking diff() method, you could just create an interval by start date and finish date, that is, by date range:

$startDate = '2007-03-24';
$endDate = '2009-06-26';
$range = new FromRange(new ISO8601DateTime($startDate), new ISO8601DateTime($endDate));

All the intricacies such as a leap year and all are already taken care of. Now when you have an interval with fixed start datetime, you can get a human-readable version:

var_dump((new HumanReadable($range))->value());

It outputs exactly what you need.

If you need some customized format, it's not a problem either. You can use a ISO8601Formatted class which accepts a callable with six arguments: year, month, day, hour, minute, and second:

(new ISO8601Formatted(
    new FromRange(
        new ISO8601DateTime('2017-07-03T14:27:39+00:00'),
        new ISO8601DateTime('2018-07-05T14:27:39.235487+00:00')
    ),
    function (int $years, int $months, int $days, int $hours, int $minutes, int $seconds) {
        return $years >= 1 ? 'More than a year' : 'Less than a year';
    }
))
    ->value();

It outputs More than a year.

For more about this approach, take a look at a quick start entry.

How to display Wordpress search results?

you need to include the Wordpress loop in your search.php this is example

search.php template file:

<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

How to split a dataframe string column into two columns?

TL;DR version:

For the simple case of:

  • I have a text column with a delimiter and I want two columns

The simplest solution is:

df[['A', 'B']] = df['AB'].str.split(' ', 1, expand=True)

You must use expand=True if your strings have a non-uniform number of splits and you want None to replace the missing values.

Notice how, in either case, the .tolist() method is not necessary. Neither is zip().

In detail:

Andy Hayden's solution is most excellent in demonstrating the power of the str.extract() method.

But for a simple split over a known separator (like, splitting by dashes, or splitting by whitespace), the .str.split() method is enough1. It operates on a column (Series) of strings, and returns a column (Series) of lists:

>>> import pandas as pd
>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2']})
>>> df

      AB
0  A1-B1
1  A2-B2
>>> df['AB_split'] = df['AB'].str.split('-')
>>> df

      AB  AB_split
0  A1-B1  [A1, B1]
1  A2-B2  [A2, B2]

1: If you're unsure what the first two parameters of .str.split() do, I recommend the docs for the plain Python version of the method.

But how do you go from:

  • a column containing two-element lists

to:

  • two columns, each containing the respective element of the lists?

Well, we need to take a closer look at the .str attribute of a column.

It's a magical object that is used to collect methods that treat each element in a column as a string, and then apply the respective method in each element as efficient as possible:

>>> upper_lower_df = pd.DataFrame({"U": ["A", "B", "C"]})
>>> upper_lower_df

   U
0  A
1  B
2  C
>>> upper_lower_df["L"] = upper_lower_df["U"].str.lower()
>>> upper_lower_df

   U  L
0  A  a
1  B  b
2  C  c

But it also has an "indexing" interface for getting each element of a string by its index:

>>> df['AB'].str[0]

0    A
1    A
Name: AB, dtype: object

>>> df['AB'].str[1]

0    1
1    2
Name: AB, dtype: object

Of course, this indexing interface of .str doesn't really care if each element it's indexing is actually a string, as long as it can be indexed, so:

>>> df['AB'].str.split('-', 1).str[0]

0    A1
1    A2
Name: AB, dtype: object

>>> df['AB'].str.split('-', 1).str[1]

0    B1
1    B2
Name: AB, dtype: object

Then, it's a simple matter of taking advantage of the Python tuple unpacking of iterables to do

>>> df['A'], df['B'] = df['AB'].str.split('-', 1).str
>>> df

      AB  AB_split   A   B
0  A1-B1  [A1, B1]  A1  B1
1  A2-B2  [A2, B2]  A2  B2

Of course, getting a DataFrame out of splitting a column of strings is so useful that the .str.split() method can do it for you with the expand=True parameter:

>>> df['AB'].str.split('-', 1, expand=True)

    0   1
0  A1  B1
1  A2  B2

So, another way of accomplishing what we wanted is to do:

>>> df = df[['AB']]
>>> df

      AB
0  A1-B1
1  A2-B2

>>> df.join(df['AB'].str.split('-', 1, expand=True).rename(columns={0:'A', 1:'B'}))

      AB   A   B
0  A1-B1  A1  B1
1  A2-B2  A2  B2

The expand=True version, although longer, has a distinct advantage over the tuple unpacking method. Tuple unpacking doesn't deal well with splits of different lengths:

>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2', 'A3-B3-C3']})
>>> df
         AB
0     A1-B1
1     A2-B2
2  A3-B3-C3
>>> df['A'], df['B'], df['C'] = df['AB'].str.split('-')
Traceback (most recent call last):
  [...]    
ValueError: Length of values does not match length of index
>>> 

But expand=True handles it nicely by placing None in the columns for which there aren't enough "splits":

>>> df.join(
...     df['AB'].str.split('-', expand=True).rename(
...         columns={0:'A', 1:'B', 2:'C'}
...     )
... )
         AB   A   B     C
0     A1-B1  A1  B1  None
1     A2-B2  A2  B2  None
2  A3-B3-C3  A3  B3    C3

Java - escape string to prevent SQL injection

PreparedStatements are the way to go in most, but not all cases. Sometimes you will find yourself in a situation where a query, or a part of it, has to be built and stored as a string for later use. Check out the SQL Injection Prevention Cheat Sheet on the OWASP Site for more details and APIs in different programming languages.

Sequel Pro Alternative for Windows

Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).

From the website:

Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

If the new data could be an array or a scalar, and you want to prevent the new data to be nested if it was an array, the splat operator is awesome! It returns a scalar for a scalar, and an unpacked list of arguments for an array.

1.9.3-p551 :020 > a = [1, 2]
 => [1, 2] 
1.9.3-p551 :021 > b = [3, 4]
 => [3, 4] 
1.9.3-p551 :022 > c = 5
 => 5 
1.9.3-p551 :023 > a.object_id
 => 6617020 
1.9.3-p551 :024 > a.push *b
 => [1, 2, 3, 4] 
1.9.3-p551 :025 > a.object_id
 => 6617020 
1.9.3-p551 :026 > a.push *c
 => [1, 2, 3, 4, 5] 
1.9.3-p551 :027 > a.object_id
 => 6617020 

How do I add a linker or compile flag in a CMake file?

You can also add linker flags to a specific target using the LINK_FLAGS property:

set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")

If you want to propagate this change to other targets, you can create a dummy target to link to.

What's the equivalent of Java's Thread.sleep() in JavaScript?

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));
}

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.

For a full explanation see:

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

composer dump-autoload

PATH vendor/composer/autoload_classmap.php
  • Composer dump-autoload won’t download a thing.
  • It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
  • Ideal for when you have a new class inside your project.
  • autoload_classmap.php also includes the providers in config/app.php

php artisan dump-autoload

  • It will call Composer with the optimize flag
  • It will 'recompile' loads of files creating the huge bootstrap/compiled.php

Why does my Spring Boot App always shutdown immediately after starting?

Just another possibility,

I replaced

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

with

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

and it started without any issues

Text overwrite in visual studio 2010

Visual Studio : Right Bottom : Look for OVR label. Double Click on it.

Bingo...

Best way to iterate through a Perl array

The best way to decide questions like this to benchmark them:

use strict;
use warnings;
use Benchmark qw(:all);

our @input_array = (0..1000);

my $a = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    foreach my $element (@array) {
       die unless $index == $element;
       $index++;
    }
};

my $b = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (defined(my $element = shift @array)) {
       die unless $index == $element;
       $index++;
    }
};

my $c = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (scalar(@array) !=0) {
       my $element = shift(@array);
       die unless $index == $element;
       $index++;
    }
};

my $d = sub {
    my @array = @{[ @input_array ]};
    foreach my $index (0.. $#array) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $e = sub {
    my @array = @{[ @input_array ]};
    for (my $index = 0; $index <= $#array; $index++) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $f = sub {
    my @array = @{[ @input_array ]};
    while (my ($index, $element) = each @array) {
       die unless $index == $element;
    }
};

my $count;
timethese($count, {
   '1' => $a,
   '2' => $b,
   '3' => $c,
   '4' => $d,
   '5' => $e,
   '6' => $f,
});

And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi

I get:

Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
         1:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 12560.13/s (n=39690)
         2:  3 wallclock secs ( 3.18 usr +  0.00 sys =  3.18 CPU) @ 7828.30/s (n=24894)
         3:  3 wallclock secs ( 3.23 usr +  0.00 sys =  3.23 CPU) @ 6763.47/s (n=21846)
         4:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 CPU) @ 9596.83/s (n=30230)
         5:  4 wallclock secs ( 3.20 usr +  0.00 sys =  3.20 CPU) @ 6826.88/s (n=21846)
         6:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 5653.53/s (n=17639)

So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.

@ikegami also points out that there are quite a few differences in these implimentations other than speed.

is the + operator less performant than StringBuffer.append()

Yes, according to the usual benchmarks. E.G : http://mckoss.com/jscript/SpeedTrial.htm.

But for the small strings, this is irrelevant. You will only care about performances on very large strings. What's more, in most JS script, the bottle neck is rarely on the string manipulations since there is not enough of it.

You'd better watch the DOM manipulation.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

With this you can have the following: Sample Input: 07:05:45PM Sample Output: 19:05:45

function timeConversion(s) {
    let output = '';
    const timeSeparator = ':'
    const timeTokenType = s.substr(s.length - 2 , 2).toLowerCase();
    const timeArr = s.split(timeSeparator).map((timeToken) => {
    const isTimeTokenType = 
          timeToken.toLowerCase().indexOf('am') > 0 ||                                                                                               
           timeToken.toLowerCase().indexOf('pm');
        if(isTimeTokenType){
            return timeToken.substr(0, 2);
        } else {
            return timeToken;
        }
    });
    const hour = timeArr[0];
    const minutes = timeArr[1];
    const seconds = timeArr[2];
    const hourIn24 = (timeTokenType === 'am') ? parseInt(hour) - 12 : 
    parseInt(hour) + 12;
    return hourIn24.toString()+ timeSeparator + minutes + timeSeparator + seconds;
}

Hope you like it !

How to clear react-native cache?

Here's a great discussion on GitHub which helped me a lot. Clearing the Cache of your React Native Project by Jarret Moses

There are solutions for 4 different instances.

  1. RN <0.50 -
    watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  2. RN >=0.50 - watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  3. NPM >=5 - watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache
  4. Windows - del %appdata%\Temp\react-native-* & cd android & gradlew clean & cd .. & del node_modules/ & npm cache clean --force & npm install & npm start -- --reset-cache

The solution is similar to Vikram Biwal's Answer.

And there is a discussion below in the given link, so even if the above 4 cases don't work for you, you can scroll through and find a possible solution.

Why is processing a sorted array faster than processing an unsorted array?

An official answer would be from

  1. Intel - Avoiding the Cost of Branch Misprediction
  2. Intel - Branch and Loop Reorganization to Prevent Mispredicts
  3. Scientific papers - branch prediction computer architecture
  4. Books: J.L. Hennessy, D.A. Patterson: Computer architecture: a quantitative approach
  5. Articles in scientific publications: T.Y. Yeh, Y.N. Patt made a lot of these on branch predictions.

You can also see from this lovely diagram why the branch predictor gets confused.

2-bit state diagram

Each element in the original code is a random value

data[c] = std::rand() % 256;

so the predictor will change sides as the std::rand() blow.

On the other hand, once it's sorted, the predictor will first move into a state of strongly not taken and when the values change to the high value the predictor will in three runs through change all the way from strongly not taken to strongly taken.


Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

How can I revert a single file to a previous version?

You can take a diff that undoes the changes you want and commit that.

E.g. If you want to undo the changes in the range from..to, do the following

git diff to..from > foo.diff  # get a reverse diff
patch < foo.diff
git commit -a -m "Undid changes from..to".

Pythonically add header to a csv file

You just add one additional row before you execute the loop. This row contains your CSV file header name.

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:    
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])   
#Data add in csv file       
     for x in xrange(rows):
         writer.writerow([g() for g in generators])

How can I create directories recursively?

Try using os.makedirs:

import os
import errno

try:
    os.makedirs(<path>)
except OSError as e:
    if errno.EEXIST != e.errno:
        raise

node.js Error: connect ECONNREFUSED; response from server

Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.

const request = require('request');

   let json = {
        "id": id,
        "filename": filename
    };
    let options = {
        uri: "http://[::1]:8000" + constants.PATH_TO_API,
        // port:443,
        method: 'POST',
        json: json
    };
    request(options, function (error, response, body) {
        if (error) {
            console.error("httpRequests : error " + error);
        }
        if (response) {
            let statusCode = response.status_code;
            if (callback) {
                callback(body);
            }
        }
    });

Tomcat manager/html is not available?

I had the situatuion when tomcat manager did not start. I had this exception in my logs/manager.DDD-MM-YY.log:

org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter CSRF
java.lang.ClassNotFoundException: org.apache.catalina.filters.CsrfPreventionFilter
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        ...

This exception was raised because I used a version of tomcat that hadn't CSRF prevention filter. Tomcat 6.0.24 doesn't have the CSRF prevention filter in it. The first version that has it is the 6.0.30 version (at least. according to the changelog). As a result, Tomcat Manager was uncompatible with version of Tomcat that I used. I've digged description of this issue here: http://blog.techstacks.com/.m/2009/05/tomcat-management-setting-up-tomcat/comments/

Steps to fix it:

  1. Check version of tomcat installed by running "sh version.sh" from your tomcat/bin directory
  2. Download corresponding version of tomcat
  3. Stop tomcat
  4. Remove your webapps/manager directory and copy manager application from distributive that you've downloaded.
  5. Start tomcat

Now you should be able to access tomcat manager.

How to initialize a List<T> to a given size (as opposed to capacity)?

This is an old question, but I have two solutions. One is fast and dirty reflection; the other is a solution that actually answers the question (set the size not the capacity) while still being performant, which none of the answers here do.


Reflection

This is quick and dirty, and should be pretty obvious what the code does. If you want to speed it up, cache the result of GetField, or create a DynamicMethod to do it:

public static void SetSize<T>(this List<T> l, int newSize) =>
    l.GetType().GetField("_size", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(l, 10);

Obviously a lot of people will be hesitant to put such code into production.


ICollection<T>

This solution is based around the fact that the constructor List(IEnumerable<T> collection) optimizes for ICollection<T> and immediately adjusts the size to the correct amount, without iterating it. It then calls the collections CopyTo to do the copy.

The code is as follows:

public List(IEnumerable<T> collection) {
....
    ICollection<T> c = collection as ICollection<T>;
    if (collection is ICollection<T> c)
    {
        int count = c.Count;
        if (count == 0)
        {
            _items = s_emptyArray;
        }
        else {
            _items = new T[count];
            c.CopyTo(_items, 0);
            _size = count;
        }
    }    

So we can completely optimally pre-initialize the List to the correct size, without any extra copying.

How so? By creating an ICollection<T> object that does nothing other than return a Count. Specifically, we will not implement anything in CopyTo which is the only other function called.

private class SizeCollection<T> : ICollection<T>
{
    public SizeCollection(int size) =>
        Count = size;

    public void Add(T i){}
    public void Clear(){}
    public bool Contains(T i)=>true;
    public void CopyTo(T[]a, int i){}
    public bool Remove(T i)=>true;
    public int Count {get;}
    public bool IsReadOnly=>true;
    public IEnumerator<T> GetEnumerator()=>null;
    IEnumerator IEnumerable.GetEnumerator()=>null;
}

public List<T> InitializedList<T>(int size) =>
    new List<T>(new SizeCollection<T>(size));

We could in theory do the same thing for AddRange/InsertRange for an existing array, which also accounts for ICollection<T>, but the code there creates a new array for the supposed items, then copies them in. In such case, it would be faster to just empty-loop Add:

public void SetSize<T>(this List<T> l, int size)
{
    if(size < l.Count)
        l.RemoveRange(size, l.Count - size);
    else
        for(size -= l.Count; size > 0; size--)
            l.Add(default(T));
}

Remove substring from the string

If it is a the end of the string, you can also use chomp:

"hello".chomp("llo")     #=> "he"

SQL Query for Student mark functionality

Select S.StudentName 
From Student S 
where S.StudentID IN 
    (Select StudentID from (
        ( Select Max(MarkRate)as MarkRate,SubjectID From  Mark Group by SubjectID)) MaxMarks, Mark
 where MaxMarks.SubjectID= Mark.SubjectID AND MaxMarks.MarkRate=Mark.MarkRate)

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

No module named pkg_resources

In my case, I had 2 python versions installed initially and later I had deleted the older one. So while creating the virtual environment

virtualenv venv

was referring to the uninstalled python

What worked for me

python3 -m virtualenv venv

Same is true when you are trying to use pip.

Reading Datetime value From Excel sheet

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:

excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
    Date: {21/02/2013 00:00:00}
    Day: 21
    DayOfWeek: Thursday
    DayOfYear: 52
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 2
    Second: 0
    Ticks: 634970016000000000
    TimeOfDay: {00:00:00}
    Year: 2013

excelApp.Range[namedRange].Value2
41326.0

Detect if page has finished loading

One option is to have the page be blank, containing a small amount of javascript. Use the script to make an AJAX call to get the actual page content, and have the success function write the result over the current document. In the timeout function you can "do something else amazing"

Approximate pseudocode:

$(document).ready(function(){
    $.ajax
      url of actual page
      success:do something amazing
      timeout: do something else
});

How to extract week number in sql

After converting your varchar2 date to a true date datatype, then convert back to varchar2 with the desired mask:

to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')

If you want the week number in a number datatype, you can wrap the statement in to_number():

to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))

However, you have several week number options to consider:

WW  Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W   Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW  Week of year (1-52 or 1-53) based on the ISO standard.

How can I iterate over an enum?

In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the operator++ for your specific enum. enum are user-defined types and overloading operator exists in the language for these specific situations.

You'll be able to code the following:

#include <iostream>
enum class Colors{red, green, blue};
Colors& operator++(Colors &c, int)
{
     switch(c)
     {
           case Colors::red:
               return c=Colors::green;
           case Colors::green:
               return c=Colors::blue;
           case Colors::blue:
               return c=Colors::red; // managing overflow
           default:
               throw std::exception(); // or do anything else to manage the error...
     }
}

int main()
{
    Colors c = Colors::red;
    // casting in int just for convenience of output. 
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    return 0;
}

test code: http://cpp.sh/357gb

Mind that I'm using enum class. Code works fine with enum also. But I prefer enum class since they are strong typed and can prevent us to make mistake at compile time.

Calling a rest api with username and password - how to

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

Changing image on hover with CSS/HTML

The problem is that you set the first image through 'src' attribute and on hover added to the image a background-image. try this:

in html use:

<img id="Library">

then in css:

#Library {
    height: 70px;
    width: 120px;
    background-image: url('LibraryTransparent.png');
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
}

iOS 7's blurred overlay effect using CSS?

This might help you!!

This Dynamically changes the background just IOS does

.myBox {
  width: 750px;
  height: 500px;
  border: rgba(0, 0, 0, 0.5) 1px solid;
  background-color: #ffffff;
}

.blurBg {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.blurBg img {
  -webkit-filter: blur(50px);
  margin-top: -150px;
  margin-left: -150px;
  width: 150%;
  opacity: 0.6;
}

How do I update an entity using spring-data-jpa?

Identity of entities is defined by their primary keys. Since firstname and lastname are not parts of the primary key, you cannot tell JPA to treat Users with the same firstnames and lastnames as equal if they have different userIds.

So, if you want to update a User identified by its firstname and lastname, you need to find that User by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don't need to do anything to save these changes explicitly.

EDIT:

Perhaps I should elaborate on overall semantics of JPA. There are two main approaches to design of persistence APIs:

  • insert/update approach. When you need to modify the database you should call methods of persistence API explicitly: you call insert to insert an object, or update to save new state of the object to the database.

  • Unit of Work approach. In this case you have a set of objects managed by persistence library. All changes you make to these objects will be flushed to the database automatically at the end of Unit of Work (i.e. at the end of the current transaction in typical case). When you need to insert new record to the database, you make the corresponding object managed. Managed objects are identified by their primary keys, so that if you make an object with predefined primary key managed, it will be associated with the database record of the same id, and state of this object will be propagated to that record automatically.

JPA follows the latter approach. save() in Spring Data JPA is backed by merge() in plain JPA, therefore it makes your entity managed as described above. It means that calling save() on an object with predefined id will update the corresponding database record rather than insert a new one, and also explains why save() is not called create().

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to access the php.ini file in godaddy shared hosting linux

I found a guide to reload the php5.ini file or load a new one right away. You will need to access your Godaddy hosting panel where you will find the option "system process" do a restart there and it will load the php5.ini or php.ini file right away.

2 external guides to assist you:

http://support.godaddy.com/help/article/5980/managing-system-processes-on-linux-hosting-accounts

http://www.studio-owens.com/blog/GoDaddy-and-Your-php-ini-File.htm

When to use Hadoop, HBase, Hive and Pig?

Short answer to this question is -

Hadoop - Is Framework which facilitates distributed file system and programming model which allow us to store humongous sized data and process data in distributed fashion very efficiently and with very less processing time compare to traditional approaches.

(HDFS - Hadoop Distributed File system) (Map Reduce - Programming Model for distributed processing)

Hive - Is query language which allows to read/write data from Hadoop distributed file system in a very popular SQL like fashion. This made life easier for many non-programming background people as they don't have to write Map-Reduce program anymore except for very complex scenarios where Hive is not supported.

Hbase - Is Columnar NoSQL Database. Underlying storage layer for Hbase is again HDFS. Most important use case for this database is to be able to store billion's of rows with million's of columns. Low latency feature of Hbase helps faster and random access of record over distributed data, is very important feature to make it useful for complex projects like Recommender Engines. Also it's record level versioning capability allow user to store transactional data very efficiently (this solves the problem of updating records we have with HDFS and Hive)

Hope this is helpful to quickly understand the above 3 features.

HTML inside Twitter Bootstrap popover

You cannot use <li href="#" since it belongs to <a href="#" that's why it wasn't working, change it and it's all good.

Here is working JSFiddle which shows you how to create bootstrap popover.

Relevant parts of the code is below:

HTML:

<!-- 
Note: Popover content is read from "data-content" and "title" tags.
-->
<a tabindex="0"
   class="btn btn-lg btn-primary" 
   role="button" 
   data-html="true" 
   data-toggle="popover" 
   data-trigger="focus" 
   title="<b>Example popover</b> - title" 
   data-content="<div><b>Example popover</b> - content</div>">Example popover</a>

JavaScript:

$(function(){
    // Enables popover
    $("[data-toggle=popover]").popover();
});

And by the way, you always need at least $("[data-toggle=popover]").popover(); to enable the popover. But in place of data-toggle="popover" you can also use id="my-popover" or class="my-popover". Just remember to enable them using e.g: $("#my-popover").popover(); in those cases.

Here is the link to the complete spec: Bootstrap Popover

Bonus:

If for some reason you don't like or cannot read content of a popup from the data-content and title tags. You can also use e.g. hidden divs and a bit more JavaScript. Here is an example about that.

Easiest way to detect Internet connection on iOS?

I extracted the code and put into one single method, hope it would help others.

#import <SystemConfiguration/SystemConfiguration.h>

#import <netinet/in.h>
#import <netinet6/in6.h>

...

- (BOOL)isInternetReachable
{    
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    if(reachability == NULL)
        return false;

    if (!(SCNetworkReachabilityGetFlags(reachability, &flags)))
        return false;

    if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
        // if target host is not reachable
        return false;


    BOOL isReachable = false;


    if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
    {
        // if target host is reachable and no connection is required
        //  then we'll assume (for now) that your on Wi-Fi
        isReachable = true;
    }


    if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
         (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
    {
        // ... and the connection is on-demand (or on-traffic) if the
        //     calling application is using the CFSocketStream or higher APIs

        if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
        {
            // ... and no [user] intervention is needed
            isReachable = true;
        }
    }

    if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
    {
        // ... but WWAN connections are OK if the calling application
        //     is using the CFNetwork (CFSocketStream?) APIs.
        isReachable = true;
    }


    return isReachable;


}

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

Checking if an Android application is running in the background

Activity gets paused when a Dialog comes above it so all the recommended solutions are half-solutions. You need to create hooks for dialogs as well.

Dynamic Web Module 3.0 -- 3.1

If you want to use version 3.1 you need to use the following schema:

  • http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd

Note that 3.0 and 3.1 are different: in 3.1 there's no Sun mentioned, so simply changing 3_0.xsd to 3_1.xsd won't work.

This is how it should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

</web-app>

Also, make sure you're depending on the latest versions in your pom.xml. That is,

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        ...
    </configuration>
</plugin>

and

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Finally, you should compile with Java 7 or 8:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
    </configuration>
</plugin>

is inaccessible due to its protection level

The reason being you can not access protected member data through the instance of the class.

Reason why it is not allowed is explained in this blog

How do you run a single test/spec file in RSpec?

Ruby 1.9.2 and Rails 3 have an easy way to run one spec file:

  ruby -I spec spec/models/user_spec.rb

Explanation:

  • ruby command tends to be faster than the rake command
  • -I spec means "include the 'spec' directory when looking for files"
  • spec/models/user_spec.rb is the file we want to run.

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

extract date only from given timestamp in oracle sql

Use the function cast() to convert from timestamp to date

select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;

For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256

OTP (token) should be automatically read from the message

**activity_main.xml**

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mukundwn.broadcastreceiver.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>



**MainActivity.java**
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver broadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        broadcastReceiver =new MyBroadcastReceiver();
    }

@Override
    protected void onStart()
{
    super.onStart();
    IntentFilter intentFilter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(broadcastReceiver,intentFilter);
}
@Override
    protected void onStop()
{
    super.onStop();
    unregisterReceiver(broadcastReceiver);
}

}


**MyBroadcastReceiver.java**

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by mukundwn on 12/02/18.
 */

public class MyBroadcastReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"hello received an sms",Toast.LENGTH_SHORT).show();
    }
}


**Manifest.xml**

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mukundwn.broadcastreceiver">

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVE"></action>
        </intent-filter>
        </receiver>
    </application>

</manifest>

How to use find command to find all files with extensions from list?

On Mac OS use

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

update to python 3.7 using anaconda

Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.


Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.

You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/

In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.

How to configure PHP to send e-mail?

configure your php.ini like this

SMTP = smtp.gmail.com

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury

; SMTP = smtp.gmail.com

; smtp_port = 465

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

I use .kts Gradle files (Kotlin Gradle DSL) and the kotlin-kapt plugin but I still get a script compilation error when I use Ivanov Maksim's answer.

Unresolved reference: kapt

For me this was the only thing which worked:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = mapOf("room.schemaLocation" to "$projectDir/schemas")
            }
        }
    }
}

How to create my json string by using C#?

To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.

The below code demonstrates the use of JSON in an ASP.NET environment:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace JSONFromCS
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e1)
        {
            List<Employee> eList = new List<Employee>();
            Employee e = new Employee();
            e.Name = "Minal";
            e.Age = 24;

            eList.Add(e);

            e = new Employee();
            e.Name = "Santosh";
            e.Age = 24;

            eList.Add(e);

            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            string script = "var employeeList = {\"Employee\": " + ans+"};";
            script += "for(i = 0;i<employeeList.Employee.length;i++)";
            script += "{";
            script += "alert ('Name : ='+employeeList.Employee[i].Name+' 
            Age : = '+employeeList.Employee[i].Age);";
            script += "}";

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
        }
    }
    public class Employee
    {
        public string Name;
        public int Age;
    }
}  

After running this program, you will get two alerts

In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:

{ "Maths" : [ {"Name"     : "Minal",        // First element
                             "Marks"     : 84,
                             "age"       : 23 },
                             {
                             "Name"      : "Santosh",    // Second element
                             "Marks"     : 91,
                             "age"       : 24 }
                           ],                       
              "Science" :  [ 
                             {
                             "Name"      : "Sahoo",     // First Element
                             "Marks"     : 74,
                             "age"       : 27 }, 
                             {                           
                             "Name"      : "Santosh",    // Second Element
                             "Marks"     : 78,
                             "age"       : 41 }
                           ] 
            } 

Syntax:

  • {} - acts as 'containers'

  • [] - holds arrays

  • : - Names and values are separated by a colon

  • , - Array elements are separated by commas

This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.

You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.

In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.

The following code demonstrates how to use that class to convert into JSON in C#3.5.

JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);   

So, try to create a List of arrays with Questions and then serialize this list into JSON

How to split data into 3 sets (train, validation and test)?

Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split() twice.

import pandas as pd
from sklearn.model_selection import train_test_split

def split_stratified_into_train_val_test(df_input, stratify_colname='y',
                                         frac_train=0.6, frac_val=0.15, frac_test=0.25,
                                         random_state=None):
    '''
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    '''

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
                         (frac_train, frac_val, frac_test))

    if stratify_colname not in df_input.columns:
        raise ValueError('%s is not a column in the dataframe' % (stratify_colname))

    X = df_input # Contains all columns.
    y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(X,
                                                          y,
                                                          stratify=y,
                                                          test_size=(1.0 - frac_train),
                                                          random_state=random_state)

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(df_temp,
                                                      y_temp,
                                                      stratify=y_temp,
                                                      test_size=relative_frac_test,
                                                      random_state=random_state)

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test

Below is a complete working example.

Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo, 15% bar and 10% baz. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:

enter image description here

Here is the example dataset:

df = pd.DataFrame( { 'A': list(range(0, 100)),
                     'B': list(range(100, 0, -1)),
                     'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )

df.head()
#    A    B label
# 0  0  100   foo
# 1  1   99   foo
# 2  2   98   foo
# 3  3   97   foo
# 4  4   96   foo

df.shape
# (100, 3)

df.label.value_counts()
# foo    75
# bar    15
# baz    10
# Name: label, dtype: int64

Now, let's call the split_stratified_into_train_val_test() function from above to get train, validation, and test dataframes following a 60/20/20 ratio.

df_train, df_val, df_test = \
    split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)

The three dataframes df_train, df_val, and df_test contain all the original rows but their sizes will follow the above ratio.

df_train.shape
#(60, 3)

df_val.shape
#(20, 3)

df_test.shape
#(20, 3)

Further, each of the three splits will have the same distribution of the label, namely 75% foo, 15% bar and 10% baz.

df_train.label.value_counts()
# foo    45
# bar     9
# baz     6
# Name: label, dtype: int64

df_val.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

df_test.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

implementing merge sort in C++

This is my version (simple and easy):
uses memory only twice the size of original array.
[ a is the left array ] [ b is the right array ] [ c used to merge a and b ] [ p is counter for c ]

void MergeSort(int list[], int size)
{
    int blockSize = 1, p;
    int *a, *b;
    int *c = new int[size];
    do
    {
        for (int k = 0; k < size; k += (blockSize * 2))
        {
            a = &list[k];
            b = &list[k + blockSize];
            p = 0;
            for (int i = 0, j = 0; i < blockSize || j < blockSize;)
            {
                if ((j < blockSize) && ((k + j + blockSize) >= size))
                {
                    ++j;
                }
                else if ((i < blockSize) && ((k + i) >= size))
                {
                    ++i;
                }
                else if (i >= blockSize)
                {
                    c[p++] = b[j++];
                }
                else if (j >= blockSize)
                {
                    c[p++] = a[i++];
                }
                else if (a[i] >= b[j])
                {
                    c[p++] = b[j++];
                }
                else if (a[i] < b[j])
                {
                    c[p++] = a[i++];
                }
            }
            for (int i = 0; i < p; i++)
            {
                a[i] = c[i];
            }
        }
        blockSize *= 2;
    } while (blockSize < size);
}

How to stick a footer to bottom in css?

I had a similar issue with this sticky footer tutorial. If memory serves, you need to put your form tags within your <div class=Main /> section since the form tag itself causes issues with the lineup.

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

Way to run Excel macros from command line or batch file?

I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.

Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.

  • Full Path to Workbook
  • Macro Name
  • [OPTIONAL] Path to separate workbook with Macro

I tested it like so:

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"

runmacro.vbs:

Set args = Wscript.Arguments

ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
 macrowb= WScript.Arguments.Item(2)
End If

LaunchMacro

Sub LaunchMacro() 
  Dim xl
  Dim xlBook  

  Set xl = CreateObject("Excel.application")
  Set xlBook = xl.Workbooks.Open(ws, 0, True)
  If wscript.arguments.count > 2 Then
   Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
  End If
  'xl.Application.Visible = True ' Show Excel Window
  xl.Application.run macro
  'xl.DisplayAlerts = False  ' suppress prompts and alert messages while a macro is running
  'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
  'xl.activewindow.close
  xl.Quit

End Sub 

Tooltips for cells in HTML table (no Javascript)

The highest-ranked answer by Mudassar Bashir using the "title" attribute seems the easiest way to do this, but it gives you less control over how the comment/tooltip is displayed.

I found that The answer by Christophe for a custom tooltip class seems to give much more control over the behavior of the comment/tooltip. Since the provided demo does not include a table, as per the question, here is a demo that includes a table.

Note that the "position" style for the parent element of the span (a in this case), must be set to "relative" so that the comment does not push the table contents around when it is displayed. It took me a little while to figure that out.

_x000D_
_x000D_
#MyTable{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:2px_x000D_
}_x000D_
_x000D_
#MyTable td{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:1px;_x000D_
  padding:3px;_x000D_
}_x000D_
_x000D_
.CellWithComment{_x000D_
  position:relative;_x000D_
}_x000D_
_x000D_
.CellComment{_x000D_
  display:none;_x000D_
  position:absolute; _x000D_
  z-index:100;_x000D_
  border:1px;_x000D_
  background-color:white;_x000D_
  border-style:solid;_x000D_
  border-width:1px;_x000D_
  border-color:red;_x000D_
  padding:3px;_x000D_
  color:red; _x000D_
  top:20px; _x000D_
  left:20px;_x000D_
}_x000D_
_x000D_
.CellWithComment:hover span.CellComment{_x000D_
  display:block;_x000D_
}
_x000D_
<table id="MyTable">_x000D_
  <caption>Cell 1,2 Has a Comment</caption>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <td>Heading 1</td>_x000D_
      <td>Heading 2</td>_x000D_
      <td>Heading 3</td>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr></tr>_x000D_
      <td>Cell 1,1</td>_x000D_
      <td class="CellWithComment">Cell 1,2_x000D_
        <span class="CellComment">Here is a comment</span>_x000D_
      </td>_x000D_
      <td>Cell 1,3</td>_x000D_
    <tr>_x000D_
      <td>Cell 2,1</td>_x000D_
      <td>Cell 2,2</td>_x000D_
      <td>Cell 2,3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

The server principal is not able to access the database under the current security context in SQL Server MS 2012

We had the same error deploying a report to SSRS in our PROD environment. It was found the problem could even be reproduced with a “use ” statement. The solution was to re-sync the user's GUID account reference with the database in question (i.e., using "sp_change_users_login" like you would after restoring a db). A stock (cursor driven) script to re-sync all accounts is attached:

USE <your database>
GO

-------- Reset SQL user account guids ---------------------
DECLARE @UserName nvarchar(255) 
DECLARE orphanuser_cur cursor for 
      SELECT UserName = su.name 
      FROM sysusers su
      JOIN sys.server_principals sp ON sp.name = su.name
      WHERE issqluser = 1 AND
            (su.sid IS NOT NULL AND su.sid <> 0x0) AND
            suser_sname(su.sid) is null 
      ORDER BY su.name 

OPEN orphanuser_cur 
FETCH NEXT FROM orphanuser_cur INTO @UserName 

WHILE (@@fetch_status = 0)
BEGIN 
--PRINT @UserName + ' user name being resynced' 
exec sp_change_users_login 'Update_one', @UserName, @UserName 
FETCH NEXT FROM orphanuser_cur INTO @UserName 
END 

CLOSE orphanuser_cur 
DEALLOCATE orphanuser_cur

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

How to run code after some delay in Flutter?

Figured it out

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

Sourcetree - undo unpushed commits

If You are on another branch, You need first "check to this commit" for commit you want to delete, and only then "reset current branch to this commit" choosing previous wright commit, will work.

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

Configuring ObjectMapper in Spring

I am using Spring 4.1.6 and Jackson FasterXML 2.1.4.

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <!-- ?????null??-->
                        <property name="serializationInclusion" value="NON_NULL"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

this works at my applicationContext.xml configration

What does the "static" modifier after "import" mean?

The import allows the java programmer to access classes of a package without package qualification.

The static import feature allows to access the static members of a class without the class qualification.

The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.

Example :

With import

import java.lang.System.*;    
class StaticImportExample{  
    public static void main(String args[]){  

       System.out.println("Hello");
       System.out.println("Java");  

  }   
} 

With static import

import static java.lang.System.*;    
class StaticImportExample{  
  public static void main(String args[]){  

   out.println("Hello");//Now no need of System.out  
   out.println("Java");  

 }   
} 

See also : What is static import in Java 5

What is the JavaScript version of sleep()?

I got Promise is not a constructor using the top answer. If you import bluebird you can do this. Simplest solution imo.

import * as Promise from 'bluebird';


  await Promise.delay(5000)

How to calculate rolling / moving average using NumPy / SciPy?

If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods:

EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

>>> a = np.arange(20)
>>> moving_average(a)
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.])
>>> moving_average(a, n=4)
array([  1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,   9.5,
        10.5,  11.5,  12.5,  13.5,  14.5,  15.5,  16.5,  17.5])

So I guess the answer is: it is really easy to implement, and maybe numpy is already a little bloated with specialized functionality.

Android check internet connection

Try the following code:

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

How do I convert an existing callback API to promises?

Under node v7.6+ which has built in promises and async:

// promisify.js
let promisify = fn => (...args) =>
    new Promise((resolve, reject) =>
        fn(...args, (err, result) => {
            if (err) return reject(err);
            return resolve(result);
        })
    );

module.exports = promisify;

How to use:

let readdir = require('fs').readdir;
let promisify = require('./promisify');
let readdirP = promisify(readdir);

async function myAsyncFn(path) {
    let entries = await readdirP(path);
    return entries;
}

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

What is ".NET Core"?

From the .NET blog Announcing .NET 2015 Preview: A New Era for .NET:

.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the [ASP.NET Core] package.

.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.

And:

[ASP.NET Core] is the first workload that has adopted .NET Core. [ASP.NET Core] runs on both the .NET Framework and .NET Core. A key value of [ASP.NET Core] is that it can run on multiple versions of [.NET Core] on the same machine. Website A and website B can run on two different versions of .NET Core on the same machine, or they can use the same version.

In short: first, there was the Microsoft .NET Framework, which consists of a runtime that executes application and library code, and a nearly fully documented standard class library.

The runtime is the Common Language Runtime, which implements the Common Language Infrastructure, works with The JIT compiler to run the CIL (formerly MSIL) bytecode.

Microsoft's specification and implementation of .NET were, given its history and purpose, very Windows- and IIS-centered and "fat". There are variations with fewer libraries, namespaces and types, but few of them were useful for web or desktop development or are troublesome to port from a legal standpoint.

So in order to provide a non-Microsoft version of .NET, which could run on non-Windows machines, an alternative had to be developed. Not only the runtime has to be ported for that, but also the entire Framework Class Library to become well-adopted. On top of that, to be fully independent from Microsoft, a compiler for the most commonly used languages will be required.

Mono is one of few, if not the only alternative implementation of the runtime, which runs on various OSes besides Windows, almost all namespaces from the Framework Class Library as of .NET 4.5 and a VB and C# compiler.

Enter .NET Core: an open-source implementation of the runtime, and a minimal base class library. All additional functionality is delivered through NuGet packages, deploying the specific runtime, framework libraries and third-party packages with the application itself.

ASP.NET Core is a new version of MVC and WebAPI, bundled together with a thin HTTP server abstraction, that runs on the .NET Core runtime - but also on the .NET Framework.

How to drop column with constraint?

I got the same:

ALTER TABLE DROP COLUMN failed because one or more objects access this column message.

My column had an index which needed to be deleted first. Using sys.indexes did the trick:

DECLARE @sql VARCHAR(max)

SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
FROM sys.indexes idx
INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
WHERE idx.type <> 0
    AND tbl.NAME = 'tblName'
    AND col.NAME = 'colName'

EXEC sp_executeSql @sql
GO

ALTER TABLE tblName
DROP COLUMN colName

How to start MySQL with --skip-grant-tables?

If you use mysql 5.6 server and have problems with C:\Program Files\MySQL\MySQL Server 5.6\my.ini:

You should go to C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

You should add skip-grant-tables and then you do not need a password.

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
# server_type=3
[mysqld]
skip-grant-tables

Note: after you are done with your work on skip-grant-tables, you should restore your file of C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

Change default global installation directory for node.js modules in Windows?

trying to install global packages into C:\Program Files (x86)\nodejs\ gave me Run as Administrator issues, because npm was trying to install into
C:\Program Files (x86)\nodejs\node_modules\

to resolve this, change global install directory to C:\Users\{username}\AppData\Roaming\npm:

in C:\Users\{username}\, create .npmrc file with contents:

prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"

reference

environment
nodejs x86 installer into C:\Program Files (x86)\nodejs\ on Windows 7 Ultimate N 64-bit SP1
node --version : v0.10.28
npm --version : 1.4.10