Programs & Examples On #Workflow engine

Biggest advantage to using ASP.Net MVC vs web forms

Modern javascript controls as well as JSON requests can be handled much easily using MVC. There we can use a lot of other mechanisms to post data from one action to another action. That's why we prefer MVC over web forms. Also we can build light weight pages.

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

Image resolution for new iPhone 6 and 6+, @3x support added?

ios will always tries to take the best image, but will fall back to other options .. so if you only have normal images in the app and it needs @2x images it will use the normal images.

if you only put @2x in the project and you open the app on a normal device it will scale the images down to display.

if you target ios7 and ios8 devices and want best quality you would need @2x and @3x for phone and normal and @2x for ipad assets, since there is no non retina phone left and no @3x ipad.

maybe it is better to create the assets in the app from vector graphic... check http://mattgemmell.com/using-pdf-images-in-ios-apps/

Is it possible to specify condition in Count()?

Assuming you do not want to restrict the rows that are returned because you are aggregating other values as well, you can do it like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount
from ...

Let's say within the same column you had values of Manager, Supervisor, and Team Lead, you could get the counts of each like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
    count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
    count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

What is the opposite of :hover (on mouse leave)?

Just add a transition to the element you are messing with. Be aware that there could be some effects when the page loads. Like if you made a border radius change, you will see it when the dom loads.

_x000D_
_x000D_
.element {_x000D_
  width: 100px;_x000D_
  transition: all ease-in-out 0.5s;_x000D_
}_x000D_
 _x000D_
 .element:hover {_x000D_
  width: 200px;_x000D_
    transition: all ease-in-out 0.5s;_x000D_
}
_x000D_
_x000D_
_x000D_

What is the difference between %g and %f in C?

E = exponent expression, simply means power(10, n) or 10 ^ n

F = fraction expression, default 6 digits precision

G = gerneral expression, somehow smart to show the number in a concise way (but really?)

See the below example,

The code

void main(int argc, char* argv[])  
{  
        double a = 4.5;
        printf("=>>>> below is the example for printf 4.5\n");
        printf("%%e %e\n",a);
        printf("%%f %f\n",a);
        printf("%%g %g\n",a);
        printf("%%E %E\n",a);
        printf("%%F %F\n",a);
        printf("%%G %G\n",a);
          
        double b = 1.79e308;
        printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
        printf("%%e %e\n",b);
        printf("%%f %f\n",b);
        printf("%%g %g\n",b);
        printf("%%E %E\n",b);
        printf("%%F %F\n",b);
        printf("%%G %G\n",b);

        double d = 2.25074e-308;
        printf("=>>>> below is the example for printf 2.25074*10^-308\n");
        printf("%%e %e\n",d);
        printf("%%f %f\n",d);
        printf("%%g %g\n",d);
        printf("%%E %E\n",d);
        printf("%%F %F\n",d);
        printf("%%G %G\n",d);
}  

The output

=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308

Compiler error "archive for required library could not be read" - Spring Tool Suite

none of the solutions above helped my problem. I've resolved it by deleting all files in {projectworkspace}/.metadata folder AND in {location}/.m2 folder and let eclipse download every single thing again. Hope this helps someone, cheers!

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

How to avoid precompiled headers

try to add #include "stdafx.h" before #include "iostream"

how to always round up to the next integer

Check by using mod - if there is a remainder, simply increment the value by one.

Application Installation Failed in Android Studio

I had the same issue in MIUI. Enabling OEM unlocking worked for me without disabling MIUI optimization.

Below is a screenshot of my Redmi 3s prime developer options setting:

screenshot of my Redmi 3s prime developer options setting

How do I write to the console from a Laravel Controller?

Aha!

This can be done with the following PHP function:

error_log('Some message here.');

Found the answer here: Print something in PHP built-in web server

Getting the "real" Facebook profile picture URL from graph API

For Android:

According to latest Facebook SDK,

First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.

Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
        new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                if (response != null) {
                    try {
                        JSONObject data = response.getJSONObject();
                        if (data.has("picture")) {
                            String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
}).executeAsync();

Object array initialization without default constructor

Nope.

But lo! If you use std::vector<Car>, like you should be (never ever use new[]), then you can specify exactly how elements should be constructed*.

*Well sort of. You can specify the value of which to make copies of.


Like this:

#include <iostream>
#include <vector>

class Car
{
private:
    Car(); // if you don't use it, you can just declare it to make it private
    int _no;
public:
    Car(int no) :
    _no(no)
    {
        // use an initialization list to initialize members,
        // not the constructor body to assign them
    }

    void printNo()
    {
        // use whitespace, itmakesthingseasiertoread
        std::cout << _no << std::endl;
    }
};

int main()
{
    int userInput = 10;

    // first method: userInput copies of Car(5)
    std::vector<Car> mycars(userInput, Car(5)); 

    // second method:
    std::vector<Car> mycars; // empty
    mycars.reserve(userInput); // optional: reserve the memory upfront

    for (int i = 0; i < userInput; ++i)
        mycars.push_back(Car(i)); // ith element is a copy of this

    // return 0 is implicit on main's with no return statement,
    // useful for snippets and short code samples
} 

With the additional function:

void printCarNumbers(Car *cars, int length)
{
    for(int i = 0; i < length; i++) // whitespace! :)
         std::cout << cars[i].printNo();
}

int main()
{
    // ...

    printCarNumbers(&mycars[0], mycars.size());
} 

Note printCarNumbers really should be designed differently, to accept two iterators denoting a range.

push_back vs emplace_back

Optimization for emplace_back can be demonstrated in next example.

For emplace_back constructor A (int x_arg) will be called. And for push_back A (int x_arg) is called first and move A (A &&rhs) is called afterwards.

Of course, the constructor has to be marked as explicit, but for current example is good to remove explicitness.

#include <iostream>
#include <vector>
class A
{
public:
  A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }
  A () { x = 0; std::cout << "A ()\n"; }
  A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }
  A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }

private:
  int x;
};

int main ()
{
  {
    std::vector<A> a;
    std::cout << "call emplace_back:\n";
    a.emplace_back (0);
  }
  {
    std::vector<A> a;
    std::cout << "call push_back:\n";
    a.push_back (1);
  }
  return 0;
}

output:

call emplace_back:
A (x_arg)

call push_back:
A (x_arg)
A (A &&)

Running the new Intel emulator for Android

If all else fails. Simply try to download the Intel HAXM zip manually, extract and install. check here

Remember this only works for an Intel cpu that supports Intel Virtualization Technology. And you MUST enable virtulization in your bios.

It's a fairly decent and very noticeable improvement to the android emulator if you ask me.

Error related to only_full_group_by when executing a query in MySql

You can try to disable the only_full_group_by setting by executing the following:

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

MySQL 8 does not accept NO_AUTO_CREATE_USER so that needs to be removed.

Datanode process not running in Hadoop

I faced similar issue while running the datanode. The following steps were useful.

  1. In [hadoop_directory]/sbin directory use ./stop-all.sh to stop all the running services.
  2. Remove the tmp dir using rm -r [hadoop_directory]/tmp (The path configured in [hadoop_directory]/etc/hadoop/core-site.xml)
  3. sudo mkdir [hadoop_directory]/tmp (Make a new tmp directory)
  4. Go to */hadoop_store/hdfs directory where you have created namenode and datanode as sub-directories. (The paths configured in [hadoop_directory]/etc/hadoop/hdfs-site.xml). Use

    rm -r namenode
    
    rm -r datanode
    
  5. In */hadoop_store/hdfs directory use

    sudo mkdir namenode
    
    sudo mkdir datanode
    

In case of permission issue, use

   chmod -R 755 namenode 

   chmod -R 755 datanode
  1. In [hadoop_directory]/bin use

     hadoop namenode -format (To format your namenode)
    
  2. In [hadoop_directory]/sbin directory use ./start-all.sh or ./start-dfs.sh to start the services.
  3. Use jps to check the services running.

Callback functions in C++

Scott Meyers gives a nice example:

class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);

class GameCharacter
{
public:
  typedef std::function<int (const GameCharacter&)> HealthCalcFunc;

  explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
  : healthFunc(hcf)
  { }

  int healthValue() const { return healthFunc(*this); }

private:
  HealthCalcFunc healthFunc;
};

I think the example says it all.

std::function<> is the "modern" way of writing C++ callbacks.

How to return a specific element of an array?

I want to return odd numbers of an array

If i read that correctly, you want something like this?

List<Integer> getOddNumbers(int[] integers) {
  List<Integer> oddNumbers = new ArrayList<Integer>();
  for (int i : integers)
    if (i % 2 != 0)
      oddNumbers.add(i);
  return oddNumbers;
}

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

Mockito : how to verify method was called on an object created within a method?

Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger

That is especially handy when your Bar.someMethod() is private.

Fire event on enter key press for a textbox

Try follow: Aspx:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="EnterEvent(event, someMethod)"></asp:TextBox>    
<asp:Button ID="Button1" onclick="someMethod()" runat="server" Text="Button" />

JS:

function EnterEvent(e, callback) {
        if (e.keyCode == 13) {
            callback();
        }
    }

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Can I configure a subdomain to point to a specific port on my server

With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host

How can the error 'Client found response content type of 'text/html'.. be interpreted

I had this happen as a result of a configuration error in web.config. Checking the connection string etc might be the answer for the time out.

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.

Note: It's just a simple representation. Weighted Edges could be added like

g.add_edges_from([(1,2),(2,5)], weight=2)

and hence plotted again.

How to get a enum value from string in C#?

With some error handling...

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}

Clear Cache in Android Application programmatically

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

PHP Warning: PHP Startup: Unable to load dynamic library

I had the same problem on XAMPP for Windows when I try to install composer. I did php -v and php throwing error :

Unable to load dynamic library '/xampp/php/ext/php_bz2.dll'

It took me a while until I realized that I need to setup my XAMPP. So I run setup_xampp.bat and php return to works like a charm.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

Kubernetes service external ip pending

You can patch the IP of Node where pods are hosted ( Private IP of Node ) , this is the easy workaround .

Taking reference with above posts , Following worked for me :

kubectl patch service my-loadbalancer-service-name \ -n lb-service-namespace \ -p '{"spec": {"type": "LoadBalancer", "externalIPs":["xxx.xxx.xxx.xxx Private IP of Physical Server - Node - where deployment is done "]}}'

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

An example with flock(1) but without subshell. flock()ed file /tmp/foo is never removed, but that doesn't matter as it gets flock() and un-flock()ed.

#!/bin/bash

exec 9<> /tmp/foo
flock -n 9
RET=$?
if [[ $RET -ne 0 ]] ; then
    echo "lock failed, exiting"
    exit
fi

#Now we are inside the "critical section"
echo "inside lock"
sleep 5
exec 9>&- #close fd 9, and release lock

#The part below is outside the critical section (the lock)
echo "lock released"
sleep 5

C# code to validate email address

As mentioned in many answers, the domain of email addresses is complex. I would strongly discourage the use of a regex in this case. Those who match (most) cases are extremely complex to read and therefor to maintain. Furthermore, the still have difficulties supporting all cases, and are slow.

Microsoft's EmailAddress class helps a bit in that respect, but is not perfect either, I would argue. For an open source project I gave it try some years ago, by using a customized EmailParser.

That is used in [EmailAddress]https://github.com/Qowaiv/Qowaiv/blob/master/src/Qowaiv/EmailAddress.cs).

By using this approach, you're not only to validate email addresses, but also by cleaning out multiple formats of display names, getting rid of the mailto:-prefix, and normalizing domain literals based on IP-addresses, and lowercasing everything (note that the local part officially is case sensitive).

Scenario's your solution should support (and the mentioned one does):

[TestCase(null)]
[TestCase("")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@sd@dd")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@[188.120.150.10")]
[TestCase("[email protected]]")]
[TestCase("ab@[188.120.150.10].com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected].")]
[TestCase("ab@b+de.cc")]
[TestCase("[email protected]")]
[TestCase("[email protected],")]
[TestCase("plainaddress")]
[TestCase("plain.address")]
[TestCase("@%^%#$@#$@#.com")]
[TestCase("@domain.com")]
[TestCase("Joe Smith &lt;[email protected]&gt;")]
[TestCase("email.domain.com")]
[TestCase("email@[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected].")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@[123.123.123.123")]
[TestCase("email@[123.123.123].123")]
[TestCase("[email protected]]")]
[TestCase("[email protected].[123.123]")]
[TestCase("email@{leftbracket.com")]
[TestCase("email@rightbracket}.com")]
[TestCase("email@p|pe.com")]
[TestCase("isis@100%.nl")]
[TestCase("email@dollar$.com")]
[TestCase("email@r&amp;d.com")]
[TestCase("email@#hash.com")]
[TestCase("email@wave~tilde.com")]
[TestCase("email@exclamation!mark.com")]
[TestCase("email@question?mark.com")]
[TestCase("email@obelix*asterisk.com")]
[TestCase("email@grave`accent.com")]
[TestCase("email@colon:colon.com")]
[TestCase("email@caret^xor.com")]
[TestCase("email@=qowaiv.com")]
[TestCase("email@plus+.com")]
[TestCase("[email protected]>")]
[TestCase("email( (nested) )@plus.com")]
[TestCase("email)mirror(@plus.com")]
[TestCase("[email protected] (not closed comment")]
[TestCase("email(with @ in comment)plus.com")]
[TestCase(@"""Joe Smith [email protected]")]
[TestCase(@"""Joe Smith' [email protected]")]
[TestCase(@"""Joe Smith""[email protected]")]
[TestCase("email@mailto:domain.com")]
[TestCase("mailto:mailto:[email protected]")]
[TestCase("Display Name <[email protected]> (after name with display)")]
[TestCase("ReDoSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
public void IsInvalid(string email)
{
    Assert.IsFalse(EmailAddress.IsValid(email), email);
}

[TestCase("w@com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@[120.254.254.120]")]
[TestCase("local@2001:0db8:85a3:0000:0000:8a2e:0370:7334")]
[TestCase("local@[2001:0db8:85a3:0000:0000:8a2e:0370:7334]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@domain")]
[TestCase("[email protected]")]
[TestCase("local@?????.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@[123.123.123.123]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("{local{name{{with{@leftbracket.com")]
[TestCase("}local}name}}with{@rightbracket.com")]
[TestCase("|local||name|with|@pipe.com")]
[TestCase("%local%%name%with%@percentage.com")]
[TestCase("[email protected]")]
[TestCase("&local&&name&with&[email protected]")]
[TestCase("#local##name#with#@hash.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("*local**name*with*@asterisk.com")]
[TestCase("`local``name`with`@grave-accent.com")]
[TestCase("^local^^name^with^@xor.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("Joe Smith <[email protected]>")]
[TestCase("[email protected] (joe Smith)")]
[TestCase(@"""Joe Smith"" [email protected]")]
[TestCase(@"""Joe\\tSmith"" [email protected]")]
[TestCase(@"""Joe\""Smith"" [email protected]")]
[TestCase(@"Test |<gaaf <[email protected]>")]
[TestCase("MailTo:[email protected]")]
[TestCase("mailto:[email protected]")]
[TestCase("Joe Smith <mailto:[email protected]>")]
[TestCase("Joe Smith <mailto:email(with comment)@domain.com>")]
[TestCase(@"""With extra < within quotes"" Display Name<[email protected]>")]
[TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
public void IsValid(string email)
{
    Assert.IsTrue(EmailAddress.IsValid(email), email);
}

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

Why is Visual Studio 2013 very slow?

None of the suggestions worked for me, but I did solve my problem. I had tried most of the other recommendations before coming to the following solution.

My Scenario/Problem:

Using Visual Studio 2017 with ReSharper Ultimate. Keyboard input in the IDE got super slow as others have described. The last change I made to my solution was to add a new web site project, so I looked into that. After trying a lot of things, I tried adding a second web site project, so I could try to replace the first one, and Visual Studio just tanked after that. It wouldn't even load the solution anymore.

My Solution:

I forced Visual Studio closed and then I removed the newly added web site project(s) from the .sln file using Notepad. After saving and starting Visual Studio, my solution loaded quickly and everything seemed to be back to normal. I added a new Web Site with a slightly different configuration (see the thinking below), and the problem did not present itself again.

My Thinking:

I think the problem stemmed from creating the new web site project and using a file system path to a network share that is hosted in Azure. I'm working over VPN which tends to slow things down, and I occasionally experience various routing problems with some services, so my problem/solution might be a bit of a snowflake. I changed the file system path to be a local repository and will publish the files as needed which seems like a much better way to go.

How to display alt text for an image in chrome

Various browsers (mis)handle this in various ways. Using title (an old IE 'standard') isn't particularly appropriate, since the title attribute is a mouseover effect. The jQuery solution above (Alexis) seems on the right track, but I don't think the 'error' occurs at a point where it could be caught. I've had success by replacing at the src with itself, and then catching the error:

$('img').each(function()
{
    $(this).error(function()
    {
        $(this).replaceWith(this.alt);
    }).attr('src',$(this).prop('src'));
});

This, as in the Alexis contribution, has the benefit of removing the missing img image.

How do I remove all non alphanumeric characters from a string except dash?

I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution

char[] arr = str.ToCharArray();

arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) 
                                  || char.IsWhiteSpace(c) 
                                  || c == '-')));
str = new string(arr);

When using the compact framework (which doesn't have FindAll)

Replace FindAll with1

char[] arr = str.Where(c => (char.IsLetterOrDigit(c) || 
                             char.IsWhiteSpace(c) || 
                             c == '-')).ToArray(); 

str = new string(arr);

1 Comment by ShawnFeatherly

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

SET @sql = 
CONCAT( 'INSERT INTO <table_name> (', 
    (
        SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') ) 
            FROM information_schema.columns 
            WHERE table_schema = <database_name>
                AND table_name = <table_name>
                AND column_name NOT IN ('id')
    ), ') SELECT ', 
    ( 
        SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`')) 
        FROM information_schema.columns 
        WHERE table_schema = <database_name>
            AND table_name = <table_source_name>
            AND column_name NOT IN ('id')  
    ),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );  

PREPARE stmt1 FROM @sql; 
execute stmt1;

Of course replace <> values with real values, and watch your quotes.

How should strace be used?

strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.

Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

Why is using a wild card with a Java import statement bad?

  1. It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
  2. It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
  3. It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
  4. The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.

Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.

List columns with indexes in PostgreSQL

How about a simple solution:

SELECT 
  t.relname table_name,
  ix.relname index_name,
  indisunique,
  indisprimary, 
  regexp_replace(pg_get_indexdef(indexrelid), '.*\((.*)\)', '\1') columns
FROM pg_index i
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_class ix ON ix.oid = i.indexrelid
WHERE t.relname LIKE 'test%'

`

How to Copy Text to Clip Board in Android?

In Kotlin I have an extension for this

fun Context.copyToClipboard(text: String) {
  val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
  val clip =
    ClipData.newPlainText(getString(R.string.copy_clipboard_label, getString(R.string.app_name)),text)
  clipboard.setPrimaryClip(clip)
}

getResourceAsStream returns null

In pom.xml manage or remove ../src/main/resources

How do I migrate an SVN repository with history to a new Git repository?

For GitLab users I've put up a gist on how I migrated from SVN here:

https://gist.github.com/leftclickben/322b7a3042cbe97ed2af

Steps to migrate from SVN to GitLab

Setup

  • SVN is hosted at svn.domain.com.au.
  • SVN is accessible via http (other protocols should work).
  • GitLab is hosted at git.domain.com.au and:
    • A group is created with the namespace dev-team.
    • At least one user account is created, added to the group, and has an SSH key for the account being used for the migration (test using ssh [email protected]).
    • The project favourite-project is created in the dev-team namespace.
  • The file users.txt contains the relevant user details, one user per line, of the form username = First Last <[email protected]>, where username is the username given in SVN logs. (See first link in References section for details, in particular answer by user Casey).

Versions

  • subversion version 1.6.17 (r1128011)
  • git version 1.9.1
  • GitLab version 7.2.1 ff1633f
  • Ubuntu server 14.04

Commands

bash
git svn clone --stdlayout --no-metadata -A users.txt 
http://svn.domain.com.au/svn/repository/favourite-project
cd favourite-project
git remote add gitlab [email protected]:dev-team/favourite-project.git
git push --set-upstream gitlab master

That's it! Reload the project page in GitLab web UI and you will see all commits and files now listed.

Notes

  • If there are unknown users, the git svn clone command will stop, in which case, update users.txt, cd favourite-project and git svn fetch will continue from where it stopped.
  • The standard trunk-tags-branches layout for SVN repository is required.
  • The SVN URL given to the git svn clone command stops at the level immediately above trunk/, tags/ and branches/.
  • The git svn clone command produces a lot of output, including some warnings at the top; I ignored the warnings.

How to play YouTube video in my Android application?

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watchv=cxLG2wtE7TM"));
startActivity(intent);

Why won't eclipse switch the compiler to Java 8?

Old question, but posting the answer incase it helps someone. Already build path was configured to use JDK 1.2.81 However, build was failing with the error below:

 lambda expressions are not supported in -source 1.5
[ERROR]   (use -source 8 or higher to enable lambda expressions)

In the latest Eclipse (Photon), adding the below entry to pom.xml worked.

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

Here an alternative using SUBSTRING

SELECT
            SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
            SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
    FROM 
            [Fields]

with fiddle

Validate phone number using javascript

JavaScript to validate the phone number:

_x000D_
_x000D_
function phonenumber(inputtxt) {_x000D_
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  if(inputtxt.value.match(phoneno)) {_x000D_
    return true;_x000D_
  }_x000D_
  else {_x000D_
    alert("message");_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The above script matches:

XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code:

function phonenumber(inputtxt) {
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  }  
  else {  
    alert("message");
    return false;
  }
}

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

A simple restart fixed it for me. I'm not sure what was the problem since I work with so much software but I have a feeling it was the VPN software or maybe the fact I put my laptop in sleep a lot and some file was corrupted. I really don't know but the restart fixed it.

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

MSOnline can't be imported on PowerShell (Connect-MsolService error)

I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;

I also use the newer command:

Connect-SPOService

How to combine two or more querysets in a Django view?

DATE_FIELD_MAPPING = {
    Model1: 'date',
    Model2: 'pubdate',
}

def my_key_func(obj):
    return getattr(obj, DATE_FIELD_MAPPING[type(obj)])

And then sorted(chain(Model1.objects.all(), Model2.objects.all()), key=my_key_func)

Quoted from https://groups.google.com/forum/#!topic/django-users/6wUNuJa4jVw. See Alex Gaynor

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

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

You can use list comprehensions.

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

will get you [ ('a', 1), ('b', 2), ('c', 3) ] and

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

the other example.

Read more about list comprehensions if you like, it's very interesting what you can do with them.

Xcode - Warning: Implicit declaration of function is invalid in C99

I have the same warning (it's make my app cannot build). When I add C function in Objective-C's .m file, But forgot to declared it at .h file.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

How is the HashMap declaration expressed in that scope? It should be:

HashMap<String, ArrayList> dictMap

If not, it is assumed to be Objects.

For instance, if your code is:

HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);

that will not work. Instead you want:

HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);

The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.

Also note that ArrayList is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList contains your class MyClass, the line above might be:

HashMap<String, ArrayList<MyClass>> dictMap

How to clear an ImageView in Android?

I had a similar problem, where I needed to basically remove ImageViews from the screen completely. Some of the answers here led me in the right direction, but ultimately calling setImageDrawable() worked for me:

imgView.setImageDrawable(null);

(As mentioned in the comment, such usage is documented in the official docs: ImageView#setImageDrawable.)

Image scaling causes poor quality in firefox/internet explorer but not chrome

I've seen the same thing in firefox, css transform scaled transparent png's looking very rough.

I noticed that when they previously had a background color set the quality was much better, so I tried setting an RGBA background with as low an opacity value as possible.

background:rgba(255,255,255,0.001);

This worked for me, give it a try.

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

How to get the Touch position in android?

Here is the Koltin style, I use this in my project and it works very well:

this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
        val x = event.x
        val y = event.y

        when(event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_UP -> {
                Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
            }
        }
        return@OnTouchListener  true
    })

Play audio with Python

I recently made my Music Player support all audio files locally. I did this by figuring out a way to use the vlc python module and also the VLC dll files. You can check it out: https://github.com/elibroftw/music-caster/blob/master/audio_player.py

Send text to specific contact programmatically (whatsapp)

This is the shortest way

    String mPhoneNumber = "+972505555555";
    mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
    String mMessage = "Hello world";
    String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
    startActivity(new Intent(Intent.ACTION_VIEW,
            Uri.parse(
                    mSendToWhatsApp
            )));

See also the documentation of WhatsApp

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   options.push(data);
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

String.Replace(char, char) method in C#

What about creating an Extension Method like this....

 public static string ReplaceTHAT(this string s)
 {
    return s.Replace("\n\r", "");
 }

And then when you want to replace that wherever you want you can do this.

s.ReplaceTHAT();

Best Regards!

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

How to count duplicate rows in pandas dataframe?

df.groupby(df.columns.tolist()).size().reset_index().\
    rename(columns={0:'records'})

   one  two  records
0    1    1        2
1    1    2        1

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

C++ IDE for Linux?

IntelliJ IDEA + the C/C++ plugin at http://plugins.intellij.net/plugin/?id=1373

Prepare to have your mind-blown.

Cheers!

How do I implement Toastr JS?

This is a simple way to do it!

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script>
function notificationme(){
toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "preventDuplicates": true,
            "onclick": null,
            "showDuration": "100",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "show",
            "hideMethod": "hide"
        };
toastr.info('MY MESSAGE!');
}
</script>

How To Set A JS object property name from a variable

Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:

var salesperson = ...

var mailchimpInterests = { 
        "aGroupId": true,
    };

mailchimpInterests[salesperson] = true;

Cannot find or open the PDB file in Visual Studio C++ 2010

you just add the path of .pdb to work directory of VS!

Why would an Enum implement an Interface?

Here's one example (a similar/better one is found in Effective Java 2nd Edition):

public interface Operator {
    int apply (int a, int b);
}

public enum SimpleOperators implements Operator {
    PLUS { 
        int apply(int a, int b) { return a + b; }
    },
    MINUS { 
        int apply(int a, int b) { return a - b; }
    };
}

public enum ComplexOperators implements Operator {
    // can't think of an example right now :-/
}

Now to get a list of both the Simple + Complex Operators:

List<Operator> operators = new ArrayList<Operator>();

operators.addAll(Arrays.asList(SimpleOperators.values()));
operators.addAll(Arrays.asList(ComplexOperators.values()));

So here you use an interface to simulate extensible enums (which wouldn't be possible without using an interface).

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

  1. Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

  2. Using a double quote password: "your password" <-- this one also solved my problem.

Text inset for UITextField?

Here is the same subclassed UITextField written in Swift 3. It is quite different from prior versions of Swift, as you'll see:

import UIKit

class MyTextField: UITextField
    {
    let inset: CGFloat = 10

    // placeholder position
    override func textRect(forBounds bounds: CGRect) -> CGRect
        {
        return bounds.insetBy(dx: inset, dy: inset)
        }

    // text position
    override func editingRect(forBounds bounds: CGRect) -> CGRect
        {
        return bounds.insetBy(dx: inset, dy: inset)
        }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect
        {
        return bounds.insetBy(dx: inset, dy: inset)
        }
    }

Incidentally, you can also do something like the following, if you want to control the inset of just one side. This particular example of adjusting only the left inset comes in handy if you place an image on top of the UITextField but you want it to appear to the user to be within the text field:

    override func editingRect(forBounds bounds: CGRect) -> CGRect
        {
        return CGRect.init(x: bounds.origin.x + inset, y: bounds.origin.y, width: bounds.width - inset, height: bounds.height)
        }

Mean Squared Error in Numpy?

Another alternative to the accepted answer that avoids any issues with matrix multiplication:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square: "Return the element-wise square of the input."

How can you float: right in React Native?

You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.

In your case, you will probably want the container to have an attribute

justifyContent: 'flex-end'

And about the text taking the whole space, again, you need to take a look at your container.

Here is a link to really great guide on flexbox: A Complete Guide to Flexbox

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

Get selected item value from Bootstrap DropDown with specific ID

$('#demolist li').on('click', function(){
    $('#datebox').val($(this).text());
});

http://jsfiddle.net/kcpma/18/

How do I remove duplicates from a C# array?

  private static string[] distinct(string[] inputArray)
        {
            bool alreadyExists;
            string[] outputArray = new string[] {};

            for (int i = 0; i < inputArray.Length; i++)
            {
                alreadyExists = false;
                for (int j = 0; j < outputArray.Length; j++)
                {
                    if (inputArray[i] == outputArray[j])
                        alreadyExists = true;
                }
                        if (alreadyExists==false)
                        {
                            Array.Resize<string>(ref outputArray, outputArray.Length + 1);
                            outputArray[outputArray.Length-1] = inputArray[i];
                        }
            }
            return outputArray;
        }

What is the best way to add options to a select from a JavaScript object with jQuery?

Set your HTML select id into following line below. In here mySelect is used as the id of the select element.

   var options = $("#mySelect");

then get the object which is the selectValues in this scenario and sets it to the jquery for each loop. It will use the value and text of the objects accordingly and appends it into the option selections as follows.

$.each(selectValues, function(val, text) {
            options.append(
             $('<option></option>').val(val).html(text)
          );
      });

This will display text as the option list when drop down list is selected and once a text is selected value of the selected text will be used.

Eg.

"1": "test 1", "2": "test 2",

Dropdown,

display name: test 1 -> value is 1 display name: test 2 -> value is 2

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

Random row selection in Pandas dataframe

sample

As of v0.20.0, you can use pd.DataFrame.sample, which can be used to return a random sample of a fixed number rows, or a percentage of rows:

df = df.sample(n=k)     # k rows
df = df.sample(frac=k)  # int(len(df.index) * k) rows

For reproducibility, you can specify an integer random_state, equivalent to using np.ramdom.seed. So, instead of setting, for example, np.random.seed = 0, you can:

df = df.sample(n=k, random_state=0)

Is there a CSS selector for the first direct child only?

The CSS selector for the direct first-child in your case is:

.section > :first-child

The direct selector is > and the first child selector is :first-child

No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:

div.section > :first-child

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

How can I determine the status of a job?

-- Microsoft SQL Server 2008 Standard Edition:
IF EXISTS(SELECT 1 
          FROM msdb.dbo.sysjobs J 
          JOIN msdb.dbo.sysjobactivity A 
              ON A.job_id=J.job_id 
          WHERE J.name=N'Your Job Name' 
          AND A.run_requested_date IS NOT NULL 
          AND A.stop_execution_date IS NULL
         )
    PRINT 'The job is running!'
ELSE
    PRINT 'The job is not running.'

How to change Screen buffer size in Windows Command Prompt from batch script

Here's what I did in case someone finds it useful (I used a lot of things according to the rest of the answers in this thread):

First I adjusted the layout settings as needed. This changes the window size immediately so it was easier to set the exact size that I wanted. By the way I didn't know that I can also have visible width smaller than width buffer. This was nice since I usually hate a long line to be wrapped. enter image description here

Then after clicking ok, I opened regedit.exe and went to "HKEY_CURRENT_USER\Console". There is a new child entry there "%SystemRoot%_system32_cmd.exe". I right clicked on that and selected Export: enter image description here

I saved this as "cmd_settings.reg". Then I created a batch script that imports those settings, invokes my original batch script (name batch_script.bat) and then deletes what I imported in order for the command line window to return to default settings:

regedit /s cmd_settings.reg
start /wait batch_script.bat
reg delete "HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe" /f

This is a sample batch that could be invoked ("batch_script.bat"):

@echo off
echo test!
pause
exit

Don't forget the exit command at the end of your script if you want the reg delete line to run after the script execution.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Passing html values into javascript functions

Try: if(parseInt(order)>0){....

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Peak signal detection in realtime timeseries data

The function scipy.signal.find_peaks, as its name suggests, is useful for this. But it's important to understand well its parameters width, threshold, distance and above all prominence to get a good peak extraction.

According to my tests and the documentation, the concept of prominence is "the useful concept" to keep the good peaks, and discard the noisy peaks.

What is (topographic) prominence? It is "the minimum height necessary to descend to get from the summit to any higher terrain", as it can be seen here:

The idea is:

The higher the prominence, the more "important" the peak is.

Heap vs Binary Search Tree (BST)

As mentioned by others, Heap can do findMin or findMax in O(1) but not both in the same data structure. However I disagree that Heap is better in findMin/findMax. In fact, with a slight modification, the BST can do both findMin and findMax in O(1).

In this modified BST, you keep track of the the min node and max node everytime you do an operation that can potentially modify the data structure. For example in insert operation you can check if the min value is larger than the newly inserted value, then assign the min value to the newly added node. The same technique can be applied on the max value. Hence, this BST contain these information which you can retrieve them in O(1). (same as binary heap)

In this BST (Balanced BST), when you pop min or pop max, the next min value to be assigned is the successor of the min node, whereas the next max value to be assigned is the predecessor of the max node. Thus it perform in O(1). However we need to re-balance the tree, thus it will still run O(log n). (same as binary heap)

I would be interested to hear your thought in the comment below. Thanks :)

Update

Cross reference to similar question Can we use binary search tree to simulate heap operation? for more discussion on simulating Heap using BST.

TypeError: got multiple values for argument

Simply put you can't do the following:

class C(object):
    def x(self, y, **kwargs):
        # Which y to use, kwargs or declaration? 
        pass

c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS

Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.

Ruby capitalize every word first letter

In Rails:

"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'

w/o Rails:

"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")

#OBJECT IT OUT
def titleize(str)
  str.split(/ |\_/).map(&:capitalize).join(" ")
end

#OR MONKEY PATCH IT
class String  
  def titleize
    self.split(/ |\_/).map(&:capitalize).join(" ")
  end
end

w/o Rails (load rails's ActiveSupport to patch #titleize method to String)

require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"

(some) string use cases handled by #titleize

  • "kirk douglas"
  • "kirk_douglas"
  • "kirk-douglas"
  • "kirkDouglas"
  • "KirkDouglas"

#titleize gotchas

Rails's titleize will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:

"hEy lOok".titleize #=> "H Ey Lo Ok"

because it is meant to handle camel-cased code like:

"kirkDouglas".titleize #=> "Kirk Douglas"

To deal with this edge case you could clean your string with #downcase first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:

"kirkDouglas".downcase.titleize #=> "Kirkdouglas"

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

How to request a random row in SQL?

Random function from the sql could help. Also if you would like to limit to just one row, just add that in the end.

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

What is the proper way to format a multi-line dict in Python?

Since your keys are strings and since we are talking about readability, I prefer :

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)

Uploading both data and files in one form using Ajax?

<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button type='button' id='submit_btn'>Submit</button>
</form>

<script>
$(document).on("click", "#submit_btn", function (e) {
    //Prevent Instant Click  
    e.preventDefault();
    // Create an FormData object 
    var formData = $("#form").submit(function (e) {
        return;
    });
    //formData[0] contain form data only 
    // You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here   -->)
    var formData = new FormData(formData[0]);
    $.ajax({
        url: $('#form').attr('action'),
        type: 'POST',
        data: formData,
        success: function (response) {
            console.log(response);
        },
        contentType: false,
        processData: false,
        cache: false
    });
    return false;
});
</script>

///// otherpage.php

<?php
    print_r($_FILES);
?>

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

jQuery hyperlinks - href value?

I almost had this problem and it was very deceiving. I am providing an answer in case someone winds up in my same position.

  1. I thought I had this problem
  2. But, I was using return false and javascript:void(0);
  3. Then a distinct difference in problem kept surfacing:
  4. I realized it's not going ALL the way to the top - and my problem zone was near the bottom of the page so this jump was strange and annoying.
  5. I realized I was using fadeIn() [jQuery library], which for a short time my content was display:none
  6. And then my content extended the reach of the page! Causing what looks like a jump!
  7. Using visibility hidden toggles now..

Hope this helps the person stuck with jumps!!

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

How to tell when UITableView has completed ReloadData?

Try setting delays:

[_tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];
[_activityIndicator performSelector:@selector(stopAnimating) withObject:nil afterDelay:0.2];

HtmlSpecialChars equivalent in Javascript?

There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:

escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual:   Kip&#039;s &lt;b&gt;evil</b> &quot;test" code's here
Expected: Kip&#039;s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code&#039;s here

Here is code that works properly:

function escapeHtml(text) {
  return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

Update

The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  
  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

How can I commit a single file using SVN over a network?

You can use

cd /You folder name
svn commit 'your file path' -m "Commit message you want to give"

You can also drage you files to command promt instead to write cd [common in MAC OSx]

Automating the InvokeRequired code pattern

Usage:

control.InvokeIfRequired(c => c.Visible = false);

return control.InvokeIfRequired(c => {
    c.Visible = value

    return c.Visible;
});

Code:

using System;
using System.ComponentModel;

namespace Extensions
{
    public static class SynchronizeInvokeExtensions
    {
        public static void InvokeIfRequired<T>(this T obj, Action<T> action)
            where T : ISynchronizeInvoke
        {
            if (obj.InvokeRequired)
            {
                obj.Invoke(action, new object[] { obj });
            }
            else
            {
                action(obj);
            }
        }

        public static TOut InvokeIfRequired<TIn, TOut>(this TIn obj, Func<TIn, TOut> func) 
            where TIn : ISynchronizeInvoke
        {
            return obj.InvokeRequired
                ? (TOut)obj.Invoke(func, new object[] { obj })
                : func(obj);
        }
    }
}

javascript set cookie with expire time

I use a function to store cookies with a custom expire time in days:

// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

IIS7 Permissions Overview - ApplicationPoolIdentity

Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

How do I use PHP to get the current year?

strftime("%Y");

I love strftime. It's a great function for grabbing/recombining chunks of dates/times.

Plus it respects locale settings which the date function doesn't do.

Importing text file into excel sheet

you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.

How to return a value from a Form in C#?

First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :

 public string Response { get; set; }

 private void OkButton_Click(object sender, EventArgs e)
 {
    Response = "ok";
 }

 private void CancelButton_Click(object sender, EventArgs e)
 {
    Response = "Cancel";
 }

Calling of form2(child) from form1(parent):

  using (Form2 formObject= new Form2() )
  {
     formObject.ShowDialog();

      string result = formObject.Response; 
      //to update response of form2 after saving in result
      formObject.Response="";

      // do what ever with result...
      MessageBox.Show("Response from form2: "+result); 
  }

Good tutorial for using HTML5 History API (Pushstate?)

The HTML5 history spec is quirky.

history.pushState() doesn't dispatch a popstate event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate event or use history.go() to navigate to the new state. The idea is that a router can listen to popstate events and do the navigation for you.

Some things to note:

  • history.pushState() and history.replaceState() don't dispatch popstate events.
  • history.back(), history.forward(), and the browser's back and forward buttons do dispatch popstate events.
  • history.go() and history.go(0) do a full page reload and don't dispatch popstate events.
  • history.go(-1) (back 1 page) and history.go(1) (forward 1 page) do dispatch popstate events.

You can use the history API like this to push a new state AND dispatch a popstate event.

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

Then listen for popstate events with a router.

Get refresh token google api

Since March 2016, use prompt=consent to regenerate Google API refresh token.

As mentioned in https://github.com/googleapis/oauth2client/issues/453,

approval_prompt=force has been replaced with prompt=none|consent|select_account

Ways to save enums in database

We just store the enum name itself - it's more readable.

We did mess around with storing specific values for enums where there are a limited set of values, e.g., this enum that has a limited set of statuses that we use a char to represent (more meaningful than a numeric value):

public enum EmailStatus {
    EMAIL_NEW('N'), EMAIL_SENT('S'), EMAIL_FAILED('F'), EMAIL_SKIPPED('K'), UNDEFINED('-');

    private char dbChar = '-';

    EmailStatus(char statusChar) {
        this.dbChar = statusChar;
    }

    public char statusChar() {
        return dbChar;
    }

    public static EmailStatus getFromStatusChar(char statusChar) {
        switch (statusChar) {
        case 'N':
            return EMAIL_NEW;
        case 'S':
            return EMAIL_SENT;
        case 'F':
            return EMAIL_FAILED;
        case 'K':
            return EMAIL_SKIPPED;
        default:
            return UNDEFINED;
        }
    }
}

and when you have a lot of values you need to have a Map inside your enum to keep that getFromXYZ method small.

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

Your approach is ok :) I simplify your shortest version a little (for saturation control look here)

(col,amt)=> (+('0x'+col)+amt*0x010101).toString(16).padStart(6,0)

_x000D_
_x000D_
// Similar to OP shortest version, we not have here # and colors range checking

var LightenDarkenColor = 
     (col,amt) => (+('0x'+col)+amt*0x010101).toString(16).padStart(6,0);    




// ------
// TEST
// ------

function update() {
  let c= col.value.padEnd(6,'0').slice(0,6);
  let color = '#'+LightenDarkenColor(c, +amt.value);
  oldColor.innerHTML = 'Old: #'+c;
  oldColor.style = `background: #${c}`;
  newColor.innerHTML = 'New: '+color
  newColor.style = `background: ${color}`;

  
}

update();
_x000D_
.box{ width: 100px; height: 100px; margin: 10px; display: inline-block}
_x000D_
<input id="col" value="3F6D2A" oninput="update()">
<input id="amt" value="30" oninput="update()"><br>
<div id="oldColor" class="box"></div>
<div id="newColor" class="box"></div>
_x000D_
_x000D_
_x000D_

And version with # and color ranges checking

_x000D_
_x000D_
// # and colors range checking

var LightenDarkenColor = 
     (col,amt) => '#'+col.slice(1).match(/../g)
                         .map(x=>(x=+`0x${x}`+amt,x<0?0:(x>255?255:x))
                         .toString(16).padStart(2,0)).join``;




// ------
// TEST
// ------

function update() {
  let c= col.value.padEnd(6,'0').slice(0,7);
  let color = LightenDarkenColor(c, +amt.value);
  oldColor.innerHTML = 'Old: '+c;
  oldColor.style = `background: ${c}`;
  newColor.innerHTML = 'New: '+color
  newColor.style = `background: ${color}`;
}

update();
_x000D_
.box{ width: 100px; height: 100px; margin: 10px; display: inline-block}
_x000D_
<input id="col" value="#3F6D2A" oninput="update()">
<input id="amt" value="40" oninput="update()"><br>
<div id="oldColor" class="box"></div>
<div id="newColor" class="box"></div>
_x000D_
_x000D_
_x000D_

How to Generate unique file names in C#

Use

Path.GetTempFileName()

or use new GUID().

Path.GetTempFilename() on MSDN.

Comparing floating point number to zero

notice, that code is:

std::abs((x - y)/x) <= epsilon

you are requiring that the "relative error" on the var is <= epsilon, not that the absolute difference is

Find MongoDB records where array field is not empty

ME.find({pictures: {$exists: true}}) 

Simple as that, this worked for me.

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

If you are running cmake to generate SomeLib yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG mode of the find_packages() command, you'll see that the User Package Registry is one of elements.

Brief how-to

Associate the targets of SomeLib that you need outside of that external project by adding them to an export set in the CMakeLists.txt files where they are created:

add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)

Create a XXXConfig.cmake file for SomeLib in its ${CMAKE_CURRENT_BUILD_DIR} and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt associated with SomeLib:

export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib)                                                    # Store location of SomeLibConfig.cmake

Issue your find_package(SomeLib REQUIRED) commmand in the CMakeLists.txt file of the project that depends on SomeLib without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH.

When it might be the right approach

This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.

But if you're never actually installing SomeLib in your workflow, calling EXPORT(PACKAGE <name>) allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib, you probably know your platform, CMAKE_MODULE_PATH, etc, so @user2288008's excellent answer will have you covered.

ORA-01861: literal does not match format string

SELECT alarm_id
,definition_description
,element_id
,TO_CHAR (alarm_datetime, 'YYYY-MM-DD HH24:MI:SS')
,severity
, problem_text
,status 
FROM aircom.alarms 
WHERE status = 1 
    AND TO_char (alarm_datetime,'DD.MM.YYYY HH24:MI:SS') > TO_DATE ('07.09.2008  09:43:00', 'DD.MM.YYYY HH24:MI:SS') 
ORDER BY ALARM_DATETIME DESC 

How to set breakpoints in inline Javascript in Google Chrome?

Using Visual Studio (2012) I had the same issue and switching to IIS Express solved the problem!

The script tag's type attribute did not factor into it.

For some reason the Visual Studio Development Server does not provide everything Chrome needs to enable the breakpoints.

intellij incorrectly saying no beans of type found for autowired repository

This seems to still be a bug in the latest IntelliJ and has to do with a possible caching issue?

If you add the @Repository annotation as mk321 mentioned above, save, then remove the annotation and save again, this fixes the problem.

CodeIgniter Disallowed Key Characters

In my case, i was serializing an input form using jquery serialize() and then urlencoding it using encodeURIComponent().

var datas = form.serialize();
encodeURIComponent(datas);
$.getJSON(url,datas,function(){});

and codeigniter was giving the disallowed character error.

i figured the issue here was, jquery serialize gives an encoded output and i was again encoding it with the encodeURIcomponent which was unnecessary, and when codeingiter decoded it it was not getting the actual string as some part was encoded twice. i will explain it with an example.

string: quantity[]=1&option=sell

urlencoded while serializing: quantity%5B%5D%3D1%26option%3Dsell

again urlencoded with encodedURICompontent(): quantity%255B%255D%253D1%2526option%253Dsell

---at codeigntier

urldecode: quantity%5B%5D=1&option=sell

which has disallowed charecters as per the input class regex.

note: this is not an answer to this question, but would help to check if one is encountering this error...thanks.

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

What’s the best way to get an HTTP response code from a URL?

In future, for those that use python3 and later, here's another code to find response code.

import urllib.request

def getResponseCode(url):
    conn = urllib.request.urlopen(url)
    return conn.getcode()

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

      JPanel panel = new JPanel();
      panel.add(textField);

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?

Python: 'break' outside loop

This is an old question, but if you wanted to break out of an if statement, you could do:

while 1:
    if blah:
        break

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

Set div height equal to screen size

Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.

Use vh instead of %;

REST API Best practices: Where to put parameters?

If there are documented best practices, I have not found them yet. However, here are a few guidelines I use when determining where to put parameters in an url:

Optional parameters tend to be easier to put in the query string.

If you want to return a 404 error when the parameter value does not correspond to an existing resource then I would tend towards a path segment parameter. e.g. /customer/232 where 232 is not a valid customer id.

If however you want to return an empty list then when the parameter is not found then I suggest using query string parameters. e.g. /contacts?name=dave

If a parameter affects an entire subtree of your URI space then use a path segment. e.g. a language parameter /en/document/foo.txt versus /document/foo.txt?language=en

I prefer unique identifiers to be in a path segment rather than a query parameter.

The official rules for URIs are found in this RFC spec here. There is also another very useful RFC spec here that defines rules for parameterizing URIs.

How to reset par(mfrow) in R

You can reset the mfrow parameter

par(mfrow=c(1,1))

What is two way binding?

Worth mentioning that there are many different solutions which offer two way binding and play really nicely.

I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.

There is a more extended list of backbone extensions/plugins on github

Converting between datetime, Timestamp and datetime64

To convert numpy.datetime64 to datetime object that represents time in UTC on numpy-1.8:

>>> from datetime import datetime
>>> import numpy as np
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> dt64 = np.datetime64(dt)
>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
>>> ts
1354650685.3624549
>>> datetime.utcfromtimestamp(ts)
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> np.__version__
'1.8.0.dev-7b75899'

The above example assumes that a naive datetime object is interpreted by np.datetime64 as time in UTC.


To convert datetime to np.datetime64 and back (numpy-1.6):

>>> np.datetime64(datetime.utcnow()).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)

It works both on a single np.datetime64 object and a numpy array of np.datetime64.

Think of np.datetime64 the same way you would about np.int8, np.int16, etc and apply the same methods to convert beetween Python objects such as int, datetime and corresponding numpy objects.

Your "nasty example" works correctly:

>>> from datetime import datetime
>>> import numpy 
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__
'1.6.2' # current version available via pip install numpy

I can reproduce the long value on numpy-1.8.0 installed as:

pip install git+https://github.com/numpy/numpy.git#egg=numpy-dev

The same example:

>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
1025222400000000000L
>>> numpy.__version__
'1.8.0.dev-7b75899'

It returns long because for numpy.datetime64 type .astype(datetime) is equivalent to .astype(object) that returns Python integer (long) on numpy-1.8.

To get datetime object you could:

>>> dt64.dtype
dtype('<M8[ns]')
>>> ns = 1e-9 # number of seconds in a nanosecond
>>> datetime.utcfromtimestamp(dt64.astype(int) * ns)
datetime.datetime(2002, 6, 28, 0, 0)

To get datetime64 that uses seconds directly:

>>> dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
>>> dt64.dtype
dtype('<M8[s]')
>>> datetime.utcfromtimestamp(dt64.astype(int))
datetime.datetime(2002, 6, 28, 0, 0)

The numpy docs say that the datetime API is experimental and may change in future numpy versions.

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Algorithm to return all combinations of k elements from n

In Python like Andrea Ambu, but not hardcoded for choosing three.

def combinations(list, k):
    """Choose combinations of list, choosing k elements(no repeats)"""
    if len(list) < k:
        return []
    else:
        seq = [i for i in range(k)]
        while seq:
            print [list[index] for index in seq]
            seq = get_next_combination(len(list), k, seq)

def get_next_combination(num_elements, k, seq):
        index_to_move = find_index_to_move(num_elements, seq)
        if index_to_move == None:
            return None
        else:
            seq[index_to_move] += 1

            #for every element past this sequence, move it down
            for i, elem in enumerate(seq[(index_to_move+1):]):
                seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1

            return seq

def find_index_to_move(num_elements, seq):
        """Tells which index should be moved"""
        for rev_index, elem in enumerate(reversed(seq)):
            if elem < (num_elements - rev_index - 1):
                return len(seq) - rev_index - 1
        return None   

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

Check substring exists in a string in C

My own humble (case sensitive) solution:

uint8_t strContains(char* string, char* toFind)
{
    uint8_t slen = strlen(string);
    uint8_t tFlen = strlen(toFind);
    uint8_t found = 0;

    if( slen >= tFlen )
    {
        for(uint8_t s=0, t=0; s<slen; s++)
        {
            do{

                if( string[s] == toFind[t] )
                {
                    if( ++found == tFlen ) return 1;
                    s++;
                    t++;
                }
                else { s -= found; found=0; t=0; }

              }while(found);
        }
        return 0;
    }
    else return -1;
}

Results

strContains("this is my sample example", "th") // 1
strContains("this is my sample example", "sample") // 1
strContains("this is my sample example", "xam") // 1
strContains("this is my sample example", "ple") // 1
strContains("this is my sample example", "ssample") // 0
strContains("this is my sample example", "samplee") // 0
strContains("this is my sample example", "") // 0
strContains("str", "longer sentence") // -1
strContains("ssssssample", "sample") // 1
strContains("sample", "sample") // 1

Tested on ATmega328P (avr8-gnu-toolchain-3.5.4.1709) ;)

How to add leading zeros for for-loop in shell?

Use printf command to have 0 padding:

printf "%02d\n" $num

Your for loop will be like this:

for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done
01
02
03
04
05

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

Converting java date to Sql timestamp

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

Encode a FileStream to base64 with c#

An easy one as an extension method

public static class Extensions
{
    public static Stream ConvertToBase64(this Stream stream)
    {
        byte[] bytes;
        using (var memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            bytes = memoryStream.ToArray();
        }

        string base64 = Convert.ToBase64String(bytes);
        return new MemoryStream(Encoding.UTF8.GetBytes(base64));
    }
}

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

In my situation, the Visual Studio loads the DLLs in Global Assembly Cache (GAC), not the DLL in my project list. I deleted the DLLs in GAC and now I can see the break point working.

What are public, private and protected in object oriented programming?

To sum it up,in object oriented programming, everything is modeled into classes and objects. Classes contain properties and methods. Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.

Oracle: is there a tool to trace queries, like Profiler for sql server?

alter system set timed_statistics=true

--or

alter session set timed_statistics=true --if want to trace your own session

-- must be big enough:

select value from v$parameter p
where name='max_dump_file_size' 

-- Find out sid and serial# of session you interested in:

 select sid, serial# from v$session
 where ...your_search_params...

--you can begin tracing with 10046 event, the fourth parameter sets the trace level(12 is the biggest):

 begin
    sys.dbms_system.set_ev(sid, serial#, 10046, 12, '');
 end;

--turn off tracing with setting zero level:

begin
   sys.dbms_system.set_ev(sid, serial#, 10046, 0, '');
end;

/*possible levels: 0 - turned off 1 - minimal level. Much like set sql_trace=true 4 - bind variables values are added to trace file 8 - waits are added 12 - both bind variable values and wait events are added */

--same if you want to trace your own session with bigger level:

alter session set events '10046 trace name context forever, level 12';

--turn off:

alter session set events '10046 trace name context off';

--file with raw trace information will be located:

 select value from v$parameter p
 where name='user_dump_dest'

--name of the file(*.trc) will contain spid:

 select p.spid from v$session s, v$process p
 where s.paddr=p.addr
 and ...your_search_params...

--also you can set the name by yourself:

alter session set tracefile_identifier='UniqueString'; 

--finally, use TKPROF to make trace file more readable:

C:\ORACLE\admin\databaseSID\udump>
C:\ORACLE\admin\databaseSID\udump>tkprof my_trace_file.trc output=my_file.prf
TKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
C:\ORACLE\admin\databaseSID\udump>

--to view state of trace file use:

set serveroutput on size 30000;
declare
  ALevel binary_integer;
begin
  SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel);
  if ALevel = 0 then
    DBMS_OUTPUT.Put_Line('sql_trace is off');
  else
    DBMS_OUTPUT.Put_Line('sql_trace is on');
  end if;
end;
/

Just kind of translated http://www.sql.ru/faq/faq_topic.aspx?fid=389 Original is fuller, but anyway this is better than what others posted IMHO

How can I get onclick event on webview in android?

On Click event On webView works in onTouch like this:

imagewebViewNewsChart.setOnTouchListener(new View.OnTouchListener(){

  @Override   
  public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction()==MotionEvent.ACTION_MOVE){                        
       return false;     
    }

    if (event.getAction()==MotionEvent.ACTION_UP){    
        startActivity(new Intent(this,Example.class));                

    } 

    return false;                 
  }                       
});

How can I call PHP functions by JavaScript?

If you actually want to send data to a php script for example you can do this:

The php:

<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized

echo $a + $b;
?>

Js (using jquery):

$.post("/path/to/above.php", {a: something, b: something}, function(data){                                          
  $('#somediv').html(data);
});

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

Can I access variables from another file?

This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)

WPF: Create a dialog / prompt

You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin, Height, Width properties set in the XAML, but should be enough to show how to get this done at a basic level.

XAML
Build a Window page like you would normally and add your fields to it, say a Label and TextBox control inside a StackPanel:

<StackPanel Orientation="Horizontal">
    <Label Name="lblUser" Content="User Name:" />
    <TextBox Name="txtUser" />
</StackPanel>

Then create a standard Button for Submission ("OK" or "Submit") and a "Cancel" button if you like:

<StackPanel Orientation="Horizontal">
    <Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
    <Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>

Code-Behind
You'll add the Click event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:

public static string strUserName = String.Empty;

Then, for the event handler functions (right-click the Click function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

Calling It From Another Page
You're thinking, if I close my window with that this.Close() up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/

They had a similar example to this (I cleaned it up a bit) of how to open your Window from another and retrieve the values:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
    {
        MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page

        //ShowDialog means you can't focus the parent window, only the popup
        popup.ShowDialog(); //execution will block here in this method until the popup closes

        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:

public static bool cancelled = false;

And let's include our btnCancel_Click event handler, and make one change to btnSubmit_Click:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{        
    cancelled = true;
    strUserName = String.Empty;
    this.Close();
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        cancelled = false;  // <-- I add this in here, just in case
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

And then we just read that variable in our MainWindow btnOpenPopup_Click event:

private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
    MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page
    //ShowDialog means you can't focus the parent window, only the popup
    popup.ShowDialog(); //execution will block here in this method until the popup closes

    // **Here we find out if we cancelled or not**
    if (popup.cancelled == true)
        return;
    else
    {
        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Long response, but I wanted to show how easy this is using public static variables. No DialogResult, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.

How to return temporary table from stored procedure

What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.

An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.

You can find an example here

how do I insert a column at a specific column index in pandas?

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

Animate element transform rotate

Just use CSS transitions:

$(element).css( { transition: "transform 0.5s",
                  transform:  "rotate(" + amount + "deg)" } );

setTimeout( function() { $(element).css( { transition: "none" } ) }, 500 );

As example I set the duration of the animation to 0.5 seconds.

Note the setTimeout to remove the transition css property after the animation is over (500 ms)


For readability I omitted vendor prefixes.

This solution requires browser's transition support off course.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

What are the dark corners of Vim your mom never told you about?

set colorcolumn=+1 or set cc=+1 for vim 7.3

Check if a given time lies between two times regardless of date

strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.

if(($to < $from && ($time >= $from || $time <= $to)) ||
    ($time >= $from && $time <= $to)) {
    return true;
}

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Number of processors/cores in command line

This is for those who want to a portable way to count cpu cores on *bsd, *nix or solaris (haven't tested on aix and hp-ux but should work). It has always worked for me.

dmesg | \
egrep 'cpu[. ]?[0-9]+' | \
sed 's/^.*\(cpu[. ]*[0-9]*\).*$/\1/g' | \
sort -u | \
wc -l | \
tr -d ' '

solaris grep & egrep don't have -o option so sed is used instead.

Remove URL parameters without refreshing page

None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:

/**
* Removes URL parameters
* @param removeParams - param array
*/
function removeURLParameters(removeParams) {
  const deleteRegex = new RegExp(removeParams.join('=|') + '=')

  const params = location.search.slice(1).split('&')
  let search = []
  for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])

  window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
}

removeURLParameters(['param1', 'param2'])

Getting the WordPress Post ID of current post

you can use $post->ID for current id.

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

How to kill zombie process

A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by pid 1, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and wait on them to determine their exit status.

An example of how you might send a signal to every process that is the parent of a zombie (note that this is extremely crude and might kill processes that you do not intend. I do not recommend using this sort of sledge hammer):

# Don't do this.  Incredibly risky sledge hammer!
kill $(ps -A -ostat,ppid | awk '/[zZ]/ && !a[$2]++ {print $2}')

Calculating Distance between two Latitude and Longitude GeoCoordinates

When CPU/math computing power is limited:

There are times (such as in my work) when computing power is scarce (e.g. no floating point processor, working with small microcontrollers) where some trig functions can take an exorbitant amount of CPU time (e.g. 3000+ clock cycles), so when I only need an approximation, especially if if the CPU must not be tied up for a long time, I use this to minimize CPU overhead:

/**------------------------------------------------------------------------
 * \brief  Great Circle distance approximation in km over short distances.
 *
 * Can be off by as much as 10%.
 *
 * approx_distance_in_mi = sqrt(x * x + y * y)
 *
 * where x = 69.1 * (lat2 - lat1)
 * and y = 69.1 * (lon2 - lon1) * cos(lat1/57.3)
 *//*----------------------------------------------------------------------*/
double    ApproximateDisatanceBetweenTwoLatLonsInKm(
                  double lat1, double lon1,
                  double lat2, double lon2
                  ) {
    double  ldRadians, ldCosR, x, y;

    ldRadians = (lat1 / 57.3) * 0.017453292519943295769236907684886;
    ldCosR = cos(ldRadians);
    x = 69.1 * (lat2 - lat1);
    y = 69.1 * (lon2 - lon1) * ldCosR;

    return sqrt(x * x + y * y) * 1.609344;  /* Converts mi to km. */
}

Credit goes to https://github.com/kristianmandrup/geo_vectors/blob/master/Distance%20calc%20notes.txt.

How to convert a table to a data frame

While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable)). Using the example from @X.X:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> data.frame(rbind(freq_t))
  X3 X4 X5
4  1  8  2
6  2  4  1
8 12  0  2

If the column names do not start with numbers, the X won't get added to the front of them.

How to get start and end of day in Javascript?

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

alert( start.toUTCString() + ':' + end.toUTCString() );

If you need to get the UTC time from those, you can use UTC().

How to suppress Update Links warning?

Open the VBA Editor of Excel and type this in the Immediate Window (See Screenshot)

Application.AskToUpdateLinks = False 

Close Excel and then open your File. It will not prompt you again. Remember to reset it when you close the workbook else it will not work for other workbooks as well.

ScreenShot:

enter image description here

EDIT

So applying it to your code, your code will look like this

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

FOLLOWUP

Sigil, The code below works on files with broken links as well. Here is my test code.

Test Conditions

  1. Create 2 new files. Name them Sample1.xlsx and Sample2.xlsx and save them on C:\
  2. In cell A1 of Sample1.xlsx, type this formula ='C:\[Sample2.xlsx]Sheet1'!$A$1
  3. Save and close both the files
  4. Delete Sample2.xlsx!!!
  5. Open a New workbook and it's module paste this code and run Sample. You will notice that you will not get a prompt.

Code

Option Explicit

Sub Sample()
    getWorkbook "c:\Sample1.xlsx"
End Sub

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

Want to show/hide div based on dropdown box selection

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
           $("#business_new").hide();
        $("#business").show();
      }
      else  if ( this.value == '2')
      {
          $("#business").hide();
        $("#business_new").show();
      }
       else  
      {
        $("#business").hide();
      }
    });
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>

Node.js Logging

Winston is a pretty good logging library. You can write logs out to a file using it.

Code would look something like:

var winston = require('winston');

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
  ],
  exceptionHandlers: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
  ],
  exitOnError: false
});

module.exports = logger;

You can then use this like:

var logger = require('./log');

logger.info('log to file');

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

Bootstrap radio button "checked" flag

Assuming you want a default button checked.

<div class="row">
    <h1>Radio Group #2</h1>
    <label for="year" class="control-label input-group">Year</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="year" value="2011">2011
        </label>
        <label class="btn btn-default">
            <input type="radio" name="year" value="2012">2012
        </label>
        <label class="btn btn-default active">
            <input type="radio" name="year" value="2013" checked="">2013
        </label>
    </div>
  </div>

Add the active class to the button (label tag) you want defaulted and checked="" to its input tag so it gets submitted in the form by default.

Best way to do multiple constructors in PHP

The solution of Kris is really nice, but I prefer a mix of factory and fluent style:

<?php

class Student
{

    protected $firstName;
    protected $lastName;
    // etc.

    /**
     * Constructor
     */
    public function __construct() {
        // allocate your stuff
    }

    /**
     * Static constructor / factory
     */
    public static function create() {
        return new self();
    }

    /**
     * FirstName setter - fluent style
     */
    public function setFirstName($firstName) {
        $this->firstName = $firstName;
        return $this;
    }

    /**
     * LastName setter - fluent style
     */
    public function setLastName($lastName) {
        $this->lastName = $lastName;
        return $this;
    }

}

// create instance
$student= Student::create()->setFirstName("John")->setLastName("Doe");

// see result
var_dump($student);
?>

Center-align a HTML table

For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.

In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center" attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class or you can put the style inline with the HTML. Here are the two options:

  1. With a class:

    <table class="centerTable"></table>

In your style.css file you would have something like this:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:

    <table style="margin: 0px auto;"></table>

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.

How to verify if nginx is running or not?

None of the above answers worked for me so let me share my experience. I am running nginx in a docker container that has a port mapping (hostPort:containerPort) - 80:80 The above answers are giving me strange console output. Only the good old 'nmap' is working flawlessly even catching the nginx version. The command working for me is:

 nmap -sV localhost -p 80

We are doing nmap using the -ServiceVersion switch on the localhost and port: 80. It works great for me.

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

How to use JavaScript with Selenium WebDriver Java

Following code worked for me:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

This just happened to me in a string assignment using double quotes. I was missing a closing curly on a POST variable...

"for {$_POST['txtName'] on $date";

should have been

"for {$_POST['txtName']} on $date";

I can't explain why. I mean, I see the error that would break the code but I don't see why it references a class error.

NodeJs : TypeError: require(...) is not a function

Remember to export your routes.js.

In routes.js, write your routes and all your code in this function module:

exports = function(app, passport) {

/* write here your code */ 

}

React Native: Possible unhandled promise rejection

In My case, I am running a local Django backend in IP 127.0.0.1:8000 with Expo start. Just make sure you have the server in public domain not hosted lcoally on your machine

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.

$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.8.0_171, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home

Then, in your .bash_profile add the following.

# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

Now if you try java -version again, you should see the version you want.

$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

Skip first couple of lines while reading lines in Python file

This solution helped me to skip the number of lines specified by the linetostart variable. You get the index (int) and the line (string) if you want to keep track of those too. In your case, you substitute linetostart with 18, or assign 18 to linetostart variable.

f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
    #Your code