Programs & Examples On #Virtual directory

Calculating the position of points in a circle

Based on the answer above from Daniel, here's my take using Python3.

import numpy


def circlepoints(points,radius,center):
    shape = []
    slice = 2 * 3.14 / points
    for i in range(points):
        angle = slice * i
        new_x = center[0] + radius*numpy.cos(angle)
        new_y = center[1] + radius*numpy.sin(angle)

        p = (new_x,new_y)
        shape.append(p)

    return shape

print(circlepoints(100,20,[0,0]))

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

Is quitting an application frowned upon?

I think the point is that there is no need to quit the app unless you have buggy software. Android quits the app when the user is not using it and the device needs more memory. If you have an app that needs to run a service in the background, you will likely want a way to turn the service off.

For example, Google Listen continues to play podcast when the app is not visible. But there is always the pause button to turn the podcast off when the user is done with it. If I remember correctly, Listen, even puts a shortcut in the notification bar so you can always get to the pause button quickly. Another example is an app like a twitter app for instance which constantly polls a service on the internet. These types of apps should really allow the user to choose how often to poll the server, or whether even to poll in a background thread.

If you need to have code that runs on exit, you can override onPause(), onStop(), or onDestroy() as appropriate. http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Getting Image from URL (Java)

This code worked fine for me.

 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URL;

public class SaveImageFromUrl {

public static void main(String[] args) throws Exception {
    String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
    String destinationFile = "image.jpg";

    saveImage(imageUrl, destinationFile);
}

public static void saveImage(String imageUrl, String destinationFile) throws IOException {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

}

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

C++ static virtual members?

It is possible!

But what exactly is possible, let's narrow down. People often want some kind of "static virtual function" because of duplication of code needed for being able to call the same function through static call "SomeDerivedClass::myfunction()" and polymorphic call "base_class_pointer->myfunction()". "Legal" method for allowing such functionality is duplication of function definitions:

class Object
{
public:
    static string getTypeInformationStatic() { return "base class";}
    virtual string getTypeInformation() { return getTypeInformationStatic(); }
}; 
class Foo: public Object
{
public:
    static string getTypeInformationStatic() { return "derived class";}
    virtual string getTypeInformation() { return getTypeInformationStatic(); }
};

What if base class has a great number of static functions and derived class has to override every of them and one forgot to provide a duplicating definition for virtual function. Right, we'll get some strange error during runtime which is hard to track down. Cause duplication of code is a bad thing. The following tries to resolve this problem (and I want to tell beforehand that it is completely type-safe and doesn't contain any black magic like typeid's or dynamic_cast's :)

So, we want to provide only one definition of getTypeInformation() per derived class and it is obvious that it has to be a definition of static function because it is not possible to call "SomeDerivedClass::getTypeInformation()" if getTypeInformation() is virtual. How can we call static function of derived class through pointer to base class? It is not possible with vtable because vtable stores pointers only to virtual functions and since we decided not to use virtual functions, we cannot modify vtable for our benefit. Then, to be able to access static function for derived class through pointer to base class we have to store somehow the type of an object within its base class. One approach is to make base class templatized using "curiously recurring template pattern" but it is not appropriate here and we'll use a technique called "type erasure":

class TypeKeeper
{
public:
    virtual string getTypeInformation() = 0;
};
template<class T>
class TypeKeeperImpl: public TypeKeeper
{
public:
    virtual string getTypeInformation() { return T::getTypeInformationStatic(); }
};

Now we can store the type of an object within base class "Object" with a variable "keeper":

class Object
{
public:
    Object(){}
    boost::scoped_ptr<TypeKeeper> keeper;

    //not virtual
    string getTypeInformation() const 
    { return keeper? keeper->getTypeInformation(): string("base class"); }

};

In a derived class keeper must be initialized during construction:

class Foo: public Object
{
public:
    Foo() { keeper.reset(new TypeKeeperImpl<Foo>()); }
    //note the name of the function
    static string getTypeInformationStatic() 
    { return "class for proving static virtual functions concept"; }
};

Let's add syntactic sugar:

template<class T>
void override_static_functions(T* t)
{ t->keeper.reset(new TypeKeeperImpl<T>()); }
#define OVERRIDE_STATIC_FUNCTIONS override_static_functions(this)

Now declarations of descendants look like:

class Foo: public Object
{
public:
    Foo() { OVERRIDE_STATIC_FUNCTIONS; }
    static string getTypeInformationStatic() 
    { return "class for proving static virtual functions concept"; }
};

class Bar: public Foo
{
public:
    Bar() { OVERRIDE_STATIC_FUNCTIONS; }
    static string getTypeInformationStatic() 
    { return "another class for the same reason"; }
};

usage:

Object* obj = new Foo();
cout << obj->getTypeInformation() << endl;  //calls Foo::getTypeInformationStatic()
obj = new Bar();
cout << obj->getTypeInformation() << endl;  //calls Bar::getTypeInformationStatic()
Foo* foo = new Bar();
cout << foo->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo::getTypeInformation(); //compile-time error
Foo::getTypeInformationStatic(); //calls Foo::getTypeInformationStatic()
Bar::getTypeInformationStatic(); //calls Bar::getTypeInformationStatic()

Advantages:

  1. less duplication of code (but we have to call OVERRIDE_STATIC_FUNCTIONS in every constructor)

Disadvantages:

  1. OVERRIDE_STATIC_FUNCTIONS in every constructor
  2. memory and performance overhead
  3. increased complexity

Open issues:

1) there are different names for static and virtual functions how to solve ambiguity here?

class Foo
{
public:
    static void f(bool f=true) { cout << "static";}
    virtual void f() { cout << "virtual";}
};
//somewhere
Foo::f(); //calls static f(), no ambiguity
ptr_to_foo->f(); //ambiguity

2) how to implicitly call OVERRIDE_STATIC_FUNCTIONS inside every constructor?

HTML img align="middle" doesn't align an image

Change 'middle' to 'center'. Like so:

<img align="center" ....>

How to find the files that are created in the last hour in unix

UNIX filesystems (generally) don't store creation times. Instead, there are only access time, (data) modification time, and (inode) change time.

That being said, find has -atime -mtime -ctime predicates:

$ man 1 find
...
-ctime  n
        The primary shall evaluate as true if the time of last change of
        file status information subtracted from the initialization time,
        divided by 86400 (with any remainder discarded), is n.
...

Thus find -ctime 0 finds everything for which the inode has changed (e.g. includes file creation, but also counts link count and permissions and filesize change) less than an hour ago.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

You can skip the Performance counter check in the setup altogether:

setup.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

T-SQL How to create tables dynamically in stored procedures?

First up, you seem to be mixing table variables and tables.

Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.

If you just want to declare a table variable:

CREATE PROC sp_createATable 
  @name        VARCHAR(10), 
  @properties  VARCHAR(500) 
AS 
  declare @tablename TABLE
  ( 
    id  CHAR(10)  PRIMARY KEY 
  ); 

The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.

Hide vertical scrollbar in <select> element

I know this thread is somewhat old, but there are a lot of really hacky answers on here, so I'd like to provide something that is a lot simpler and a lot cleaner:

select {
    overflow-y: auto;
}

As you can see in this fiddle, this solution provides you with flexibility if you don't know the exact number of select options you are going to have. It hides the scrollbar in the case that you don't need it without hiding possible extra option elements in the other case. Don't do all this hacky overlapping div stuff. It just makes for unreadable markup.

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Here is the one of methods to avoid duplicates into javascript array...and it supports for strings and numbers...

 var unique = function(origArr) {
    var newArray = [],
        origLen = origArr.length,
        found,
        x = 0; y = 0;

    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArray.length; y++ ) {
            if ( origArr[x] === newArray[y] ) found = true;
        }
        if ( !found) newArray.push( origArr[x] );    
    }
   return newArray;
}

check this fiddle..

Minimal web server using netcat

If you're using Apline Linux, the BusyBox netcat is slightly different:

while true; do nc -l -p 8080 -e sh -c 'echo -e "HTTP/1.1 200 OK\n\n$(date)"'; done

And another way using printf:

while true; do nc -l -p 8080 -e sh -c "printf 'HTTP/1.1 200 OK\n\n%s' \"$(date)\""; done

Difference between SelectedItem, SelectedValue and SelectedValuePath

To answer a little more conceptually:

SelectedValuePath defines which property (by its name) of the objects bound to the ListBox's ItemsSource will be used as the item's SelectedValue.

For example, if your ListBox is bound to a collection of Person objects, each of which has Name, Age, and Gender properties, SelectedValuePath=Name will cause the value of the selected Person's Name property to be returned in SelectedValue.

Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath cannot be used.

SelectedItem, meanwhile, returns the entire Person object currently selected.

(Here's a further example from MSDN, using TreeView)

Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:

Note that these values are distinct from DisplayMemberPath (which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.

GitHub "fatal: remote origin already exists"

for using git you have to be

root

if not then use sudo

for removing origin :

git remote remove origin

for adding origin :

git remote add origin http://giturl

Get the last non-empty cell in a column in Google Sheets

for a row:

=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))

for a column:

=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))

Best way to structure a tkinter application?

Probably the best way to learn how to structure your program is by reading other people's code, especially if it's a large program to which many people have contributed. After looking at the code of many projects, you should get an idea of what the consensus style should be.

Python, as a language, is special in that there are some strong guidelines as to how you should format your code. The first is the so-called "Zen of Python":

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

On a more practical level, there is PEP8, the style guide for Python.

With those in mind, I would say that your code style doesn't really fit, particularly the nested functions. Find a way to flatten those out, either by using classes or moving them into separate modules. This will make the structure of your program much easier to understand.

Can linux cat command be used for writing text to file?

simply pipeline echo with cat

For example

echo write something to file.txt | cat > file.txt

Java 8: merge lists with stream API

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

Number format in excel: Showing % value without multiplying with 100

Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.

The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.

The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type

5.66%

into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.

select2 changing items dynamically

I'm successfully using the following to update options dynamically:

$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});

Create random list of integers in Python

Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

You could use

[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]

to generate 10,000 numbers in the range using sample 10 times.

(Of course this won't beat NumPy.)

$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop

$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
100 loops, best of 3: 9.24 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop

$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
>   a = range(x)
>   shuffle(a)
>   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop

$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop

But since you don't care about the distribution of numbers, why not just use:

range(1000)*(10000/1000)

?

sql delete statement where date is greater than 30 days

You could also use

SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY;

Unexpected token < in first line of HTML

I had this problem in an ASP.NET application, specifically a Web Forms.

I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:

VB.NET

If Not Response.IsRequestBeingRedirected _
    And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
    And Not Request.Url.AbsoluteUri.Contains(".css") _
    And Not Request.Url.AbsoluteUri.Contains(".js") _
    And Not Request.Url.AbsoluteUri.Contains("images/") _
    And Not Request.Url.AbsoluteUri.Contains("favicon") Then
        Response.Redirect("~/change-password.aspx")
End If

I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.

How to install xgboost in Anaconda Python (Windows platform)?

I was able to install xgboost for Python in Windows yesterday by following this link. But when I tried to import using Anaconda, it failed. I recognized this is due to the fact that Anaconda has a different Python distribution. I then searched again and found this great article which made it!

The trick is after installing successfully for regular Python, to have it work for Anaconda, you just need to pull up the Anaconda prompt and cd into this folder "code\xgboost\python-package", then run:

python setup.py install

And voila! The article says you need to add the path, but for me it worked directly. Good luck!

Also copied below the original contents in case the link is not available...

Once the last command completes the build is done. We can now install the Python module. What follows depends on the Python distribution you are using. For Anaconda, I will simply use the Anaconda prompt, and type the following in it (after the prompt, in my case [Anaconda3] C:\Users\IBM_ADMIN>):

[Anaconda3] C:\Users\IBM_ADMIN>cd code\xgboost\python-package
The point is to move to the python-package directory of XGBoost.  Then type:
[Anaconda3] C:\Users\IBM_ADMIN\code\xgboost\python-package>python setup.py install

We are almost done. Let's launch a notebook to test XGBoost. Importing it directly causes an error. In order to avoid it we must add the path to the g++ runtime libraries to the os environment path variable with:

import os

mingw_path = 'C:\\Program Files\\mingw-w64\\x86_64-5.3.0-posix-seh-rt_v4-rev0\\mingw64\\bin'

os.environ['PATH'] = mingw_path + ';' + os.environ['PATH']

We can then import xgboost and run a small example.

import xgboost as xgb 
import numpy as np
data = np.random.rand(5,10) # 5 entities, each contains 10 features
label = np.random.randint(2, size=5) # binary target
dtrain = xgb.DMatrix( data, label=label)

dtest = dtrain

param = {'bst:max_depth':2, 'bst:eta':1, 'silent':1, 'objective':'binary:logistic' }
param['nthread'] = 4
param['eval_metric'] = 'auc'

evallist  = [(dtest,'eval'), (dtrain,'train')]

num_round = 10
bst = xgb.train( param, dtrain, num_round, evallist )

bst.dump_model('dump.raw.txt')

We are all set!

How do I verify that an Android apk is signed with a release certificate?

Use this command, (go to java < jdk < bin path in cmd prompt)

$ jarsigner -verify -verbose -certs my_application.apk

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html

How do you run a script on login in *nix?

If you wish to run one script and only one script, you can make it that users default shell.

echo "/usr/bin/uptime" >> /etc/shells
vim /etc/passwd  
  * username:x:uid:grp:message:homedir:/usr/bin/uptime

can have interesting effects :) ( its not secure tho, so don't trust it too much. nothing like setting your default shell to be a script that wipes your drive. ... although, .. I can imagine a scenario where that could be amazingly useful )

Vector of structs initialization

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

But I found new to do this using default_structure_element like following...

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

how to change the dist-folder path in angular-cli after 'ng build'

The only thing that worked for me was to change outDir in in both angular-cli.json AND src/tsconfig.json.

I wanted my dist-folder outside the angular project folder. If I didn't change the setting in src/tsconfig.json as well, Angular CLI would throw warnings whenever I build the project.

Here are the most important lines ...

// angular-cli.json
{
  ...
  "apps": [
    {
      "outDir": "../dist",
      ...
    }
  ],
  ...
}

And ...

// tsconfig.json
{
  "compilerOptions": {
    "outDir": "../../dist/out-tsc",
    ...
  }
}

How to check the exit status using an if statement

Just to add to the helpful and detailed answer:

If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:

run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }

Or, use a case statement:

run_some_command; ec=$?  # grab the exit code into a variable so that it can
                         # be reused later, without the fear of being overwritten
case $ec in
    0) ;;
    1) printf '%s\n' "Command exited with non-zero"; exit 1;;
    *) do_something_else;;
esac

Related answer about error handling in Bash:

Apply jQuery datepicker to multiple instances

The obvious answer would be to generate different ids, a separate id for each text box, something like

[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>

I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.

Then, you have to find a way to generate as many

$('#my_date[i]').datepicker();

as items in your Model.MyRecords. Again, within square brackets is your counter, so your jQuery function would be something like:

<script type="text/javascript">
    $(function() {
        $('#my_date1').datepicker();
        $('#my_date2').datepicker();
        $('#my_date3').datepicker();
        ...
    });
</script>

Calling dynamic function with dynamic number of parameters

In case somebody is still looking for dynamic function call with dynamic parameters -

callFunction("aaa('hello', 'world')");

    function callFunction(func) {
                try
                {
                    eval(func);
                }
                catch (e)
                { }
            }
    function aaa(a, b) {
                alert(a + ' ' + b);
            }

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I've had a same problem with react-redux types. The simplest solution was add to tsconfig.json:

"noImplicitAny": false

Example:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "noImplicitAny": false,
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}

How do I convert a IPython Notebook into a Python file via commandline?

There's a very nice package called nb_dev which is designed for authoring Python packages in Jupyter Notebooks. Like nbconvert, it can turn a notebook into a .py file, but it is more flexible and powerful because it has a lot of nice additional authoring features to help you develop tests, documentation, and register packages on PyPI. It was developed by the fast.ai folks.

It has a bit of a learning curve, but the documentation is good and it is not difficult overall.

Interface or an Abstract Class: which one to use?

Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.

  • I have multiple abstract classes which handle the standard crud and also some specialty functionality like conversion and streaming for different categories of files.
  • The file access interface defines a common set of methods which are needed to get, store and delete a file.

This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.

Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.

How do I remove all non-ASCII characters with regex and Notepad++?

Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

How to pass multiple values to single parameter in stored procedure

I spent time finding a proper way. This may be useful for others.

Create a UDF and refer in the query -

http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm

pass array to method Java

You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

How can I introduce multiple conditions in LIKE operator?

Even u can try this

Function

CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

Query

select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';

Android "hello world" pushnotification example

Update 2016:

GCM is being replaced with FCM

Update 2015:

Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To

Update 2014:

1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.

2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.

3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.

First Answer 2014

Here is a good question you may should have a look at it: How to add a push notification in my own android app

Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/

Convert a String of Hex into ASCII in Java

Easiest way to do it with javax.xml.bind.DatatypeConverter:

    String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
    byte[] s = DatatypeConverter.parseHexBinary(hex);
    System.out.println(new String(s));

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Had the same error because I forgot to send a correct header a first

header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

How to include view/partial specific styling in AngularJS

@tennisgent's solution is great. However, I think is a little limited.

Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

For a full solution I suggest using AngularCSS.

  1. Supports Angular's ngRoute, UI Router, directives, controllers and services.
  2. Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  3. You can customize where the stylesheets are injected: head, body, custom selector, etc...
  4. Supports preloading, persisting and cache busting
  5. Supports media queries and optimizes page load via matchMedia API

https://github.com/door3/angular-css

Here are some examples:

Routes

  $routeProvider
    .when('/page1', {
      templateUrl: 'page1/page1.html',
      controller: 'page1Ctrl',
      /* Now you can bind css to routes */
      css: 'page1/page1.css'
    })
    .when('/page2', {
      templateUrl: 'page2/page2.html',
      controller: 'page2Ctrl',
      /* You can also enable features like bust cache, persist and preload */
      css: {
        href: 'page2/page2.css',
        bustCache: true
      }
    })
    .when('/page3', {
      templateUrl: 'page3/page3.html',
      controller: 'page3Ctrl',
      /* This is how you can include multiple stylesheets */
      css: ['page3/page3.css','page3/page3-2.css']
    })
    .when('/page4', {
      templateUrl: 'page4/page4.html',
      controller: 'page4Ctrl',
      css: [
        {
          href: 'page4/page4.css',
          persist: true
        }, {
          href: 'page4/page4.mobile.css',
          /* Media Query support via window.matchMedia API
           * This will only add the stylesheet if the breakpoint matches */
          media: 'screen and (max-width : 768px)'
        }, {
          href: 'page4/page4.print.css',
          media: 'print'
        }
      ]
    });

Directives

myApp.directive('myDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'my-directive/my-directive.html',
    css: 'my-directive/my-directive.css'
  }
});

Additionally, you can use the $css service for edge cases:

myApp.controller('pageCtrl', function ($scope, $css) {

  // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
  $css.bind({ 
    href: 'my-page/my-page.css'
  }, $scope);

  // Simply add stylesheet(s)
  $css.add('my-page/my-page.css');

  // Simply remove stylesheet(s)
  $css.remove(['my-page/my-page.css','my-page/my-page2.css']);

  // Remove all stylesheets
  $css.removeAll();

});

You can read more about AngularCSS here:

http://door3.com/insights/introducing-angularcss-css-demand-angularjs

How to fix Error: listen EADDRINUSE while using nodejs?

I have the same problem too,and I simply close the terminal and open a new terminal and run

node server.js

again. that works for me, some time just need to wait for a few second till it work again.

But this works only on a developer machine instead of a server console..

Multiple github accounts on the same computer?

I use shell scripts to switch me to whatever account I want to be "active". Essentially you start from a fresh start, get one account configured properly and working, then move the these files to a name with the proper prefix. From then on you can use the command "github", or "gitxyz" to switch:

# my github script
cd ~/.ssh

if [ -f git_dhoerl -a -f git_dhoerl.pub -a -f config_dhoerl ]
then
    ; 
else 
    echo "Error: missing new files"
    exit 1
fi 

# Save a copy in /tmp, just in case
cp id_rsa /tmp
cp id_rsa.pub /tmp
cp config /tmp
echo "Saved old files in /tmp, just in case"

rm id_rsa
rm id_rsa.pub
rm config
echo "Removed current links/files"

ln git_dhoerl id_rsa
ln git_dhoerl.pub id_rsa.pub
ln config_dhoerl config

git config --global user.email "dhoerl@<company>.com"
git config --global github.user "dhoerl"        
git config --global github.token "whatever_it_is"

ssh-add -D

I've had great luck with this. I also created a run script in Xcode (for you Mac users) so it would not build my project unless I had the proper setting (since its using git):

Run Script placed after Dependencies (using /bin/ksh as the shell):

if [ "$(git config --global --get user.email)" != "dhoerl@<company>.com" ]
then
    exit 1
fi

EDIT: added tests for new files existence and copying old files to /tmp to address comment by @naomik below.

Sending JWT token in the headers with Postman

I am adding to this question a little interesting tip that may help you guys testing JWT Apis.

Its is very simple actually.

When you log in, in your Api (login endpoint), you will immediately receive your token, and as @mick-cullen said you will have to use the JWT on your header as:

Authorization: Bearer TOKEN_STRING

Now if you like to automate or just make your life easier, your tests you can save the token as a global that you can call on all other endpoints as:

Authorization: Bearer {{jwt_token}}

On Postman: Then make a Global variable in postman as jwt_token = TOKEN_STRING.

On your login endpoint: To make it useful, add on the beginning of the Tests Tab add:

var data = JSON.parse(responseBody);
postman.clearGlobalVariable("jwt_token");
postman.setGlobalVariable("jwt_token", data.jwt_token);

I am guessing that your api is returning the token as a json on the response as: {"jwt_token":"TOKEN_STRING"}, there may be some sort of variation.

On the first line you add the response to the data varibale. Clean your Global And assign the value.

So now you have your token on the global variable, what makes easy to use Authorization: Bearer {{jwt_token}} on all your endpoints.

Hope this tip helps.


EDIT
Something to read

About tests on Postman: testing examples

Command Line: Newman

CI: integrating with Jenkins

Nice blog post: master api test automation

Running interactive commands in Paramiko

I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.

I dug around and found this article:

Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

To continue your example you could do

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()

The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.

Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

Lumen: get URL parameter in a Blade view

More simple in Laravel 5.7 and 5.8

{{ Request()->parameter }}

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

It looks like a permissions issue - not a Windows 7 issue.

Your ssh key is not authorised - Permission denied (publickey).

You need to create a public ssh key and ask the administrator of the Git repository to add the ssh public key

Information on how to do this: Saving ssh key fails

How to serialize Joda DateTime with Jackson JSON processor?

As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule on your ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

For custom serialization/de-serialization of DateTime, you need to implement your own StdScalarSerializer and StdScalarDeserializer; it's pretty convoluted, but anyway.

For example, here's a DateTime serializer that uses the ISODateFormat with the UTC time zone:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

And the corresponding de-serializer:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

Then tie these together with a module:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

Then register the module on your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Getting the ID of the element that fired an event

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

HTTP Error 500.19 and error code : 0x80070021

Well, we're using Amazon Web Services and so we are looking to use scripts and programs to get through this problem. So I have been on the hunt for a command line tool. So first I tried the trick of running

c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

but because I'm running a cloud based Windows Server 2012 it complained

This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.

and I Googled and found the official Microsoft Support Page KB2736284. So there is a command line tool dism.exe. So I tried the following

dism /online /enable-feature /featurename:IIS-ASPNET45

but it complained and gave a list of featurenames to try, so I tried them one by one and I tested my WebAPI webpage after each and it worked after the bottom one in the list.

dism /online /enable-feature /featurename:IIS-ApplicationDevelopment
dism /online /enable-feature /featurename:IIS-ISAPIFilter 
dism /online /enable-feature /featurename:IIS-ISAPIExtensions 
dism /online /enable-feature /featurename:IIS-NetFxExtensibility45 

And so now I can browse to my WebAPI site and see the API information. That should help a few people. [However, I am not out of the woods totally myself yet and I cannot reach the website from outside the box. Still working on it.]

Also, I did some earlier steps following other people responses. I can confirm that the following Feature Delegation needs to be change (though I'd like to find a command line tool for these).

In Feature delegation

Change 
'Handler Mappings' from Read Only to Read/Write

Change 
'Modules' from Read Only to Read/Write

Change 
'SSL Settings' from Read Only to Read/Write

HTML input arrays

It's just PHP, not HTML.

It parses all HTML fields with [] into an array.

So you can have

<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />

and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

echo $_POST['food'][0]; // would output first checkbox selected

or to see all values selected:

foreach( $_POST['food'] as $value ) {
    print $value;
}

Anyhow, don't think there is a specific name for it

Convert integer value to matching Java Enum

You could add a static method in your enum that accepts an int as a parameter and returns a PcapLinkType.

public static PcapLinkType of(int linkType) {

    switch (linkType) {
        case -1: return DLT_UNKNOWN
        case 0: return DLT_NULL;

        //ETC....

        default: return null;

    }
}

Impact of Xcode build options "Enable bitcode" Yes/No

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.

When you build your project, Xcode invokes clang for Objective-C targets and swift/swiftc for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.

The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.

When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.

Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.

  • Are there any performance impacts if I enable / disable it?

There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.

As for positive impacts… well that's complicated.

For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.

In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.

Excel Date to String conversion

Here is a VBA approach:

Sub change()
    toText Sheets(1).Range("A1:F20")
End Sub

Sub toText(target As Range)
Dim cell As Range
    For Each cell In target
        cell.Value = cell.Text
        cell.NumberFormat = "@"
    Next cell
End Sub

If you are looking for a solution without programming, the Question should be moved to SuperUser.

How do I set up access control in SVN?

You can use svn+ssh:, and then it's based on access control to the repository at the given location.

This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.

Add carriage return to a string

Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

TestNG ERROR Cannot find class in classpath

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION

java -cp "path_copied" org.testng.TestNG testng.xml

If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

moment.js, how to get day of week number

I think this would work

moment().weekday(); //if today is thursday it will return 4

Float a div in top right corner without overlapping sibling header

If you can change the order of the elements, floating will work.

_x000D_
_x000D_
section {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  border: 1px solid;_x000D_
}_x000D_
h1 {_x000D_
  display: inline;_x000D_
}_x000D_
div {_x000D_
  float: right;_x000D_
}
_x000D_
<section>_x000D_
  <div>_x000D_
    <button>button</button>_x000D_
  </div>_x000D_
_x000D_
  <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>_x000D_
</section>
_x000D_
_x000D_
_x000D_

?By placing the div before the h1 and floating it to the right, you get the desired effect.

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

pandas: best way to select all columns whose names start with X

You can try the regex here to filter out the columns starting with "foo"

df.filter(regex='^foo*')

If you need to have the string foo in your column then

df.filter(regex='foo*')

would be appropriate.

For the next step, you can use

df[df.filter(regex='^foo*').values==1]

to filter out the rows where one of the values of 'foo*' column is 1.

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

How to pass data between fragments

So lets say you have Activity AB that controls Frag A and Fragment B. Inside Fragment A you need an interface that Activity AB can implement. In the sample android code, they have:

private Callbacks mCallbacks = sDummyCallbacks;

/*A callback interface that all activities containing this fragment must implement. This mechanism allows activities to be notified of item selections. */

public interface Callbacks {
/*Callback for when an item has been selected. */    
      public void onItemSelected(String id);
}

/*A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when this fragment is not attached to an activity. */    
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

The Callback interface is put inside one of your Fragments (let’s say Fragment A). I think the purpose of this Callbacks interface is like a nested class inside Frag A which any Activity can implement. So if Fragment A was a TV, the CallBacks is the TV Remote (interface) that allows Fragment A to be used by Activity AB. I may be wrong about the detail because I'm a noob but I did get my program to work perfectly on all screen sizes and this is what I used.

So inside Fragment A, we have: (I took this from Android’s Sample programs)

@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
//mCallbacks.onItemSelected( PUT YOUR SHIT HERE. int, String, etc.);
//mCallbacks.onItemSelected (Object);
}

And inside Activity AB we override the onItemSelected method:

public class AB extends FragmentActivity implements ItemListFragment.Callbacks {
//...
@Override
//public void onItemSelected (CATCH YOUR SHIT HERE) {
//public void onItemSelected (Object obj) {
    public void onItemSelected(String id) {
    //Pass Data to Fragment B. For example:
    Bundle arguments = new Bundle();
    arguments.putString(“FragmentB_package”, id);
    FragmentB fragment = new FragmentB();
    fragment.setArguments(arguments);
    getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
    }

So inside Activity AB, you basically throwing everything into a Bundle and passing it to B. If u are not sure how to use a Bundle, look the class up.

I am basically going by the sample code that Android provided. The one with the DummyContent stuff. When you make a new Android Application Package, it's the one titled MasterDetailFlow.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

URL encoding the space character: + or %20?

A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.

In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)

This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

The implementation depends on the programming language that you chose.

If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.

how to declare global variable in SQL Server..?

You could try a global table:

create table ##global_var
            (var1 int
            ,var2 int)

USE "DB_1"
GO
SELECT * FROM "TABLE" WHERE "COL_!" = (select var1 from ##global_var) 

AND "COL_2" = @GLOBAL_VAR_2

USE "DB_2"
GO

SELECT * FROM "TABLE" WHERE "COL_!" = (select var2 from ##global_var) 

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

How do I break out of a loop in Scala?

I am new to Scala, but how about this to avoid throwing exceptions and repeating methods:

object awhile {
def apply(condition: () => Boolean, action: () => breakwhen): Unit = {
    while (condition()) {
        action() match {
            case breakwhen(true)    => return ;
            case _                  => { };
        }
    }
}
case class breakwhen(break:Boolean);

use it like this:

var i = 0
awhile(() => i < 20, () => {
    i = i + 1
    breakwhen(i == 5)
});
println(i)

if you don’t want to break:

awhile(() => i < 20, () => {
    i = i + 1
    breakwhen(false)
});

How to scroll UITableView to specific position

[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This will take your tableview to the first row.

Eclipse - debugger doesn't stop at breakpoint

Also verify if breakpoints on other lines DO work, it may be a bug in the debugger. I have had a problem with the Eclipse debugger where putting a breakpoint on a boolean assignment whose code was on the next line didn't work I reported this here, but putting it on the previous or next line did.

ThreeJS: Remove object from scene

I started to save this as a function, and call it as needed for whatever reactions require it:

function Remove(){
    while(scene.children.length > 0){ 
    scene.remove(scene.children[0]); 
}
}

Now you can call the Remove(); function where appropriate.

Where do I put image files, css, js, etc. in Codeigniter?

Hi our sturucture is like Application, system, user_guide

create a folder name assets just near all the folders and then inside this assets folder create css and javascript and images folder put all your css js insiide the folders

now go to header.php and call the css just like this.

<link rel="stylesheet" href="<?php echo base_url();?>assets/css/touchTouch.css">
  <link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css">
  <link rel="stylesheet" href="<?php echo base_url();?>assets/css/camera.css"> 

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

What is Type-safe?

Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.

In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).

PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).

C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.

Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).

How to annotate MYSQL autoincrement field with JPA annotations

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

Which is what you'd get when using AUTO with MySQL:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

Which is actually equivalent to

@Id @GeneratedValue
private Long id;

In other words, your mapping should work. But Hibernate should omit the id column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.

Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect or MySQL5Dialect depending on the engine you're using)?

Also, who created the table? Can you show the corresponding DDL?

Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:

insert 
into
    Operator
    (active, password, username) 
values
    (?, ?, ?)

Note that the id column is absent from the above statement, as expected.

To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).

Regarding the dialect, the only difference between MySQL5Dialect or MySQL5InnoDBDialect is that the later adds ENGINE=InnoDB to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.

Add a linebreak in an HTML text area

Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!

Laravel 5.1 API Enable Cors

I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT and DELETE) which will be preceded by an OPTIONS request, specifying the middleware in the $routeMiddleware array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS as well. This is because without an OPTIONS route Laravel will internally respond to that method without the CORS headers.

So in short either define the middleware in the $middleware array which runs globally for all requests or if you're doing it in $middlewareGroups or $routeMiddleware then also define a route handler for OPTIONS. This can be done like this:

Route::match(['options', 'put'], '/route', function () {
    // This will work with the middleware shown in the accepted answer
})->middleware('cors');

I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    private static $allowedOriginsWhitelist = [
      'http://localhost:8000'
    ];

    // All the headers must be a string

    private static $allowedOrigin = '*';

    private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';

    private static $allowCredentials = 'true';

    private static $allowedHeaders = '';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if (! $this->isCorsRequest($request))
      {
        return $next($request);
      }

      static::$allowedOrigin = $this->resolveAllowedOrigin($request);

      static::$allowedHeaders = $this->resolveAllowedHeaders($request);

      $headers = [
        'Access-Control-Allow-Origin'       => static::$allowedOrigin,
        'Access-Control-Allow-Methods'      => static::$allowedMethods,
        'Access-Control-Allow-Headers'      => static::$allowedHeaders,
        'Access-Control-Allow-Credentials'  => static::$allowCredentials,
      ];

      // For preflighted requests
      if ($request->getMethod() === 'OPTIONS')
      {
        return response('', 200)->withHeaders($headers);
      }

      $response = $next($request)->withHeaders($headers);

      return $response;
    }

    /**
     * Incoming request is a CORS request if the Origin
     * header is set and Origin !== Host
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function isCorsRequest($request)
    {
      $requestHasOrigin = $request->headers->has('Origin');

      if ($requestHasOrigin)
      {
        $origin = $request->headers->get('Origin');

        $host = $request->getSchemeAndHttpHost();

        if ($origin !== $host)
        {
          return true;
        }
      }

      return false;
    }

    /**
     * Dynamic resolution of allowed origin since we can't
     * pass multiple domains to the header. The appropriate
     * domain is set in the Access-Control-Allow-Origin header
     * only if it is present in the whitelist.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedOrigin($request)
    {
      $allowedOrigin = static::$allowedOrigin;

      // If origin is in our $allowedOriginsWhitelist
      // then we send that in Access-Control-Allow-Origin

      $origin = $request->headers->get('Origin');

      if (in_array($origin, static::$allowedOriginsWhitelist))
      {
        $allowedOrigin = $origin;
      }

      return $allowedOrigin;
    }

    /**
     * Take the incoming client request headers
     * and return. Will be used to pass in Access-Control-Allow-Headers
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedHeaders($request)
    {
      $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');

      return $allowedHeaders;
    }
}

Also written a blog post on this.

PHP is not recognized as an internal or external command in command prompt

You just need to a add the path of your PHP file. In case you are using wamp or have not installed it on the C drive.

The picture shows how to find the path

HTML colspan in CSS

The CSS properties "column-count", "column-gap", and "column-span" can do this in a way that keeps all the columns of the pseudo-table inside the same wrapper (HTML stays nice and neat).

The only caveats are that you can only define 1 column or all columns, and column-span doesn't yet work in Firefox, so some additional CSS is necessary to ensure it will displays correctly. https://www.w3schools.com/css/css3_multiple_columns.asp

_x000D_
_x000D_
.split-me {_x000D_
  -webkit-column-count: 3;_x000D_
  -webkit-column-gap: 0;_x000D_
  -moz-column-count: 3;_x000D_
  -moz-column-gap: 0;_x000D_
  column-count: 3;_x000D_
  column-gap: 0;_x000D_
}_x000D_
_x000D_
.cols {_x000D_
  /* column-span is 1 by default */_x000D_
  column-span: 1;_x000D_
}_x000D_
_x000D_
div.three-span {_x000D_
  column-span: all !important;_x000D_
}_x000D_
_x000D_
/* alternate style for column-span in Firefox */_x000D_
@-moz-document url-prefix(){_x000D_
  .three-span {_x000D_
    position: absolute;_x000D_
    left: 8px;_x000D_
    right: 8px;_x000D_
    top: auto;_x000D_
    width: auto;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
    
_x000D_
<p>The column width stays fully dynamic, just like flex-box, evenly scaling on resize.</p>_x000D_
_x000D_
<div class='split-me'>_x000D_
  <div class='col-1 cols'>Text inside Column 1 div.</div>_x000D_
  <div class='col-2 cols'>Text inside Column 2 div.</div>_x000D_
  <div class='col-3 cols'>Text inside Column 3 div.</div>_x000D_
  <div class='three-span'>Text div spanning 3 columns.</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
  <style>_x000D_
/* Non-Essential Visual Styles */_x000D_
_x000D_
html * { font-size: 12pt; font-family: Arial; text-align: center; }_x000D_
.split-me>* { padding: 5px; } _x000D_
.cols { border: 2px dashed black; border-left: none; }_x000D_
.col-1 { background-color: #ddffff; border-left: 2px dashed black; }_x000D_
.col-2 { background-color: #ffddff; }_x000D_
.col-3 { background-color: #ffffdd; }_x000D_
.three-span {_x000D_
  border: 2px dashed black; border-top: none;_x000D_
  text-align: center; background-color: #ddffdd;_x000D_
}_x000D_
  </style>
_x000D_
_x000D_
_x000D_

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

How to round double to nearest whole number and then convert to a float?

Here is a quick example:

public class One {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double a = 4.56777;
        System.out.println( new Float( Math.round(a)) );

    }

}

the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double values and provides whole long values

Regards

ContractFilter mismatch at the EndpointDispatcher exception

So, my case was the following. I didn't use proxy for the client-server interaction, I used ChannelFactory (thus all the advice to upgrade to service reference was meaningless to me).

The service was hosted in IIS and for some reason it had wrong references in the bin folder there. The project recompilation simply didn't lead to new dlls in that folder.

So I just deleted all the stuff from there and added reference to the service in the same solution, then recompiled and now everything works.

How are POST and GET variables handled in Python?

suppose you're posting a html form with this:

<input type="text" name="username">

If using raw cgi:

import cgi
form = cgi.FieldStorage()
print form["username"]

If using Django, Pylons, Flask or Pyramid:

print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method

Using Turbogears, Cherrypy:

from cherrypy import request
print request.params['username']

Web.py:

form = web.input()
print form.username

Werkzeug:

print request.form['username']

If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

def index(self, username):
    print username

Google App Engine:

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

So you really will have to choose one of those frameworks.

Enabling CORS in Cloud Functions for Firebase

In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info

Get selected text from a drop-down list (select box) using jQuery

Select Text and selected value on dropdown/select change event in jQuery

$("#yourdropdownid").change(function() {
    console.log($("option:selected", this).text()); //text
    console.log($(this).val()); //value
})

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

jquery function val() is not equivalent to "$(this).value="?

Note that :

typeof $(this) is JQuery object.

and

typeof $(this)[0] is HTMLElement object

then : if you want to apply .val() on HTMLElement , you can add this extension .

HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

Then :

document.getElementById('myDiv').val() ==== $('#myDiv').val()

And

 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

????? INVERSE :

Conversely? if you want to add value property to jQuery object , follow those steps :

  1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

  2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

  3. Search on jQuery.fn.init , it will be almost Line 2747

enter image description here

  1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

Enjoy now : $('#myDiv').value

Django CSRF check failing with an Ajax POST request

It seems nobody has mentioned how to do this in pure JS using the X-CSRFToken header and {{ csrf_token }}, so here's a simple solution where you don't need to search through the cookies or the DOM:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

Can I return the 'id' field after a LINQ insert?

After you commit your object into the db the object receives a value in its ID field.

So:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;

MetadataException: Unable to load the specified metadata resource

Just type path as follows instead of {Path.To.The.}: res:///{Path.To.The.}YourEdmxFileName.csdl|res:///{Path.To.The.}YourEdmxFileName.ssdl|res://*/{Path.To.The.}YourEdmxFileName.msl

Check if object value exists within a Javascript array of objects and if not add a new object to array

const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;

    if (cartArray.some(checkIfElementExists)) {
        console.log('already exists');
    } else {
        alert('does not exists here')

Oracle Convert Seconds to Hours:Minutes:Seconds

If you're just looking to convert a given number of seconds into HH:MI:SS format, this should do it

SELECT 
    TO_CHAR(TRUNC(x/3600),'FM9900') || ':' ||
    TO_CHAR(TRUNC(MOD(x,3600)/60),'FM00') || ':' ||
    TO_CHAR(MOD(x,60),'FM00')
FROM DUAL

where x is the number of seconds.

Close Current Tab

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with window.open() you can close it with window.close().

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

How can I view the shared preferences file using Android Studio?

This is an old post, but I though I should put a graphical answer here as the question is about viewing the SharedPreferences.xml using Android Studio. So here it goes.

Go to the Tools -> Android Device Monitor. Open the device monitor by clicking it.

enter image description here

Then you need to select the File Explorer tab in the device monitor. Find the data folder and find another data folder inside it. It will contain a folder having the name of your application package and there will be the desired SharedPreferences.xml.

enter image description here

Select the SharedPreferences.xml file and then pull and save the file in your computer using the button marked at the top-right corner of the image above.

I've used a device emulator.

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Let's do a test with 2 examples:

    <?php    
    $memory = (int)ini_get("memory_limit"); // Display your current value in php.ini (for example: 64M)
    echo "original memory: ".$memory."<br>";
    ini_set('memory_limit','128M'); // Try to override the memory limit for this script
    echo "new memory:".$memory;
    }
    // Will display:
    // original memory: 64
    // new memory: 64
    ?>

The above example doesn't work for overriding the memory_limit value. But This will work:

    <?php
    $memory = (int)ini_get("memory_limit"); // get the current value
    ini_set('memory_limit','128'); // override the value
    echo "original memory: ".$memory."<br>"; // echo the original value
    $new_memory = (int)ini_get("memory_limit"); // get the new value
    echo "new memory: ".$new_memory;  // echo the new value
    // Will display:
    // original memory: 64
    // new memory: 128
    ?>

You have to place the ini_set('memory_limit','128M'); at the top of the file or at least before any echo.

As for me, suhosin wasn't the solution because it doesn't even appear in my phpinfo(), but this worked:

    <?php
    ini_set('memory_limit','2048M'); // set at the top of the file
    (...)
    ?>

How to set button click effect in Android?

It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.

Kotlin Version:

fun buttonEffect(button: View) {
    button.setOnTouchListener { v, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
                v.invalidate()
            }
            MotionEvent.ACTION_UP -> {
                v.background.clearColorFilter()
                v.invalidate()
            }
        }
        false
    }
}

Java Version:

public static void buttonEffect(View button){
    button.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
                    v.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    v.getBackground().clearColorFilter();
                    v.invalidate();
                    break;
                }
            }
            return false;
        }
    });
}

Fastest Way of Inserting in Entity Framework

I'm looking for the fastest way of inserting into Entity Framework

There are some third-party libraries supporting Bulk Insert available:

  • Z.EntityFramework.Extensions (Recommended)
  • EFUtilities
  • EntityFramework.BulkInsert

See: Entity Framework Bulk Insert library

Be careful, when choosing a bulk insert library. Only Entity Framework Extensions supports all kind of associations and inheritances and it's the only one still supported.


Disclaimer: I'm the owner of Entity Framework Extensions

This library allows you to perform all bulk operations you need for your scenarios:

  • Bulk SaveChanges
  • Bulk Insert
  • Bulk Delete
  • Bulk Update
  • Bulk Merge

Example

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

// Customize Primary Key
context.BulkMerge(customers, operation => {
   operation.ColumnPrimaryKeyExpression = 
        customer => customer.Code;
});

Difference between two DateTimes C#?

Try the following

double hours = (b-a).TotalHours;

If you just want the hour difference excluding the difference in days you can use the following

int hours = (b-a).Hours;

The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).

The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.

How to provide password to a command that prompts for one in bash?

You can use the -S flag to read from std input. Find below an example:

function shutd()
{
  echo "mySuperSecurePassword" | sudo -S shutdown -h now
}    

Get list from pandas dataframe column or row?

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")

Output:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

100% width table overflowing div container

update your CSS to the following: this should fix

.page {
    width: 280px;
    border:solid 1px blue;
    overflow-x: auto;
}

TypeError: Converting circular structure to JSON in nodejs

Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account

https://www.npmjs.com/package/circular-json

You can stringify your circular structure by doing:

const str = CircularJSON.stringify(obj);

then you can convert it onto JSON using JSON parser

JSON.parse(str)

Lollipop : draw behind statusBar with its color set to transparent

With Android Studio 1.4, the template project with boiler plate code sets Overlay theme on your AppbarLayout and/or Toolbar. They are also set to be rendered behind the status bar by fitSystemWindow attribute = true. This will cause only toolbar to be rendered directly below the status bar and everything else will rendered beneath the toolbar. So the solutions provided above won't work on their own. You will have to make the following changes.

  • Remove the Overlay theme or change it to non overlay theme for the toolbar.
  • Put the following code in your styles-21.xml file.

    @android:color/transparent

  • Assign this theme to the activity containing the navigation drawer in the AndroidManifest.xml file.

This will make the Navigation drawer to render behind the transparent status bar.

How to merge two arrays in JavaScript and de-duplicate items

I know this question is not about array of objects, but searchers do end up here.

so it's worth adding for future readers a proper ES6 way of merging and then removing duplicates

array of objects:

var arr1 = [ {a: 1}, {a: 2}, {a: 3} ];
var arr2 = [ {a: 1}, {a: 2}, {a: 4} ];

var arr3 = arr1.concat(arr2.filter( ({a}) => !arr1.find(f => f.a == a) ));

// [ {a: 1}, {a: 2}, {a: 3}, {a: 4} ]

How do I tell what type of value is in a Perl variable?

A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.

If you want to know if it is a reference, you can use ref. If you want to know the reference type, you can use the reftype routine from Scalar::Util.

If you want to know if it is an object, you can use the blessed routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL has some methods to tell you about an object: if you want to check that it has the method you want to call, use can; if you want to see that it inherits from something, use isa; and if you want to see it the object handles a role, use DOES.

If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied. If you get an object, continue your checks.

If you want to know if it looks like a number, you can use looks_like_number from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.

If you need to do something more fancy, you can use a module such as Params::Validate.

Generating all permutations of a given string

public class Permutation 
{ 
public static void main(String[] args) 
{ 
    String str = "ABC"; 
    int n = str.length(); 
    Permutation permutation = new Permutation(); 
    permutation.permute(str, 0, n-1); 
} 

/** 
* permutation function 
* @param str string to calculate permutation for 
* @param l starting index 
* @param r end index 
*/
private void permute(String str, int l, int r) 
{ 
    if (l == r) 
        System.out.println(str); 
    else
    { 
        for (int i = l; i <= r; i++) 
        { 
            str = swap(str,l,i); 
            permute(str, l+1, r); 
            str = swap(str,l,i); 
        } 
    } 
} 

/** 
* Swap Characters at position 
* @param a string value 
* @param i position 1 
* @param j position 2 
* @return swapped string 
*/
public String swap(String a, int i, int j) 
{ 
    char temp; 
    char[] charArray = a.toCharArray(); 
    temp = charArray[i] ; 
    charArray[i] = charArray[j]; 
    charArray[j] = temp; 
    return String.valueOf(charArray); 
} 

} 

Escaping ampersand character in SQL string

This works as well:

select * from mde_product where cfn = 'A3D"&"R01'

you define & as literal by enclosing is with double qoutes "&" in the string.

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

Javascript - validation, numbers only

The simplest solution.

Thanks to my partner that gave me this answer.

You can set an onkeypress event on the input textbox like this:

onkeypress="validate(event)"

and then use regular expressions like this:

function validate(evt){
     evt.value = evt.value.replace(/[^0-9]/g,"");
}

It will scan and remove any letter or sign different from number in the field.

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

When to use Task.Delay, when to use Thread.Sleep?

My opinion,

Task.Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep() doesn't return anything ). You can check if this task is completed(use Task.IsCompleted property) later after another time-consuming process.

Thread.Sleep() doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.

As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep() in production code. I couldn't find any use case for it. Maybe that's because I mostly do web application development.

JavaScript unit test tools for TDD

BusterJS

There is also BusterJS from Christian Johansen, the author of Test Driven Javascript Development and the Sinon framework. From the site:

Buster.JS is a new JavaScript testing framework. It does browser testing by automating test runs in actual browsers (think JsTestDriver), as well as Node.js testing.

Apache Name Virtual Host with SSL

The VirtualHost would look like this:

NameVirtualHost IP_Address:443

<VirtualHost IP_Address:443>
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/ca.crt    # Where "ca" is the name of the Certificate
    SSLCertificateKeyFile /etc/pki/tls/private/ca.key
    ServerAdmin webmaster@domain_name.com
    DocumentRoot /var/www/html
    ServerName www.domain_name.com
    ErrorLog logs/www.domain_name.com-error_log
    CustomLog logs/www.domain_name.com-access_log common
</VirtualHost>

Is there any way to have a fieldset width only be as wide as the controls in them?

Unfortunately neither display:inline-block nor width:0px works in Internet Explorer up to version 8. I have not tried Internet Explorer 9. Much as I would like to ignore Internet Explorer, I can't.

The only option that works on Firefox and Internet Explorer 8 is float:left. The only slight drawback is that you have to remember to use clear:both on the element that follows the form. Of course, it will be very obvious if you forget ;-)

How to wait till the response comes from the $http request, in angularjs?

I was having the same problem and none if these worked for me. Here is what did work though...

app.factory('myService', function($http) {
    var data = function (value) {
            return $http.get(value);
    }

    return { data: data }
});

and then the function that uses it is...

vm.search = function(value) {

        var recieved_data = myService.data(value);

        recieved_data.then(
            function(fulfillment){
                vm.tags = fulfillment.data;
            }, function(){
                console.log("Server did not send tag data.");
        });
    };

The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.

Java HTML Parsing

Another library that might be useful for HTML processing is jsoup. Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.

http://jsoup.org/

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db.

There is no default config file, so you will either need to specify this when starting mongod with:

 mongod --config /etc/mongodb.conf

.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.

Note: to check the dbpath and command-line options for a running mongod, connect via the mongo shell and run:

db.serverCmdLineOpts()

In particular, if a custom dbpath is set it will be the value of:

db.serverCmdLineOpts().parsed.dbpath           // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath   // MongoDB 2.6+

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

Django Template Variables and Javascript

Here is what I'm doing very easily: I modified my base.html file for my template and put that at the bottom:

{% if DJdata %}
    <script type="text/javascript">
        (function () {window.DJdata = {{DJdata|safe}};})();
    </script>
{% endif %}

then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)

Hope it helps!

Return only string message from Spring MVC 3 Controller

Simplest solution:

Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.

@PostMapping("/create")
public String foo()
{
    String result = "something"
    return "\"" + result + "\"";
}

How to write to an existing excel file without overwriting data (using pandas)?

Here is a helper function:

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None

    (c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
    """
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist 
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)
        
        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)
        
        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()
            

NOTE: for Pandas < 0.21.0, replace sheet_name with sheetname!

Usage examples:

append_df_to_excel('d:/temp/test.xlsx', df)

append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False, startrow=25)

List of all index & index columns in SQL Server DB

sELECT 
     TableName = t.name,
     IndexName = ind.name,
     --IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name,
     key_ordinal,
     ind.type_desc
     --ind.*,
     --ic.*,
     --col.* 
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
WHERE 
     ind.is_primary_key = 0 
     AND ind.is_unique = 0 
     AND ind.is_unique_constraint = 0 
     AND t.is_ms_shipped = 0 
     and t.name='CompanyReconciliation' --table name
     and key_ordinal>0
ORDER BY 
     t.name, ind.name, ind.index_id, ic.index_column_id 

How to dynamically load a Python class

Here is to share something I found on __import__ and importlib while trying to solve this problem.

I am using Python 3.7.3.

When I try to get to the class d in module a.b.c,

mod = __import__('a.b.c')

The mod variable refer to the top namespace a.

So to get to the class d, I need to

mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d

If we try to do

mod = __import__('a.b.c')
d = getattr(mod, 'd')

we are actually trying to look for a.d.

When using importlib, I suppose the library has done the recursive getattr for us. So, when we use importlib.import_module, we actually get a handle on the deepest module.

mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d

Is there a Subversion command to reset the working copy?

Very quick and simple and does exactly what you want

svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'

The /(config|.ini)/ is for my own purposes.

And might be a good idea to add --no-ignore to the svn command

What does "static" mean in C?

Multi-file variable scope example

Here I illustrate how static affects the scope of function definitions across multiple files.

a.c

#include <stdio.h>

/*
Undefined behavior: already defined in main.
Binutils 2.24 gives an error and refuses to link.
https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*int i = 0;*/

/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 */
/*int i;*/

/* OK: extern. Will use the one in main. */
extern int i;

/* OK: only visible to this file. */
static int si = 0;

void a() {
    i++;
    si++;
    puts("a()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

main.c

#include <stdio.h>

int i = 0;
static int si = 0;

void a();    

void m() {
    i++;
    si++;
    puts("m()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

int main() {
    m();
    m();
    a();
    a();
    return 0;
}

GitHub upstream.

Compile and run:

gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o

Output:

m()
i = 1
si = 1

m()
i = 2
si = 2

a()
i = 3
si = 1

a()
i = 4
si = 2

Interpretation

  • there are two separate variables for si, one for each file
  • there is a single shared variable for i

As usual, the smaller the scope, the better, so always declare variables static if you can.

In C programming, files are often used to represent "classes", and static variables represent private static members of the class.

What standards say about it

C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static is a "storage-class specifier".

6.2.2/3 "Linkages of identifiers" says static implies internal linkage:

If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

and 6.2.2/2 says that internal linkage behaves like in our example:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.

where "translation unit is a source file after preprocessing.

How GCC implements it for ELF (Linux)?

With the STB_LOCAL binding.

If we compile:

int i = 0;
static int si = 0;

and disassemble the symbol table with:

readelf -s main.o

the output contains:

Num:    Value          Size Type    Bind   Vis      Ndx Name
  5: 0000000000000004     4 OBJECT  LOCAL  DEFAULT    4 si
 10: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    4 i

so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ.

STB_LOCAL is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:

STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other

which makes it a perfect choice to represent static.

Variables without static are STB_GLOBAL, and the spec says:

When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.

which is coherent with the link errors on multiple non static definitions.

If we crank up the optimization with -O3, the si symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging.

See also

C++ anonymous namespaces

In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions

How to hide a status bar in iOS?

You need to add this code in your AppDelegate file, not in your Root View Controller

Or add the property Status bar is initially hidden in your plist file

enter image description here

Folks, in iOS 7+

please add this to your info.plist file, It will make the difference :)

UIStatusBarHidden UIViewControllerBasedStatusBarAppearance

enter image description here

For iOS 11.4+ and Xcode 9.4 +

Use this code either in one or all your view controllers

override var prefersStatusBarHidden: Bool { return true }

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

In general, whenever you get an error like Can't bind to 'xxx' since it isn't a known native property, the most likely cause is forgetting to specify a component or a directive (or a constant that contains the component or the directive) in the directives metadata array. Such is the case here.

Since you did not specify RouterLink or the constant ROUTER_DIRECTIVES – which contains the following:

export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, 
  RouterLinkActive];

– in the directives array, then when Angular parses

<a [routerLink]="['RoutingTest']">Routing Test</a>

it doesn't know about the RouterLink directive (which uses attribute selector routerLink). Since Angular does know what the a element is, it assumes that [routerLink]="..." is a property binding for the a element. But it then discovers that routerLink is not a native property of a elements, hence it throws the exception about the unknown property.


I've never really liked the ambiguity of the syntax. I.e., consider

<something [whatIsThis]="..." ...>

Just by looking at the HTML we can't tell if whatIsThis is

  • a native property of something
  • a directive's attribute selector
  • a input property of something

We have to know which directives: [...] are specified in the component's/directive's metadata in order to mentally interpret the HTML. And when we forget to put something into the directives array, I feel this ambiguity makes it a bit harder to debug.

recyclerview No adapter attached; skipping layout

In my situation it was a forgotten component which locates in ViewHolder class but it wasn't located in layout file

How can I define an array of objects?

What you really want may simply be an enumeration

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

git replace local version with remote version

My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

In that scenario you can just run the following command:

git checkout -- path/filename

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Getting list of Facebook friends with latest API

Use FQL instead, its a like SQL but for Facebook's data tables and easily covers data query you'de like to make. You won't have to use all of those /xx/xxx/xx calls, just know the tables and columns you are intereseted in.

$myQuery = "SELECT uid2 FROM friend WHERE uid1=me()";
$facebook->api( "/fql?q=" . urlencode($myQuery) )

Great interactive examples at http://developers.facebook.com/docs/reference/fql/

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

How to embed images in html email

I'm using this function that find all images in my letter and attaches it to the message.

Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail();

Example usage:

define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*

mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']); 
// send email with all images from html attached to letter


function preparehtmlmail($html) {

  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();

  foreach ($matches[1] as $img) {
    $img_old = $img;

    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }

  $boundary = "--".md5(uniqid(time()));
  $headers .= "MIME-Version: 1.0\n";
  $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  $headers .= "From: ".DEFCALLBACKMAIL."\r\n";
  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'utf-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
  $multipart .= "$html\n\n";

  foreach ($paths as $path) {
    if(file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }

    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);

    $message_part = "";

    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }

    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";

  }

  $multipart .= "--$boundary--\n";
  return array('multipart' => $multipart, 'headers' => $headers);  
}

What are the performance characteristics of sqlite with very large database files?

There used to be a statement in the SQLite documentation that the practical size limit of a database file was a few dozen GB:s. That was mostly due to the need for SQLite to "allocate a bitmap of dirty pages" whenever you started a transaction. Thus 256 byte of RAM were required for each MB in the database. Inserting into a 50 GB DB-file would require a hefty (2^8)*(2^10)=2^18=256 MB of RAM.

But as of recent versions of SQLite, this is no longer needed. Read more here.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Ways to circumvent the same-origin policy

Personally, window.postMessage is the most reliable way that I've found for modern browsers. You do have to do a slight bit more work to make sure you're not leaving yourself open to XSS attacks, but it's a reasonable tradeoff.

There are also several plugins for the popular Javascript toolkits out there that wrap window.postMessage that provide similar functionality to older browsers using the other methods discussed above.

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

ASP.NET Web Site or ASP.NET Web Application?

One of the key differences is that Websites compile dynamically and create on-the-fly assemblies. Web applicaitons compile into one large assembly.

The distinction between the two has been done away with in Visual Studio 2008.

How can I easily convert DataReader to List<T>?

You cant simply (directly) convert the datareader to list.

You have to loop through all the elements in datareader and insert into list

below the sample code

using (drOutput)   
{
            System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();        
            int customerId = drOutput.GetOrdinal("customerId ");
            int CustomerName = drOutput.GetOrdinal("CustomerName ");

        while (drOutput.Read())        
        {
            CustomerEntity obj=new CustomerEntity ();
            obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
            obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
            arrObjects .Add(obj);
        }

}

Store text file content line by line into array

You can use this full code for your problem. For more details you can check it on appucoder.com

class FileDemoTwo{
    public static void main(String args[])throws Exception{
        FileDemoTwo ob = new FileDemoTwo();
        BufferedReader in = new BufferedReader(new FileReader("read.txt"));
        String str;
        List<String> list = new ArrayList<String>();
        while((str =in.readLine()) != null ){
            list.add(str);
        }
        String[] stringArr = list.toArray(new String[0]);
        System.out.println(" "+Arrays.toString(stringArr)); 
    }

}

How to tell whether a point is to the right or left side of a line

Try this code which makes use of a cross product:

public bool isLeft(Point a, Point b, Point c){
     return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0;
}

Where a = line point 1; b = line point 2; c = point to check against.

If the formula is equal to 0, the points are colinear.

If the line is horizontal, then this returns true if the point is above the line.

Add an element to an array in Swift

If the array is NSArray you can use the adding function to add any object at the end of the array, like this:

Swift 4.2

var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"

// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)

Result:

print(myArray) 
// ["First element", "Second element"]

That is a very simple way, regards!

Remove CSS from a Div using JQuery

You could use the removeAttr method, if you want to delete all the inline style you added manually with javascript. It's better to use CSS classes but you never know.

$("#displayPanel div").removeAttr("style")

How to hide a navigation bar from first ViewController in Swift?

Ways to hide Navigation Bar in Swift:

self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true

HTML5: Slider with two inputs possible?

Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

_x000D_
_x000D_
    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');


            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}


input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}


/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>
                            </div>
_x000D_
_x000D_
_x000D_

Microsoft SQL Server 2005 service fails to start

I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.

Clean out Eclipse workspace metadata

In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).

See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)

How to get UTC timestamp in Ruby?

The default formatting is not very useful, in my opinion. I prefer ISO8601 as it's sortable, relatively compact and widely recognized:

>> require 'time'
=> true
>> Time.now.utc.iso8601
=> "2011-07-28T23:14:04Z"

What does -1 mean in numpy reshape?

Long story short: you set some dimensions and let NumPy set the remaining(s).

(userDim1, userDim2, ..., -1) -->>

(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))

How to get text from each cell of an HTML table?

Another C# example. I just made an extension method for it.

public static string GetCellFromTable(this IWebElement table, int rowIndex, int columnIndex)
    {
        return table.FindElements(By.XPath("./tbody/tr"))[rowIndex].FindElements(By.XPath("./td"))[columnIndex].Text;
    }

how to disable DIV element and everything inside

pure javascript no jQuery

_x000D_
_x000D_
function sah() {_x000D_
  $("#div2").attr("disabled", "disabled").off('click');_x000D_
  var x1=$("#div2").hasClass("disabledDiv");_x000D_
  _x000D_
  (x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
  sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
    function sah1(el) {_x000D_
        try {_x000D_
            el.disabled = el.disabled ? false : true;_x000D_
        } catch (E) {}_x000D_
        if (el.childNodes && el.childNodes.length > 0) {_x000D_
            for (var x = 0; x < el.childNodes.length; x++) {_x000D_
                sah1(el.childNodes[x]);_x000D_
            }_x000D_
        }_x000D_
    }
_x000D_
#div2{_x000D_
  padding:5px 10px;_x000D_
  background-color:#777;_x000D_
  width:150px;_x000D_
  margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
    pointer-events: none;_x000D_
    opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
        <div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
        <input type="text" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="button" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="radio" name="sex" value="Male" />Male_x000D_
        <Br />_x000D_
        <input type="radio" name="sex" value="Female" />Female_x000D_
        <Br />_x000D_
    </div>_x000D_
    <Br />_x000D_
    <Br />_x000D_
    <input type="button" value="Click" onclick="sah()" />
_x000D_
_x000D_
_x000D_

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

How to retrieve available RAM from Windows command line?

wmic OS get TotalVisibleMemorySize /Value

Note not TotalPhysicalMemory as suggested elsewhere

Git commit with no commit message

I found the simplest solution:

git commit -am'save'

That's all,you will work around git commit message stuff.

you can even save that commend to a bash or other stuff to make it more simple.

Our team members always write those messages,but almost no one will see those message again.

Commit message is a time-kill stuff at least in our team,so we ignore it.

Does C have a string type?

There is no string type in C. You have to use char arrays.

By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.

How to select all the columns of a table except one column?

You can use this approach to get the data from all the columns except one:-

  1. Insert all the data into a temporary table
  2. Then drop the column which you dont want from the temporary table
  3. Fetch the data from the temporary table(This will not contain the data of the removed column)
  4. Drop the temporary table

Something like this:

SELECT * INTO #TemporaryTable FROM YourTableName

ALTER TABLE #TemporaryTable DROP COLUMN Columnwhichyouwanttoremove

SELECT * FROM #TemporaryTable 

DROP TABLE #TemporaryTable 

How can strip whitespaces in PHP's variable?

you also use preg_replace_callback function . and this function is identical to its sibling preg_replace except for it can take a callback function which gives you more control on how you manipulate your output.

$str = "this is a   string";

echo preg_replace_callback(
        '/\s+/',
        function ($matches) {
            return "";
        },
        $str
      );

How do I format a date in Jinja2?

You can use it like this in template without any filters

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

I can’t find the Android keytool

One thing that wasn't mentioned here (but kept me from running keytool altogether) was that you need to run the Command Prompt as Administrator.

Just wanted to share it...

Unable to connect with remote debugger

I had a similar issue that led me to this question. In my browser debugger I was getting this error message:

Access to fetch at 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

It took me awhile to realize I was using 127.0.0.1:8081 instead of localhost:8081 for my debugger.

To fix it, I simply had to change Chrome from:

http://127.0.0.1:8081/debugger-ui/

to

http://localhost:8081/debugger-ui/

C# refresh DataGridView when updating or inserted on another form

Create a small function and use it anywhere

public SqlConnection con = "Your connection string"; 
public void gridviewUpdate()
{
    con.Open();
    string select = "SELECT * from table_name";
    SqlDataAdapter da = new SqlDataAdapter(select, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "table_name");
    datagridview.DataSource = ds;
    datagridview.DataMember = "table_name";
    con.Close();
}

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.

$(items).each(function(i, item){

  setTimeout(function(){

    geoLocate("my address", function(myLatlng){
      ...
    });

  }, 200 * i);

}

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {
       hangoutButton.click(); // this will trigger the click event
    };
};

this will do the trick

No plot window in matplotlib

Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.

ipython --matplotlib

How to sum up an array of integers in C#

Try this code:

using System;

namespace Array
{
    class Program
    {
        static void Main()
        {
            int[] number = new int[] {5, 5, 6, 7};

            int sum = 0;
            for (int i = 0; i <number.Length; i++)
            {
                sum += number[i];
            }
            Console.WriteLine(sum);
        }
    }
} 

The result is:

23

Check if a property exists in a class

This answers a different question:

If trying to figure out if an OBJECT (not class) has a property,

OBJECT.GetType().GetProperty("PROPERTY") != null

returns true if (but not only if) the property exists.

In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

helped me here.

Edit: Nowadays, it's probably smart to use the nameof operator instead of the stringified property name.

How do I make calls to a REST API using C#?

Unrelated, I'm sure, but do wrap your IDisposable objects in using blocks to ensure proper disposal:

using System;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
            {
                requestWriter.Write(DATA);
            }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                {
                    string response = responseReader.ReadToEnd();
                    Console.Out.WriteLine(response);
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

Delete element in a slice

There are two options:

A: You care about retaining array order:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

B: You don't care about retaining order (this is probably faster):

a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1]   // Chop off the last one.

See the link to see implications re memory leaks if your array is of pointers.

https://github.com/golang/go/wiki/SliceTricks

CROSS JOIN vs INNER JOIN in SQL

SQL Server also accepts the simpler notation of:

SELECT A.F, 
       B.G, 
       C.H 
  FROM TABLE_A A, 
       TABLE_B B, 
       TABLE_C C
 WHERE A.X = B.X 
   AND B.Y = C.Y

Using this simpler notation, one does not need to bother about the difference between inner and cross joins. Instead of two "ON" clauses, there is a single "WHERE" clause that does the job. If you have any difficulty in figuring out which "JOIN" "ON" clauses go where, abandon the "JOIN" notation and use the simpler one above.

It is not cheating.

Using C# to read/write Excel files (.xls/.xlsx)

I use NPOI for all my Excel needs.

http://npoi.codeplex.com/

Comes with a solution of examples for many common Excel tasks.

DateTime.TryParseExact() rejecting valid formats

string DemoLimit = "02/28/2018";
 string pattern = "MM/dd/yyyy";
 CultureInfo enUS = new CultureInfo("en-US"); 
 DateTime.TryParseExact(DemoLimit, pattern, enUS, 
                     DateTimeStyles.AdjustToUniversal, out datelimit);

For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

Pandas split column of lists into multiple columns

There seems to be a syntactically simpler way, and therefore easier to remember, as opposed to the proposed solutions. I'm assuming that the column is called 'meta' in a dataframe df:

df2 = pd.DataFrame(df['meta'].str.split().values.tolist())

When to use .First and when to use .FirstOrDefault with LINQ?

First()

  1. Returns first element of a sequence.
  2. It throw an error when There is no element in the result or source is null.
  3. you should use it,If more than one element is expected and you want only first element.

FirstOrDefault()

  1. Returns first element of a sequence, or a default value if no element is found.
  2. It throws an error Only if the source is null.
  3. you should use it, If more than one element is expected and you want only first element. Also good if result is empty.

We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...

UserInfo Table

How to use First()

var result = dc.UserInfos.First(x => x.ID == 1);

There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]

var result = dc.UserInfos.First(x => x.FName == "Rahul");   

There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]

var result = dc.UserInfos.First(x => x.ID ==13);

There is no record with ID== 13. An error should be occur.
InvalidOperationException: Sequence contains no elements

How to Use FirstOrDefault()

var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);

There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]

var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");

There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]

var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);

There is no record with ID== 13. The return value is null

Hope it will help you to understand when to use First() or FirstOrDefault().

What is the simplest C# function to parse a JSON string into an object?

I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.