Programs & Examples On #Reversing

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

javascript - replace dash (hyphen) with a space

This fixes it:

let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);

There were two problems with your code:

  1. First, String.replace() doesn’t change the string itself, it returns a changed string.
  2. Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.

Reversing an Array in Java

In place reversal with minimum amount of swaps.

for (int i = 0; i < a.length / 2; i++) {
    int tmp = a[i];
    a[i] = a[a.length - 1 - i];
    a[a.length - 1 - i] = tmp;
}

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

Reversing a String with Recursion in Java

The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"

Chart won't update in Excel (2007)

Just activate the sheet where the chart is:

Sheets(1).Activate

and your problem disappears.

I had the same problem and none of the things you mentioned in question worked for me until I just activated sheet. The accepted answer didn't work for me neither.

Alternatively you can make:

ActiveCell.Activate

In C/C++ what's the simplest way to reverse the order of bits in a byte?

template <typename T>
T reverse(T n, size_t b = sizeof(T) * CHAR_BIT)
{
    assert(b <= std::numeric_limits<T>::digits);

    T rv = 0;

    for (size_t i = 0; i < b; ++i, n >>= 1) {
        rv = (rv << 1) | (n & 0x01);
    }

    return rv;
}

EDIT:

Converted it to a template with the optional bitcount

Open Source Alternatives to Reflector?

Well, Reflector itself is a .NET assembly so you can open Reflector.exe in Reflector to check out how it's built.

How many characters can a Java String have?

Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.

By character I mean "char"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.

Reversing a string in C

You can actually do something like this:

#include <string.h>

void reverse(char *);

int main(void){
 char name[7] = "walter";
 reverse(name);
 printf("%s", name);
}

void reverse(char *s) {
  size_t len = strlen(s);
  char *a = s;
  char *b = &s[(int)len - 1];
  char tmp;
  for (; a < b; ++a, --b) {
    tmp = *a;
    *a = *b;
    *b = tmp;
  }
}

How to duplicate sys.stdout to a log file?

If you wish to log all output to a file AND output it to a text file then you can do the following. It's a bit hacky but it works:

import logging
debug = input("Debug or not")
if debug == "1":
    logging.basicConfig(level=logging.DEBUG, filename='./OUT.txt')
    old_print = print
    def print(string):
        old_print(string)
        logging.info(string)
print("OMG it works!")

EDIT: Note that this does not log errors unless you redirect sys.stderr to sys.stdout

EDIT2: A second issue is that you have to pass 1 argument unlike with the builtin function.

EDIT3: See the code before to write stdin and stdout to console and file with stderr only going to file

import logging, sys
debug = input("Debug or not")
if debug == "1":
    old_input = input
    sys.stderr.write = logging.info
    def input(string=""):
        string_in = old_input(string)
        logging.info("STRING IN " + string_in)
        return string_in
    logging.basicConfig(level=logging.DEBUG, filename='./OUT.txt')
    old_print = print
    def print(string="", string2=""):
        old_print(string, string2)
        logging.info(string)
        logging.info(string2)
print("OMG")
b = input()
print(a) ## Deliberate error for testing

Reversing a linked list in Java, recursively

Here is a simple iterative approach:

public static Node reverse(Node root) {
    if (root == null || root.next == null) {
        return root;
    }

    Node curr, prev, next;
    curr = root; prev = next = null;
    while (curr != null) {
        next = curr.next;
        curr.next = prev;

        prev = curr;
        curr = next;
    }
    return prev;
}

And here is a recursive approach:

public static Node reverseR(Node node) {
    if (node == null || node.next == null) {
        return node;
    }

    Node next = node.next;
    node.next = null;

    Node remaining = reverseR(next);
    next.next = node;
    return remaining;
}

How do I check if a number is a palindrome?

Try this:

print('!* To Find Palindrome Number') 

def Palindrome_Number():

            n = input('Enter Number to check for palindromee')  
            m=n 
            a = 0  

    while(m!=0):  
        a = m % 10 + a * 10    
        m = m / 10    

    if( n == a):    
        print('%d is a palindrome number' %n)
    else:
        print('%d is not a palindrome number' %n)

just call back the functions

What is the difference between ng-if and ng-show/ng-hide

@Gajus Kuizinas and @CodeHater are correct. Here i am just giving an example. While we are working with ng-if, if the assigned value is false then the whole html elements will be removed from DOM. and if assigned value is true, then the html elements will be visible on the DOM. And the scope will be different compared to the parent scope. But in case of ng-show, it wil just show and hide the elements based on the assigned value. But it always stays in the DOM. Only the visibility changes as per the assigned value.

http://plnkr.co/edit/3G0V9ivUzzc8kpLb1OQn?p=preview

Hope this example will help you in understanding the scopes. Try giving false values to ng-show and ng-if and check the DOM in console. Try entering the values in the input boxes and observe the difference.

<!DOCTYPE html>

Hello Plunker!

<input type="text" ng-model="data">
<div ng-show="true">
    <br/>ng-show=true :: <br/><input type="text" ng-model="data">
</div>
<div ng-if="true">
    <br/>ng-if=true :: <br/><input type="text" ng-model="data">
</div> 
{{data}}

jQuery UI Color Picker

You can find some demos and plugins here.

http://jqueryui.pbworks.com/ColorPicker

A beginner's guide to SQL database design

Experience counts for a lot, but in terms of table design you can learn a lot from how ORMs like Hibernate and Grails operate to see why they do things. In addition:

  1. Keep different types of data separate - don't store addresses in your order table, link to an address in a separate addresses table, for example.

  2. I personally like having an integer or long surrogate key on each table (that holds data, not those that link different tables together, e,g., m:n relationships) that is the primary key.

  3. I also like having a created and modified timestamp column.

  4. Ensure that every column that you do "where column = val" in any query has an index. Maybe not the most perfect index in the world for the data type, but at least an index.

  5. Set up your foreign keys. Also set up ON DELETE and ON MODIFY rules where relevant, to either cascade or set null, depending on your object structure (so you only need to delete once at the 'head' of your object tree, and all that object's sub-objects get removed automatically).

  6. If you want to modularise your code, you might want to modularise your DB schema - e.g., this is the "customers" area, this is the "orders" area, and this is the "products" area, and use join/link tables between them, even if they're 1:n relations, and maybe duplicate the important information (i.e., duplicate the product name, code, price into your order_details table). Read up on normalisation.

  7. Someone else will recommend exactly the opposite for some or all of the above :p - never one true way to do some things eh!

@import vs #import - iOS 7

It's a new feature called Modules or "semantic import". There's more info in the WWDC 2013 videos for Session 205 and 404. It's kind of a better implementation of the pre-compiled headers. You can use modules with any of the system frameworks in iOS 7 and Mavericks. Modules are a packaging together of the framework executable and its headers and are touted as being safer and more efficient than #import.

One of the big advantages of using @import is that you don't need to add the framework in the project settings, it's done automatically. That means that you can skip the step where you click the plus button and search for the framework (golden toolbox), then move it to the "Frameworks" group. It will save many developers from the cryptic "Linker error" messages.

You don't actually need to use the @import keyword. If you opt-in to using modules, all #import and #include directives are mapped to use @import automatically. That means that you don't have to change your source code (or the source code of libraries that you download from elsewhere). Supposedly using modules improves the build performance too, especially if you haven't been using PCHs well or if your project has many small source files.

Modules are pre-built for most Apple frameworks (UIKit, MapKit, GameKit, etc). You can use them with frameworks you create yourself: they are created automatically if you create a Swift framework in Xcode, and you can manually create a ".modulemap" file yourself for any Apple or 3rd-party library.

You can use code-completion to see the list of available frameworks:

enter image description here

Modules are enabled by default in new projects in Xcode 5. To enable them in an older project, go into your project build settings, search for "Modules" and set "Enable Modules" to "YES". The "Link Frameworks" should be "YES" too:

You have to be using Xcode 5 and the iOS 7 or Mavericks SDK, but you can still release for older OSs (say iOS 4.3 or whatever). Modules don't change how your code is built or any of the source code.


From the WWDC slides:

  • Imports complete semantic description of a framework
  • Doesn't need to parse the headers
  • Better way to import a framework’s interface
  • Loads binary representation
  • More flexible than precompiled headers
  • Immune to effects of local macro definitions (e.g. #define readonly 0x01)
  • Enabled for new projects by default

To explicitly use modules:

Replace #import <Cocoa/Cocoa.h> with @import Cocoa;

You can also import just one header with this notation:

@import iAd.ADBannerView;

The submodules autocomplete for you in Xcode.

How to give environmental variable path for file appender in configuration file in log4j

Since you are using unix you can use a path like this.

  /home/Production/modulename/logs/message.log

path should start with /

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

Select unique or distinct values from a list in UNIX shell script

I get a better tips to get non-duplicate entries in a file

awk '$0 != x ":FOO" && NR>1 {print x} {x=$0} END {print}' file_name | uniq -f1 -u

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Default parameters with C++ constructors

One more thing to consider is whether or not the class could be used in an array:

foo bar[400];

In this scenario, there is no advantage to using the default parameter.

This would certainly NOT work:

foo bar("david", 34)[400]; // NOPE

When using SASS how can I import a file from a different directory?

node-sass (the official SASS wrapper for node.js) provides a command line option --include-path to help with such requirements.

Example:

In package.json:

"scripts": {
    "build-css": "node-sass src/ -o src/ --include-path src/",
}

Now, if you have a file src/styles/common.scss in your project, you can import it with @import 'styles/common'; anywhere in your project.

Refer https://github.com/sass/node-sass#usage-1 for more details.

How to delete a stash created with git stash create?

git stash drop takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n} which n nominates which stash to drop. You can't pass a commit id to git stash drop.

git stash drop            # drop top hash, stash@{0}
git stash drop stash@{n}  # drop specific stash - see git stash list

Dropping a stash will change the stash@{n} designations of all stashes further down the stack.

I'm not sure why you think need to drop a stash because if you are using stash create a stash entry isn't created for your "stash" so there isn't anything to drop.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

An instance might be corrupted or not updated properly.

Try these Commands:

C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
 
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
 
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
 
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.

Get top n records for each group of grouped results

How about using self-joining:

CREATE TABLE mytable (person, groupname, age);
INSERT INTO mytable VALUES('Bob',1,32);
INSERT INTO mytable VALUES('Jill',1,34);
INSERT INTO mytable VALUES('Shawn',1,42);
INSERT INTO mytable VALUES('Jake',2,29);
INSERT INTO mytable VALUES('Paul',2,36);
INSERT INTO mytable VALUES('Laura',2,39);

SELECT a.* FROM mytable AS a
  LEFT JOIN mytable AS a2 
    ON a.groupname = a2.groupname AND a.age <= a2.age
GROUP BY a.person
HAVING COUNT(*) <= 2
ORDER BY a.groupname, a.age DESC;

gives me:

a.person    a.groupname  a.age     
----------  -----------  ----------
Shawn       1            42        
Jill        1            34        
Laura       2            39        
Paul        2            36      

I was strongly inspired by the answer from Bill Karwin to Select top 10 records for each category

Also, I'm using SQLite, but this should work on MySQL.

Another thing: in the above, I replaced the group column with a groupname column for convenience.

Edit:

Following-up on the OP's comment regarding missing tie results, I incremented on snuffin's answer to show all the ties. This means that if the last ones are ties, more than 2 rows can be returned, as shown below:

.headers on
.mode column

CREATE TABLE foo (person, groupname, age);
INSERT INTO foo VALUES('Paul',2,36);
INSERT INTO foo VALUES('Laura',2,39);
INSERT INTO foo VALUES('Joe',2,36);
INSERT INTO foo VALUES('Bob',1,32);
INSERT INTO foo VALUES('Jill',1,34);
INSERT INTO foo VALUES('Shawn',1,42);
INSERT INTO foo VALUES('Jake',2,29);
INSERT INTO foo VALUES('James',2,15);
INSERT INTO foo VALUES('Fred',1,12);
INSERT INTO foo VALUES('Chuck',3,112);


SELECT a.person, a.groupname, a.age 
FROM foo AS a 
WHERE a.age >= (SELECT MIN(b.age)
                FROM foo AS b 
                WHERE (SELECT COUNT(*)
                       FROM foo AS c
                       WHERE c.groupname = b.groupname AND c.age >= b.age) <= 2
                GROUP BY b.groupname)
ORDER BY a.groupname ASC, a.age DESC;

gives me:

person      groupname   age       
----------  ----------  ----------
Shawn       1           42        
Jill        1           34        
Laura       2           39        
Paul        2           36        
Joe         2           36        
Chuck       3           112      

How to output loop.counter in python jinja template?

The counter variable inside the loop is called loop.index in jinja2.

>>> from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

See http://jinja.pocoo.org/docs/templates/ for more.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

Merge/flatten an array of arrays

Here is the recursive way...

function flatten(arr){
    let newArray = [];
    for(let i=0; i< arr.length; i++){
        if(Array.isArray(arr[i])){
          newArray =  newArray.concat(flatten(arr[i]))
        }else{
          newArray.push(arr[i])
        }
    }
  return newArray; 
}

console.log(flatten([1, 2, 3, [4, 5] ])); // [1, 2, 3, 4, 5]
console.log(flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]))  // [1,2,3]
console.log(flatten([[1],[2],[3]])) // [1,2,3]

How to check if iframe is loaded or it has a content?

I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)

First:
Create an iframe with a data- attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>

Now in the iframe code, use :

var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);



Now back to the injected script as per my case:

setTimeout(function(){
  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
  {
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');
  }
},3000);


and,

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
    {
        console.log('URL issues');
        return;
    }
    else {
        var myMsg = event.data;
        if(myMsg == '1'){
            //8-12-18 changed from 'data-isload' to 'data-isloaded
            $("#myiframe").prop('data-isloaded', '1');
        }
    }           
}



It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

No == operator found while comparing structs in C++

In C++, structs do not have a comparison operator generated by default. You need to write your own:

bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return /* your comparison code goes here */
}

moment.js, how to get day of week number

I think this would work

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

What are good message queue options for nodejs?

you could use redis with the lightning fast node_redis client. It even has built-in pubsub semantics.

Go install fails with error: no install location for directory xxx outside GOPATH

You'll want to have 3 directories inside your chosen GOPATH directory.

GOPATH
     /bin
     /src
       /someProgram
        program.go
       /someLibrary
        library.go
     /pkg

Then you'll run go install from inside either someProgram (which puts an executable in bin) or someLibrary (which puts a library in pkg).

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

How do I make a new line in swift

You can use the following code;

var example: String = "Hello World \r\n This is a new line"

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

How can I create an object based on an interface file definition in TypeScript?

Many of the solutions so far posted use type assertions and therefor do not throw compilation errors if required interface properties are omitted in the implementation.

For those interested in some other robust, compact solutions:

Option 1: Instantiate an anonymous class which implements the interface:

new class implements MyInterface {
  nameFirst = 'John';
  nameFamily = 'Smith';
}();

Option 2: Create a utility function:

export function impl<I>(i: I) { return i; }

impl<MyInterface>({
  nameFirst: 'John';
  nameFamily: 'Smith';
})

Location of hibernate.cfg.xml in project?

Using configure() method two times is responsible the problem for me. Instead of using like this :

    Configuration configuration = new Configuration().configure();
    configuration.configure("/main/resources/hibernate.cfg.xml");

Now, I am using like this, problem does not exist anymore.

    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");

P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5

public class HibernateUtil {

 private static SessionFactory sessionFactory ;


 static {
     try{
    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
     catch(Exception e){
         e.printStackTrace();
     }
     }

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}  

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

Allow 2 decimal places in <input type="number">

On input:

step="any"
class="two-decimals"

On script:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

How to center a button within a div?

To center a <button type = "button"> both vertically and horizontally within a <div> which width is computed dynamically like in your case, this is what to do:

  1. Set text-align: center; to the wrapping <div>: this will center the button whenever you resize the <div> (or rather the window)
  2. For the vertical alignment, you will need to set margin: valuepx; for the button. This is the rule on how to calculate valuepx:

    valuepx = (wrappingDIVheight - buttonHeight)/2

Here is a JS Bin demo.

Checking if a collection is empty in Java: which is the best method?

if (CollectionUtils.isNotEmpty(listName))

Is the same as:

if(listName != null && !listName.isEmpty())

In first approach listName can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0 is something unnecessary at all, also i learned that it is slower than using .isEmpty()

Auto-size dynamic text to fill fixed size container

I did like

let name = "Making statements based on opinion; back them up with references or personal experience."
let originFontSize = 15;
let maxDisplayCharInLine = 50; 
let fontSize = Math.min(originFontSize, originFontSize / (name.length / maxDisplayCharInLine));

What is the Sign Off feature in Git for?

Sign-off is a line at the end of the commit message which certifies who is the author of the commit. Its main purpose is to improve tracking of who did what, especially with patches.

Example commit:

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

It should contain the user real name if used for an open-source project.

If branch maintainer need to slightly modify patches in order to merge them, he could ask the submitter to rediff, but it would be counter-productive. He can adjust the code and put his sign-off at the end so the original author still gets credit for the patch.

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

[Project Maintainer: Renamed test methods according to naming convention.]
Signed-off-by: Project Maintainer <[email protected]>

Source: http://gerrit.googlecode.com/svn/documentation/2.0/user-signedoffby.html

Sorting HTML table with JavaScript

You could deal with a json array and the sort function. It is a pretty easy maintanable structure to manipulate (ex: sorting).

Untested, but here's the idea. That would support multiple ordering and sequential ordering if you pass in a array in which you put the columns in the order they should be ordered by.

var DATA_TABLE = {
    {name: 'George', lastname: 'Blarr', age:45},
    {name: 'Bob', lastname: 'Arr', age: 20}
    //...
};

function sortDataTable(arrayColNames, asc) { // if not asc, desc
    for (var i=0;i<arrayColNames.length;i++) {
        var columnName = arrayColNames[i];
        DATA_TABLE = DATA_TABLE.sort(function(a,b){
            if (asc) {
                return (a[columnName] > b[columnName]) ? 1 : -1;
            } else {
                return (a[columnName] < b[columnName]) ? 1 : -1;
            }
        });
    }
}

function updateHTMLTable() {
    // update innerHTML / textContent according to DATA_TABLE
    // Note: textContent for firefox, innerHTML for others
}

Now let's imagine you need to order by lastname, then name, and finally by age.

var orderAsc = true;
sortDataTable(['lastname', 'name', 'age'], orderAsc);

It should result in something like :

{name: 'Jack', lastname: 'Ahrl', age: 20},
{name: 'Jack', lastname: 'Ahrl', age: 22},
//...

Hide HTML element by id

.nav ul li a#nav-ask{
    display:none;
}

Angular: date filter adds timezone, how to output UTC?

The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.

How do I make an image smaller with CSS?

You can try this:

-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);

Example: image "grows" 1.3 times

-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);

Pandas How to filter a Series

Another way is to first convert to a DataFrame and use the query method (assuming you have numexpr installed):

import pandas as pd

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

s = pd.Series(test)
s.to_frame(name='x').query("x != 1")

Is there a command like "watch" or "inotifywait" on the Mac?

watchdog is a cross-platform python API for watching files / directories, and it has builtin "tricks" tool that allows you to trigger actions (including shell commands) when events occur (including new added file, removed file and changed file).

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

Just as others said, you can perform a case sensitive search. Or just change the collation format of a specified column as me. For the User/Password columns in my database I change them to collation through the following command:

ALTER TABLE `UserAuthentication` CHANGE `Password` `Password` VARCHAR(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL;

Align items in a stack panel?

Maybe not what you want if you need to avoid hard-coding size values, but sometimes I use a "shim" (Separator) for this:

<Separator Width="42"></Separator>

Get IPv4 addresses from Dns.GetHostEntry()

    public static string GetIPAddress(string hostname)
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(hostname);

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
                return ip.ToString();
            }
        }
        return string.Empty;
    }

How to make rpm auto install dependencies

The link @gertvdijk provided shows a quick way to achieve the desired results without configuring a local repository:

$ yum --nogpgcheck localinstall packagename.arch.rpm

Just change packagename.arch.rpm to the RPM filename you want to install.

Edit Just a clarification, this will automatically install all dependencies that are already available via system YUM repositories.

If you have dependencies satisfied by other RPMs that are not in the system's repositories, then this method will not work unless each RPM is also specified along with packagename.arch.rpm on the command line.

What is the equivalent of "!=" in Excel VBA?

Just a note. If you want to compare a string with "" ,in your case, use

If LEN(str) > 0 Then

or even just

If LEN(str) Then

instead.

How to bundle an Angular app for production

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

C Program to find day of week given date

Here is a simple code that I created in c that should fix your problem :

#include <conio.h>

int main()
{
  int y,n,oy,ly,td,a,month,mon_,d,days,down,up; // oy==ordinary year, td=total days, d=date

    printf("Enter the year,month,date: ");
    scanf("%d%d%d",&y,&month,&d);
    n= y-1; //here we subtracted one year because we have to find on a particular day of that year, so we will not count whole year.
    oy= n%4;

    if(oy==0) // for leap year
      {
         mon_= month-1;
         down= mon_/2;  //down means months containing 30 days.
           up= mon_-down; // up means months containing 31 days.
           if(mon_>=2)
             {
               days=(up*31)+((down-1)*30)+29+d; // here in down case one month will be of feb so we subtracted 1 and after that seperately
               td= (oy*365)+(ly*366)+days;      // added 29 days as it is the if block of leap year case.
             }
           if(mon_==1)
             {
               days=(up*31)+d;
               td= (oy*365)+(ly*366)+days;
             } 
           if(mon_==0)
             {
               days= d;
               td= (oy*365)+(ly*366)+days;
             }    
      }
    else
      {
         mon_= month-1;
         down= mon_/2;
           up= mon_-down;
           if(mon_>=2)
             {
               days=(up*31)+((down-1)*30)+28+d;
               td= (oy*365)+(ly*366)+days;
             }
           if(mon_==1)
             {
               days=(up*31)+d;
               td= (oy*365)+(ly*366)+days;
             } 
           if(mon_==0)
             {
               days= d;
               td= (oy*365)+(ly*366)+days;
             }    
      }  

    ly= n/4;
     a= td%7;

     if(a==0)
       printf("\nSunday");
     if(a==1)
       printf("\nMonday");
     if(a==2)
       printf("\nTuesday");
     if(a==3)
       printf("\nWednesday");
     if(a==4)
       printf("\nThursday");
     if(a==5)
       printf("\nFriday");
     if(a==6)
       printf("\nSaturday");
  return 0;   
}

How to use target in location.href

The problem is that some versions of explorer don't support the window.open javascript function

Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.

Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.

There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

Fast check for NaN in NumPy

I think np.isnan(np.min(X)) should do what you want.

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

Send POST request using NSURLSession

You can use https://github.com/mxcl/OMGHTTPURLRQ

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];

NSURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];

Python: how to print range a-z?

#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))

#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))

#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]

Sorting arraylist in alphabetical order (case insensitive)

def  lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"]; 

println lst.sort { a, b -> a.compareToIgnoreCase b }

This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists

Parsing HTML using Python

Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.

Python HTML parser performance

I'd recommend BeautifulSoup even though it isn't built in. Just because it's so easy to work with for those kinds of tasks. Eg:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)

x = soup.body.find('div', attrs={'class' : 'container'}).text

How do I install and use curl on Windows?

Note also that installing Git for Windows from git-scm.com also installs Curl. You can then run Curl from Git for Windows' BASH terminal (not the default Windows CMD terminal).

How to run jenkins as a different user

ISSUE 1:

Started by user anonymous

That does not mean that Jenkins started as an anonymous user.

It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the

"Started by anonymous" 

will change to

"Started by < username >". 

Note: You do not have to enable security in order to run jenkins or to clone correctly.

If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System.


ISSUE 2:

The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.

Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.

Hope that helps.

Can I set an unlimited length for maxJsonLength in web.config?

For those who are having issues with in MVC3 with JSON that's automatically being deserialized for a model binder and is too large, here is a solution.

  1. Copy the code for the JsonValueProviderFactory class from the MVC3 source code into a new class.
  2. Add a line to change the maximum JSON length before the object is deserialized.
  3. Replace the JsonValueProviderFactory class with your new, modified class.

Thanks to http://blog.naver.com/techshare/100145191355 and https://gist.github.com/DalSoft/1588818 for pointing me in the right direction for how to do this. The last link on the first site contains full source code for the solution.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf

change

AddHandler application/x-httpd-php .js .xml .htc .css

to:

AddHandler application/x-httpd-php .js .xml .htc

Twitter Bootstrap Modal Form Submit

You can also cheat in some way by hidding a submit button on your form and triggering it when you click on your modal button.

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

Nuget connection attempt failed "Unable to load the service index for source"

The error can be caused by just temporary network issue, and disappear, if try again.

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

C++ Get name of type in template

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;

#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X


REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...

And then use it like

throw ParseError(TypeParseTraits<T>::name);

EDIT:

You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

Check if a string is palindrome

Reverse the string and check if original string and reverse are same or not

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

"Debug only" code that should run only when "turned on"

What you're looking for is

[ConditionalAttribute("DEBUG")]

attribute.

If you for instance write a method like :

[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
    Console.WriteLine("This message was brought to you by your debugger : ");
    Console.WriteLine(message);
}

any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.

Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.

Printing out all the objects in array list

You have to define public String toString() method in your Student class. For example:

public String toString() {
  return "Student: " + studentName + ", " + studentNo;
}

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.

  public static String toCamelCase(String value) {
    StringBuilder sb = new StringBuilder();

    final char delimChar = '_';
    boolean lower = false;
    for (int charInd = 0; charInd < value.length(); ++charInd) {
      final char valueChar = value.charAt(charInd);
      if (valueChar == delimChar) {
        lower = false;
      } else if (lower) {
        sb.append(Character.toLowerCase(valueChar));
      } else {
        sb.append(Character.toUpperCase(valueChar));
        lower = true;
      }
    }

    return sb.toString();
  }

A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.

Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.

mysql extract year from date format

SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name;

Refresh Fragment at reload

// Reload current fragment
Fragment frag = new Order();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_home, frag).commit();

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

How to convert a string to JSON object in PHP

you can use this for example

$array = json_decode($string,true)

but validate the Json before. You can validate from http://jsonviewer.stack.hu/

E11000 duplicate key error index in mongodb mongoose

I had the same issue. Tried debugging different ways couldn't figure out. I tried dropping the collection and it worked fine after that. Although this is not a good solution if your collection has many documents. But if you are in the early state of development try dropping the collection.

db.users.drop();

How do you change the character encoding of a postgres database?

Daniel Kutik's answer is correct, but it can be even more safe, with database renaming.

So, the truly safe way is:

  1. Create new database with the different encoding and name
  2. Dump your database
  3. Restore dump to the new DB
  4. Test that your application runs correctly with the new DB
  5. Rename old DB to something meaningful
  6. Rename new DB
  7. Test application again
  8. Drop the old database

In case of emergency, just rename DBs back

what does mysql_real_escape_string() really do?

Best explained here.

http://www.w3schools.com/php/func_mysql_real_escape_string.asp

http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

It generally it helps to avoid SQL injection, for example consider the following code:

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

and a hacker can send a query like:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Where is web.xml in Eclipse Dynamic Web Project

When you create a Dynamic Web Project you have the option to automatically create the web.xml file. If you don't mark that, the eclipse doesn't create it...

So, you have to add a new web.xml file in the WEB-INF folder.

To add a web.xml click on Next -> Next instead of Finish. You will find it on the final screen of the wizard.

Apache server keeps crashing, "caught SIGTERM, shutting down"

Have you asked your provider to investigate? I assume this is not a dedicated server,

On the face of it, this seems like a security exception and somone is trying to exploit it / or there is a process running at a set time which is causing this, can you think of anything that runs on the server every 2 days? Logging tools?

SIGTERM is the signal sent to a process to request its termination. The symbolic constant for SIGTERM is defined in the header file signal.h. Symbolic signal names are used because signal numbers can vary across platforms, however on the vast majority of systems, SIGTERM is signal #15.

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

if for some reason you need to add via code, you can use this:

mTextView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

where left, top, right bottom are Drawables

Class not registered Error

Somewhere in the code you are using, there is a call to the Win32 API, CoCreateInstance, to dynamically load a DLL and instantiate an object from it.

The mapping between the component ID and the DLL that is capable of instantiating that object is usually found in HEKY_CLASSES_ROOT\CLSID in the registry. To discuss this further would be to explain a lot about COM in Windows. But the error indicates that the COM guid is not present in the registry.

I don't much about what the PackAndGo DLL is (an Autodesk component), but I suspect you simply need to "install" that component or the software package it came with through the designated installer to have that DLL and appropriate COM registry keys on your computer you are trying to run your code on. (i.e. go run setup.exe for this product).

In other words, I think you need to install "Pack and Go" on this computer instead of just copying the DLL to the target machine.

Also, make sure you decide to build your code appropriate as 32-bit vs. 64-bit depending on the which build flavor (32 or 64 bit) of Pack And Go you install.

Trim spaces from start and end of string

jQuery.trim(" hello, how are you? ");

:)

Import multiple csv files into pandas and concatenate into one DataFrame

Another on-liner with list comprehension which allows to use arguments with read_csv.

df = pd.concat([pd.read_csv(f'dir/{f}') for f in os.listdir('dir') if f.endswith('.csv')])

Compare two objects' properties to find differences?

Sure you can with reflection. Here is the code to grab the properties off of a given type.

var info = typeof(SomeType).GetProperties();

If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names

public bool AreDifferent(Type t1, Type t2) {
  var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  return list1.SequenceEqual(list2);
}

What is the 'override' keyword in C++ used for?

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

   class Foo
   {
   public:
        virtual void func1();
   }

   class Bar : public Foo
   {
   public:
        void func1() override;
   }

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

How to trigger jQuery change event in code

Use That :

$(selector).trigger("change");

OR

$('#id').trigger("click");

OR

$('.class').trigger(event);

Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.

File Upload In Angular?

From the answers above I build this with Angular 5.x

Just call uploadFile(url, file).subscribe() to trigger an upload

import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";

@Injectable()
export class UploadService {

  constructor(private http: HttpClient) { }

  // file from event.target.files[0]
  uploadFile(url: string, file: File): Observable<HttpEvent<any>> {

    let formData = new FormData();
    formData.append('upload', file);

    let params = new HttpParams();

    const options = {
      params: params,
      reportProgress: true,
    };

    const req = new HttpRequest('POST', url, formData, options);
    return this.http.request(req);
  }
}

Use it like this in your component

  // At the drag drop area
  // (drop)="onDropFile($event)"
  onDropFile(event: DragEvent) {
    event.preventDefault();
    this.uploadFile(event.dataTransfer.files);
  }

  // At the drag drop area
  // (dragover)="onDragOverFile($event)"
  onDragOverFile(event) {
    event.stopPropagation();
    event.preventDefault();
  }

  // At the file input element
  // (change)="selectFile($event)"
  selectFile(event) {
    this.uploadFile(event.target.files);
  }

  uploadFile(files: FileList) {
    if (files.length == 0) {
      console.log("No file selected!");
      return

    }
    let file: File = files[0];

    this.upload.uploadFile(this.appCfg.baseUrl + "/api/flash/upload", file)
      .subscribe(
        event => {
          if (event.type == HttpEventType.UploadProgress) {
            const percentDone = Math.round(100 * event.loaded / event.total);
            console.log(`File is ${percentDone}% loaded.`);
          } else if (event instanceof HttpResponse) {
            console.log('File is completely loaded!');
          }
        },
        (err) => {
          console.log("Upload Error:", err);
        }, () => {
          console.log("Upload done");
        }
      )
  }

error: use of deleted function

gcc 4.6 supports a new feature of deleted functions, where you can write

hdealt() = delete;

to disable the default constructor.

Here the compiler has obviously seen that a default constructor can not be generated, and =delete'd it for you.

What is the difference between "px", "dip", "dp" and "sp"?

Pixels(px) – corresponds to actual pixels on the screen. This is used if you want to give in terms of absolute pixels for width or height.

Density-independent Pixels (dp or dip) – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

Scale-independent Pixels(sp) – this is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user’s preference.

Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities. You can learn more about pixel and dp from https://www.google.com/design/spec/layout/units-measurements.html#units-measurements-density-independent-pixels-dp-

Source url:- http://www.androidtutorialshub.com/what-is-the-difference-between-px-dp-dip-sp-on-android/

Wrap text in <td> tag

use word-break it can be used without styling table to table-layout: fixed

_x000D_
_x000D_
table {_x000D_
  width: 140px;_x000D_
  border: 1px solid #bbb_x000D_
}_x000D_
_x000D_
.tdbreak {_x000D_
  word-break: break-all_x000D_
}
_x000D_
<p>without word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>LOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>with word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="tdbreak">LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

ORA-00972 identifier is too long alias column name

As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

Apparently this would be possible in settings.gradle with something like this.

rootProject.name = 'someName'
gradle.rootProject {
    it.sourceCompatibility = '1.7'
}

I recently received advice that a project property can be set by using a closure which will be called later when the Project is available.

Is it possible to use jQuery .on and hover?

(Look at the last edit in this answer if you need to use .on() with elements populated with JavaScript)

Use this for elements that are not populated using JavaScript:

$(".selector").on("mouseover", function () {
    //stuff to do on mouseover
});

.hover() has it's own handler: http://api.jquery.com/hover/

If you want to do multiple things, chain them in the .on() handler like so:

$(".selector").on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

According to the answers provided below you can use hover with .on(), but:

Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

Also, there are no performance advantages to using it and it's more bulky than just using mouseenter or mouseleave. The answer I provided requires less code and is the proper way to achieve something like this.

EDIT

It's been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.

While I prefer using mouseenter and mouseleave (helps me understand whats going on in the code) with .on() it is just the same as writing the following with hover()

$(".selector").hover(function () {
    //stuff to do on mouse enter
}, 
function () {
    //stuff to do on mouse leave
});

Since the original question did ask how they could properly use on() with hover(), I thought I would correct the usage of on() and didn't find it necessary to add the hover() code at the time.

EDIT DECEMBER 11, 2012

Some new answers provided below detail how .on() should work if the div in question is populated using JavaScript. For example, let's say you populate a div using jQuery's .load() event, like so:

(function ($) {
    //append div to document body
    $('<div class="selector">Test</div>').appendTo(document.body);
}(jQuery));

The above code for .on() would not stand. Instead, you should modify your code slightly, like this:

$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on

This code will work for an element populated with JavaScript after a .load() event has happened. Just change your argument to the appropriate selector.

pandas python how to count the number of records or rows in a dataframe

Simply, row_num = df.shape[0] # gives number of rows, here's the example:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2

How to parse Excel (XLS) file in Javascript/HTML5

This code can help you
Most of the time jszip.js is not working so include xlsx.full.min.js in your js code.

Html Code

 <input type="file" id="file" ng-model="csvFile"  
    onchange="angular.element(this).scope().ExcelExport(event)"/>

Javascript

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.8/xlsx.full.min.js">
</script>

$scope.ExcelExport= function (event) {


    var input = event.target;
    var reader = new FileReader();
    reader.onload = function(){
        var fileData = reader.result;
        var wb = XLSX.read(fileData, {type : 'binary'});

        wb.SheetNames.forEach(function(sheetName){
        var rowObj =XLSX.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
        var jsonObj = JSON.stringify(rowObj);
        console.log(jsonObj)
        })
    };
    reader.readAsBinaryString(input.files[0]);
    };

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The only thing that worked for me was the accepted answer of

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();

HOWEVER

This brought about new issues, of having <?xml encoding="utf-8" ?> in the output of the document.

The solution for me was then to do

foreach ($doc->childNodes as $xx) {
    if ($xx instanceof \DOMProcessingInstruction) {
        $xx->parentNode->removeChild($xx);
    }
}

Some solutions told me that to remove the xml header, that I had to perform

$dom->saveXML($dom->documentElement);

This didn't work for me as for a partial document (e.g. a doc with two <p> tags), only one of the <p> tags where being returned.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

For me the issue was caused by com.google.android.exoplayer conflicting with com.facebook.android:audience-network-sdk.

I fixed the problem by excluding the exoplayer library from the audience-network-sdk :

compile ('com.facebook.android:audience-network-sdk:4.24.0') {
    exclude group: 'com.google.android.exoplayer'
}

How to delete duplicate lines in a file without sorting it in Unix?

Perl one-liner similar to @jonas's awk solution:

perl -ne 'print if ! $x{$_}++' file

This variation removes trailing whitespace before comparing:

perl -lne 's/\s*$//; print if ! $x{$_}++' file

This variation edits the file in-place:

perl -i -ne 'print if ! $x{$_}++' file

This variation edits the file in-place, and makes a backup file.bak

perl -i.bak -ne 'print if ! $x{$_}++' file

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

The issue is with your project which is not able to complete maven build. Steps to follow :

  1. Right Click Application and RunAs maven install.
  2. If you get any error while reaching the repos online try giving the proxies in settings.xml under your .m2 directory.Check this link for setting proxies for maven build.
  3. Once done , try doing a Update Project by Right Click Project , Maven->Update Maven Project and select codebase and do check the Force Update of Snapshot/Release check box.

This will update your maven build and will surely remove your errors with pom.xml

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

Simple solution is to run this query: mysql -h yourhostname -u username -p databasename < yoursqlfile.sql

And if you want to import with progress bar, try this: pv yoursqlfile.sql | mysql -uxxx -pxxxx databasename

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

How can I know if Object is String type object?

 object instanceof Type

is true if the object is a Type or a subclass of Type

 object.getClass().equals(Type.class) 

is true only if the object is a Type

How to read a single character at a time from a file in Python?

#reading out the file at once in a list and then printing one-by-one
f=open('file.txt')
for i in list(f.read()):
    print(i)

How to run ~/.bash_profile in mac terminal

If you change .bash_profile, it only applies to new Terminal sessions.

To apply it to an existing session, run source ~/.bash_profile. You can run any Bash script this way - think of executing source as the same as typing commands in the Terminal window (from the specified script).

More info: How to reload .bash_profile from the command line?

Bonus: You can make environment variables available to OSX applications - not just the current Bash session but apps like Visual Studio Code or IntelliJ - using launchctl setenv GOPATH "${GOPATH:-}"

Merge DLL into EXE?

NOTE: if you're trying to load a non-ILOnly assembly, then

Assembly.Load(block)

won't work, and an exception will be thrown: more details

I overcame this by creating a temporary file, and using

Assembly.LoadFile(dllFile)

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

WScript.exe exists in two versions, one in C:\Windows\System32\ and the other in C:\Windows\SysWOW64\ directories. They run respectively in 64 bits and 32 bits (against immediate logic but true).

You may add the following code at the beginning of your script so that it automatically starts again in 32 bits if it detects that it's called in 64 bits.

Note that it transmits the arguments if it calls itself to switch to 64 bits.

' C:\Windows\System32\WScript.exe = WScript.exe
Dim ScriptHost : ScriptHost = Mid(WScript.FullName, InStrRev(WScript.FullName, "\") + 1, Len(WScript.FullName))

Dim oWs : Set oWs = CreateObject("WScript.Shell")
Dim oProcEnv : Set oProcEnv = oWs.Environment("Process")

' Am I running 64-bit version of WScript.exe/Cscript.exe? So, call script again in x86 script host and then exit.
If InStr(LCase(WScript.FullName), LCase(oProcEnv("windir") & "\System32\")) And oProcEnv("PROCESSOR_ARCHITECTURE") = "AMD64" Then
    ' rebuild arguments
    If Not WScript.Arguments.Count = 0 Then
        Dim sArg, Arg
        sArg = ""
        For Each Arg In Wscript.Arguments
              sArg = sArg & " " & """" & Arg & """"
        Next
    End If

    Dim sCmd : sCmd = """" &  oProcEnv("windir") & "\SysWOW64\" & ScriptHost & """" & " """ & WScript.ScriptFullName & """" & sArg
    'WScript.Echo "Call " & sCmd
    oWs.Run sCmd
    WScript.Quit
End If

Searching if value exists in a list of objects using Linq

customerList.Any(x=>x.Firstname == "John")

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

Java: splitting the filename into a base and extension

What's wrong with your code? Wrapped in a neat utility method it's fine.

What's more important is what to use as separator — the first or last dot. The first is bad for file names like "setup-2.5.1.exe", the last is bad for file names with multiple extensions like "mybundle.tar.gz".

Simple Vim commands you wish you'd known earlier

I often make functions for editing tasks and store them in my .vimrc file, so I can find them again.

For example, reading .NET callstacks that have been converted into a single line:

function! FixCallStacks()
:%s;\[NLN\];\r;g
:%s;\[TAB\];\t;g
endfunction

UICollectionView cell selection and cell reuse

Changing the cell property such as the cell's background colors shouldn't be done on the UICollectionViewController itself, it should be done inside you CollectionViewCell class. Don't use didSelect and didDeselect, just use this:

class MyCollectionViewCell: UICollectionViewCell 
{
     override var isSelected: Bool
     {
         didSet
         {
            // Your code
         }
     } 
}

Getting the class name of an instance?

Good question.

Here's a simple example based on GHZ's which might help someone:

>>> class person(object):
        def init(self,name):
            self.name=name
        def info(self)
            print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__)
>>> bob = person(name='Robert')
>>> bob.info()
My name is Robert, I am a person

How can I make directory writable?

To make the parent directory as well as all other sub-directories writable, just add -R

chmod -R a+w <directory>

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

Difference between one-to-many and many-to-one relationship

one-to-many has parent class contains n number of childrens so it is a collection mapping.

many-to-one has n number of childrens contains one parent so it is a object mapping

Process to convert simple Python script into Windows executable

I would join @Nicholas in recommending PyInstaller (with the --onefile flag), but be warned: do not use the "latest release", PyInstaller 1.3 -- it's years old. Use the "pre-release" 1.4, download it here -- or even better the code from the svn repo -- install SVN and run svn co http://svn.pyinstaller.org/trunk pyinstaller.

As @Nicholas implies, dynamic libraries cannot be run from the same file as the rest of the executable -- but fortunately they can be packed together with all the rest in a "self-unpacking" executable that will unpack itself into some temporary directory as needed; PyInstaller does a good job at this (and at many other things -- py2exe is more popular, but pyinstaller in my opinion is preferable in all other respects).

C - error: storage size of ‘a’ isn’t known

You define your struct as xyx, however in your main, you use struct xyz a; , which only creates a forward declaration of a differently named struct.

Try using xyx a; instead of that line.

react-router go back a page how do you configure history?

Simply use like this

<span onClick={() => this.props.history.goBack()}>Back</span>

Read response body in JAX-RS client from a post request

For my use case, none of the previous answers worked because I was writing a server-side unit test which was failing due the following error message as described in the Unable to Mock Glassfish Jersey Client Response Object question:

java.lang.IllegalStateException: Method not supported on an outbound message.
at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145)
at ...

This exception occurred on the following line of code:

String actJsonBody = actResponse.readEntity(String.class);

The fix was to turn the problem line of code into:

String actJsonBody = (String) actResponse.getEntity();

How to reset settings in Visual Studio Code?

Go to File -> preferences -> settings.

On the right panel you will see all customized user settings so you can remove the ones you want to reset. On doing so the default settings mentioned in left pane will become active instantly.

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How do I get the Git commit count?

The one I used to use was:

git log | grep "^commit" | wc -l

Simple but it worked.

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Convert data.frame columns from factors to characters

The global option

stringsAsFactors: The default setting for arguments of data.frame and read.table.

may be something you want to set to FALSE in your startup files (e.g. ~/.Rprofile). Please see help(options).

Where can I download IntelliJ IDEA Color Schemes?

If you're just looking for a dark color scheme for IntelliJ IDEA, this is the first link I get in a Google search:

Dark Pastels theme for IntelliJ IDEA Dark Pastels theme for IntelliJ IDEA

Of course, you can tweak either of these two schemes to your satisfaction. Don't feel like you have to stick to the fonts and the colors that the original authors have chosen. We programmers don't get nearly enough change to try our hand at interior decorating to pass up this opportunity.

Is there any reason these won't work in the version you have? As best I can tell, you can simply import any theme that you want.

Is there a way to ignore a single FindBugs warning?

As others Mentioned, you can use the @SuppressFBWarnings Annotation. If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

Pyspark: Exception: Java gateway process exited before sending the driver its port number

I use Mac OS. I fixed the problem!

Below is how I fixed it.

JDK8 seems works fine. (https://github.com/jupyter/jupyter/issues/248)

So I checked my JDK /Library/Java/JavaVirtualMachines, I only have jdk-11.jdk in this path.

I downloaded JDK8 (I followed the link). Which is:

brew tap caskroom/versions
brew cask install java8

After this, I added

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"

to ~/.bash_profile file. (you sholud check your jdk1.8 file name)

It works now! Hope this help :)

How would you make a comma-separated string from a list of strings?

Don't you just want:

",".join(l)

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

https://docs.python.org/library/csv.html

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

How to handle the click event in Listview in android?

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",   
 Toast.LENGTH_SHORT).show();
}

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

Using Predicate in Swift

// change "name" and "value" according to your array data.

// Change "yourDataArrayName" name accroding to your array(NSArray).

    let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")

    if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {

 //enter code here.

        print(sortedDta)
    }

'ssh-keygen' is not recognized as an internal or external command

I just had this issue and thought I'd share what I thought was an easier way around this.

Open git-bash and run the same command with the addition of -C since you're commenting in your email address: ssh-keygen -t rsa -C "[email protected]" command. That's it.

git-bash should have been installed when you installed git. If you can't find it you can check C:\Program Files\Git\Git Bash

The first time I did this it failed to create the .ssh folder for me so I had to open a standard Command Prompt and mkdir C:\Users\yourusername\.ssh

How do I round to the nearest 0.5?

There are several options. If performance is a concern, test them to see which works fastest in a large loop.

double Adjust(double input)
{
    double whole = Math.Truncate(input);
    double remainder = input - whole;
    if (remainder < 0.3)
    {
        remainder = 0;
    }
    else if (remainder < 0.8)
    {
        remainder = 0.5;
    }
    else
    {
        remainder = 1;
    }
    return whole + remainder;
}

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

How to open in default browser in C#

This opened the default for me:

System.Diagnostics.Process.Start(e.LinkText.ToString());

sequelize findAll sort order in nodejs

I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)

So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).

When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):

var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.

Using Node.JS, how do I read a JSON file into (server) memory?

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })

How to copy a file from one directory to another using PHP?

Best way to copy all files from one folder to another using PHP

<?php
$src = "/home/www/example.com/source/folders/123456";  // source folder or file
$dest = "/home/www/example.com/test/123456";   // destination folder or file        

shell_exec("cp -r $src $dest");

echo "<H2>Copy files completed!</H2>"; //output when done
?>

Change the size of a JTextField inside a JBorderLayout

From the api on GridLayout:

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).

    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );

T-SQL Subquery Max(Date) and Joins

SELECT
    MyParts.*,MyPriceDate.Price,MyPriceDate.PriceDate
    FROM MyParts
        INNER JOIN (SELECT Partid, MAX(PriceDate) AS MaxPriceDate FROM MyPrice GROUP BY Partid) dt ON MyParts.Partid = dt.Partid
        INNER JOIN MyPrice ON dt.Partid = MyPrice.Partid AND MyPrice.PriceDate=dt.MaxPriceDate

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

SQL update from one Table to another based on a ID match

Use the following block of query to update Table1 with Table2 based on ID:

UPDATE Sales_Import, RetrieveAccountNumber 
SET Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber 
where Sales_Import.LeadID = RetrieveAccountNumber.LeadID;

This is the easiest way to tackle this problem.

Adding three months to a date in PHP

This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.

$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

How can I pad a String in Java?

java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]

Parsing JSON with Unix tools

For more complex JSON parsing I suggest using python jsonpath module (by Stefan Goessner) -

  1. Install it -

sudo easy_install -U jsonpath

  1. Use it -

Example file.json (from http://goessner.net/articles/JsonPath) -

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Parse it (extract all book titles with price < 10) -

$ cat file.json | python -c "import sys, json, jsonpath; print '\n'.join(jsonpath.jsonpath(json.load(sys.stdin), 'store.book[?(@.price < 10)].title'))"

Will output -

Sayings of the Century
Moby Dick

NOTE: The above command line does not include error checking. for full solution with error checking you should create small python script, and wrap the code with try-except.

Multiple WHERE Clauses with LINQ extension methods

If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:

// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();

if (condition1)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}

if (condition2)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}

if (condition3)
{
    predicate = predicate.And(d => d.SomeIntProperty >= 4);
}

return originalCollection.Where<YourDataClass>(predicate.Compile());

The full source of mentioned PredicateBuilder is bellow (but you could also check the original page with a few more examples):

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

Note: I've tested this approach with Portable Class Library project and have to use .Compile() to make it work:

Where(predicate .Compile() );

Python - How to concatenate to a string in a for loop?

This should work:

endstring = ''.join(list)

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

Getting the client's time zone (and offset) in JavaScript

try getTimezoneOffset() of the Date object:

var curdate = new Date()
var offset = curdate.getTimezoneOffset()

This method returns time zone offset in minutes which is the difference between GMT and local time in minutes.

What is the difference between primary, unique and foreign key constraints, and indexes?

Here are some reference for you:

Primary & foreign key Constraint.

Primary Key: A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.

Foreign Key: A foreign key (sometimes called a referencing key) is a key used to link two tables together. Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key (it remains a primary key in the original table).

Index, on the other hand, is an attribute that you can apply on some columns so that the data retrieval done on those columns can be speed up.

How to use 'hover' in CSS

You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).

<a class="hover">click</a>

<style type="text/css">

    a.hover:hover {
        text-decoration: underline;

    }

</style>

Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)

how to display data values on Chart.js

Edited @ajhuddy's answer a little. Only for bar charts. My version adds:

  • Fade in animation for the values.
  • Prevent clipping by positioning the value inside the bar if the bar is too high.
  • No blinking.

Example

Downside: When hovering over a bar that has value inside it the value might look a little jagged. I have not found a solution do disable hover effects. It might also need tweaking depending on your own settings.

Configuration:

bar: {
  tooltips: {
    enabled: false
  },
  hover: {
    animationDuration: 0
  },
  animation: {
    onComplete: function() {
      this.chart.controller.draw();
      drawValue(this, 1);
    },
    onProgress: function(state) {
      var animation = state.animationObject;
      drawValue(this, animation.currentStep / animation.numSteps);
    }
  }
}

Helpers:

// Font color for values inside the bar
var insideFontColor = '255,255,255';
// Font color for values above the bar
var outsideFontColor = '0,0,0';
// How close to the top edge bar can be before the value is put inside it
var topThreshold = 20;

var modifyCtx = function(ctx) {
  ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  return ctx;
};

var fadeIn = function(ctx, obj, x, y, black, step) {
  var ctx = modifyCtx(ctx);
  var alpha = 0;
  ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
  ctx.fillText(obj, x, y);
};

var drawValue = function(context, step) {
  var ctx = context.chart.ctx;

  context.data.datasets.forEach(function (dataset) {
    for (var i = 0; i < dataset.data.length; i++) {
      var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
      var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20;
      fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
    }
  });
};

Colorizing text in the console with C++

On Windows 10 you may use escape sequences this way:

#ifdef _WIN32
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
// print in red and restore colors default
std::cout << "\033[32m" << "Error!" << "\033[0m" << std::endl;

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Here is a solution that doesn't rely on complex math as sdcvvc's/Dimitris Andreou's answers do, doesn't change the input array as caf and Colonel Panic did, and doesn't use the bitset of enormous size as Chris Lercher, JeremyP and many others did. Basically, I began with Svalorzen's/Gilad Deutch's idea for Q2, generalized it to the common case Qk and implemented in Java to prove that the algorithm works.

The idea

Suppose we have an arbitrary interval I of which we only know that it contains at least one of the missing numbers. After one pass through the input array, looking only at the numbers from I, we can obtain both the sum S and the quantity Q of missing numbers from I. We do this by simply decrementing I's length each time we encounter a number from I (for obtaining Q) and by decreasing pre-calculated sum of all numbers in I by that encountered number each time (for obtaining S).

Now we look at S and Q. If Q = 1, it means that then I contains only one of the missing numbers, and this number is clearly S. We mark I as finished (it is called "unambiguous" in the program) and leave it out from further consideration. On the other hand, if Q > 1, we can calculate the average A = S / Q of missing numbers contained in I. As all numbers are distinct, at least one of such numbers is strictly less than A and at least one is strictly greater than A. Now we split I in A into two smaller intervals each of which contains at least one missing number. Note that it doesn't matter to which of the intervals we assign A in case it is an integer.

We make the next array pass calculating S and Q for each of the intervals separately (but in the same pass) and after that mark intervals with Q = 1 and split intervals with Q > 1. We continue this process until there are no new "ambiguous" intervals, i.e. we have nothing to split because each interval contains exactly one missing number (and we always know this number because we know S). We start out from the sole "whole range" interval containing all possible numbers (like [1..N] in the question).

Time and space complexity analysis

The total number of passes p we need to make until the process stops is never greater than the missing numbers count k. The inequality p <= k can be proved rigorously. On the other hand, there is also an empirical upper bound p < log2N + 3 that is useful for large values of k. We need to make a binary search for each number of the input array to determine the interval to which it belongs. This adds the log k multiplier to the time complexity.

In total, the time complexity is O(N ? min(k, log N) ? log k). Note that for large k, this is significantly better than that of sdcvvc/Dimitris Andreou's method, which is O(N ? k).

For its work, the algorithm requires O(k) additional space for storing at most k intervals, that is significantly better than O(N) in "bitset" solutions.

Java implementation

Here's a Java class that implements the above algorithm. It always returns a sorted array of missing numbers. Besides that, it doesn't require the missing numbers count k because it calculates it in the first pass. The whole range of numbers is given by the minNumber and maxNumber parameters (e.g. 1 and 100 for the first example in the question).

public class MissingNumbers {
    private static class Interval {
        boolean ambiguous = true;
        final int begin;
        int quantity;
        long sum;

        Interval(int begin, int end) { // begin inclusive, end exclusive
            this.begin = begin;
            quantity = end - begin;
            sum = quantity * ((long)end - 1 + begin) / 2;
        }

        void exclude(int x) {
            quantity--;
            sum -= x;
        }
    }

    public static int[] find(int minNumber, int maxNumber, NumberBag inputBag) {
        Interval full = new Interval(minNumber, ++maxNumber);
        for (inputBag.startOver(); inputBag.hasNext();)
            full.exclude(inputBag.next());
        int missingCount = full.quantity;
        if (missingCount == 0)
            return new int[0];
        Interval[] intervals = new Interval[missingCount];
        intervals[0] = full;
        int[] dividers = new int[missingCount];
        dividers[0] = minNumber;
        int intervalCount = 1;
        while (true) {
            int oldCount = intervalCount;
            for (int i = 0; i < oldCount; i++) {
                Interval itv = intervals[i];
                if (itv.ambiguous)
                    if (itv.quantity == 1) // number inside itv uniquely identified
                        itv.ambiguous = false;
                    else
                        intervalCount++; // itv will be split into two intervals
            }
            if (oldCount == intervalCount)
                break;
            int newIndex = intervalCount - 1;
            int end = maxNumber;
            for (int oldIndex = oldCount - 1; oldIndex >= 0; oldIndex--) {
                // newIndex always >= oldIndex
                Interval itv = intervals[oldIndex];
                int begin = itv.begin;
                if (itv.ambiguous) {
                    // split interval itv
                    // use floorDiv instead of / because input numbers can be negative
                    int mean = (int)Math.floorDiv(itv.sum, itv.quantity) + 1;
                    intervals[newIndex--] = new Interval(mean, end);
                    intervals[newIndex--] = new Interval(begin, mean);
                } else
                    intervals[newIndex--] = itv;
                end = begin;
            }
            for (int i = 0; i < intervalCount; i++)
                dividers[i] = intervals[i].begin;
            for (inputBag.startOver(); inputBag.hasNext();) {
                int x = inputBag.next();
                // find the interval to which x belongs
                int i = java.util.Arrays.binarySearch(dividers, 0, intervalCount, x);
                if (i < 0)
                    i = -i - 2;
                Interval itv = intervals[i];
                if (itv.ambiguous)
                    itv.exclude(x);
            }
        }
        assert intervalCount == missingCount;
        for (int i = 0; i < intervalCount; i++)
            dividers[i] = (int)intervals[i].sum;
        return dividers;
    }
}

For fairness, this class receives input in form of NumberBag objects. NumberBag doesn't allow array modification and random access and also counts how many times the array was requested for sequential traversing. It is also more suitable for large array testing than Iterable<Integer> because it avoids boxing of primitive int values and allows wrapping a part of a large int[] for a convenient test preparation. It is not hard to replace, if desired, NumberBag by int[] or Iterable<Integer> type in the find signature, by changing two for-loops in it into foreach ones.

import java.util.*;

public abstract class NumberBag {
    private int passCount;

    public void startOver() {
        passCount++;
    }

    public final int getPassCount() {
        return passCount;
    }

    public abstract boolean hasNext();

    public abstract int next();

    // A lightweight version of Iterable<Integer> to avoid boxing of int
    public static NumberBag fromArray(int[] base, int fromIndex, int toIndex) {
        return new NumberBag() {
            int index = toIndex;

            public void startOver() {
                super.startOver();
                index = fromIndex;
            }

            public boolean hasNext() {
                return index < toIndex;
            }

            public int next() {
                if (index >= toIndex)
                    throw new NoSuchElementException();
                return base[index++];
            }
        };
    }

    public static NumberBag fromArray(int[] base) {
        return fromArray(base, 0, base.length);
    }

    public static NumberBag fromIterable(Iterable<Integer> base) {
        return new NumberBag() {
            Iterator<Integer> it;

            public void startOver() {
                super.startOver();
                it = base.iterator();
            }

            public boolean hasNext() {
                return it.hasNext();
            }

            public int next() {
                return it.next();
            }
        };
    }
}

Tests

Simple examples demonstrating the usage of these classes are given below.

import java.util.*;

public class SimpleTest {
    public static void main(String[] args) {
        int[] input = { 7, 1, 4, 9, 6, 2 };
        NumberBag bag = NumberBag.fromArray(input);
        int[] output = MissingNumbers.find(1, 10, bag);
        System.out.format("Input: %s%nMissing numbers: %s%nPass count: %d%n",
                Arrays.toString(input), Arrays.toString(output), bag.getPassCount());

        List<Integer> inputList = new ArrayList<>();
        for (int i = 0; i < 10; i++)
            inputList.add(2 * i);
        Collections.shuffle(inputList);
        bag = NumberBag.fromIterable(inputList);
        output = MissingNumbers.find(0, 19, bag);
        System.out.format("%nInput: %s%nMissing numbers: %s%nPass count: %d%n",
                inputList, Arrays.toString(output), bag.getPassCount());

        // Sieve of Eratosthenes
        final int MAXN = 1_000;
        List<Integer> nonPrimes = new ArrayList<>();
        nonPrimes.add(1);
        int[] primes;
        int lastPrimeIndex = 0;
        while (true) {
            primes = MissingNumbers.find(1, MAXN, NumberBag.fromIterable(nonPrimes));
            int p = primes[lastPrimeIndex]; // guaranteed to be prime
            int q = p;
            for (int i = lastPrimeIndex++; i < primes.length; i++) {
                q = primes[i]; // not necessarily prime
                int pq = p * q;
                if (pq > MAXN)
                    break;
                nonPrimes.add(pq);
            }
            if (q == p)
                break;
        }
        System.out.format("%nSieve of Eratosthenes. %d primes up to %d found:%n",
                primes.length, MAXN);
        for (int i = 0; i < primes.length; i++)
            System.out.format(" %4d%s", primes[i], (i % 10) < 9 ? "" : "\n");
    }
}

Large array testing can be performed this way:

import java.util.*;

public class BatchTest {
    private static final Random rand = new Random();
    public static int MIN_NUMBER = 1;
    private final int minNumber = MIN_NUMBER;
    private final int numberCount;
    private final int[] numbers;
    private int missingCount;
    public long finderTime;

    public BatchTest(int numberCount) {
        this.numberCount = numberCount;
        numbers = new int[numberCount];
        for (int i = 0; i < numberCount; i++)
            numbers[i] = minNumber + i;
    }

    private int passBound() {
        int mBound = missingCount > 0 ? missingCount : 1;
        int nBound = 34 - Integer.numberOfLeadingZeros(numberCount - 1); // ceil(log_2(numberCount)) + 2
        return Math.min(mBound, nBound);
    }

    private void error(String cause) {
        throw new RuntimeException("Error on '" + missingCount + " from " + numberCount + "' test, " + cause);
    }

    // returns the number of times the input array was traversed in this test
    public int makeTest(int missingCount) {
        this.missingCount = missingCount;
        // numbers array is reused when numberCount stays the same,
        // just Fisher–Yates shuffle it for each test
        for (int i = numberCount - 1; i > 0; i--) {
            int j = rand.nextInt(i + 1);
            if (i != j) {
                int t = numbers[i];
                numbers[i] = numbers[j];
                numbers[j] = t;
            }
        }
        final int bagSize = numberCount - missingCount;
        NumberBag inputBag = NumberBag.fromArray(numbers, 0, bagSize);
        finderTime -= System.nanoTime();
        int[] found = MissingNumbers.find(minNumber, minNumber + numberCount - 1, inputBag);
        finderTime += System.nanoTime();
        if (inputBag.getPassCount() > passBound())
            error("too many passes (" + inputBag.getPassCount() + " while only " + passBound() + " allowed)");
        if (found.length != missingCount)
            error("wrong result length");
        int j = bagSize; // "missing" part beginning in numbers
        Arrays.sort(numbers, bagSize, numberCount);
        for (int i = 0; i < missingCount; i++)
            if (found[i] != numbers[j++])
                error("wrong result array, " + i + "-th element differs");
        return inputBag.getPassCount();
    }

    public static void strideCheck(int numberCount, int minMissing, int maxMissing, int step, int repeats) {
        BatchTest t = new BatchTest(numberCount);
        System.out.println("¦-----------------------+-----------------+-----------------¦");
        for (int missingCount = minMissing; missingCount <= maxMissing; missingCount += step) {
            int minPass = Integer.MAX_VALUE;
            int passSum = 0;
            int maxPass = 0;
            t.finderTime = 0;
            for (int j = 1; j <= repeats; j++) {
                int pCount = t.makeTest(missingCount);
                if (pCount < minPass)
                    minPass = pCount;
                passSum += pCount;
                if (pCount > maxPass)
                    maxPass = pCount;
            }
            System.out.format("¦ %9d  %9d  ¦  %2d  %5.2f  %2d  ¦  %11.3f    ¦%n", missingCount, numberCount, minPass,
                    (double)passSum / repeats, maxPass, t.finderTime * 1e-6 / repeats);
        }
    }

    public static void main(String[] args) {
        System.out.println("+-----------------------------------------------------------+");
        System.out.println("¦      Number count     ¦      Passes     ¦  Average time   ¦");
        System.out.println("¦   missimg     total   ¦  min  avg   max ¦ per search (ms) ¦");
        long time = System.nanoTime();
        strideCheck(100, 0, 100, 1, 20_000);
        strideCheck(100_000, 2, 99_998, 1_282, 15);
        MIN_NUMBER = -2_000_000_000;
        strideCheck(300_000_000, 1, 10, 1, 1);
        time = System.nanoTime() - time;
        System.out.println("+-----------------------------------------------------------+");
        System.out.format("%nSuccess. Total time: %.2f s.%n", time * 1e-9);
    }
}

Try them out on Ideone

What is an .inc and why use it?

It's just a way for the developer to be able to easily identify files which are meant to be used as includes. It's a popular convention. It does not have any special meaning to PHP, and won't change the behaviour of PHP or the script itself.

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

Pandas read_csv low_memory and dtype options

Try:

dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')

According to the pandas documentation:

dtype : Type name or dict of column -> type

As for low_memory, it's True by default and isn't yet documented. I don't think its relevant though. The error message is generic, so you shouldn't need to mess with low_memory anyway. Hope this helps and let me know if you have further problems

How to detect duplicate values in PHP array?

$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;

Add the loading screen in starting of the android application

You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res folder and make a class like this :-

public class LoadingScreen {private ImageView loading;

LoadingScreen(ImageView loading) {
    this.loading = loading;
}

public void setLoadScreen(){
    final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
    final Handler loadingHandler = new Handler();
    Runnable runnable = new Runnable() {
        int loadingImgIndex = 0;
        public void run() {
            loading.setImageResource(loadingImages[loadingImgIndex]);
            loadingImgIndex++;
            if (loadingImgIndex >= loadingImages.length)
                loadingImgIndex = 0;
            loadingHandler.postDelayed(this, 500);
        }
    };
    loadingHandler.postDelayed(runnable, 500);
}}

In your MainActivity, you can pass a to the LoadingScreen class like this :-

private ImageView loadingImage;

Don't forget to add an ImageView in activity_main. After that call the LoadingScreen class like this;

LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();

I hope this will help you

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

pip install failing with: OSError: [Errno 13] Permission denied on directory

If you need permissions, you cannot use 'pip' with 'sudo'. You can do a trick, so that you can use 'sudo' and install package. Just place 'sudo python -m ...' in front of your pip command.

sudo python -m pip install --user -r package_name

"VT-x is not available" when I start my Virtual machine

Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?

Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.

Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

The entity type <type> is not part of the model for the current context

Could be stupid, but if you only got this error on some Table, dont forget to clean your project and rebuild (could save a lot of time)

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

Export to csv/excel from kibana

I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

Meaning of "referencing" and "dereferencing" in C

The context that * is in, confuses the meaning sometimes.

  // when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.   

//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.) 


    //when calling a function
int main(){ 
    function(&var);  // we are giving the function a 'reference', we are giving it an 'address'
  }

So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.

In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)

int* p;
int *a;   // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).

int c = 10;  //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)

p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c

a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"

*a = 10;
 a = 0xab33d111;

Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.

//Why it's used
int function(b){
    b = b + 1; // we just want to add one to any variable that this function operates on.
} 

int main(){

    int c = 1;  // I want this variable to be 3.

    function(c); 
    function(c);// I call the function I made above twice, because I want c to be 3.

     // this will return c as 1. Even though I called it twice.
     // when you call a function it makes a copy of the variable.
     // so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
  //let's redo this whole thing, and use pointers

int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}

int main(){
    int c = 1; //again, I want this to be three at the end of the program
    int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
    function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.

    function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...


      //now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.

}

Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.

What do these three dots in React do?

This a spread operator...

For example if you have an array first=[1,2,3,4,5] and another second=[6,7,8].

[...first, ...second] //result is [1,2,3,4,5,6,7,8]

The same can also be done with json objects.

Returning a value from thread?

class Program
{
    static void Main(string[] args)
    {
        string returnValue = null;
       new Thread(
          () =>
          {
              returnValue =test() ; 
          }).Start();
        Console.WriteLine(returnValue);
        Console.ReadKey();
    }

    public static string test()
    {
        return "Returning From Thread called method";
    }
}

Detect if PHP session exists

According to the PHP.net manual:

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

Can a foreign key refer to a primary key in the same table?

Other answers have given clear enough examples of a record referencing another record in the same table.

There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.

All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.

Popular relational database management systems support this use case smoothly.

Take-aways:

  1. When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.

  2. When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.

  3. Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Convert a PHP object to an associative array

I think it is a nice idea to use traits to store object-to-array converting logic. A simple example:

trait ArrayAwareTrait
{
    /**
     * Return list of Entity's parameters
     * @return array
     */
    public function toArray()
    {
        $props = array_flip($this->getPropertiesList());
        return array_map(
            function ($item) {
                if ($item instanceof \DateTime) {
                    return $item->format(DATE_ATOM);
                }
                return $item;
            },
            array_filter(get_object_vars($this), function ($key) use ($props) {
                return array_key_exists($key, $props);
            }, ARRAY_FILTER_USE_KEY)
        );
    }


    /**
     * @return array
     */
    protected function getPropertiesList()
    {
        if (method_exists($this, '__sleep')) {
            return $this->__sleep();
        }
        if (defined('static::PROPERTIES')) {
            return static::PROPERTIES;
        }
        return [];
    }
}

class OrderResponse
{
    use ArrayAwareTrait;

    const PROP_ORDER_ID = 'orderId';
    const PROP_TITLE = 'title';
    const PROP_QUANTITY = 'quantity';
    const PROP_BUYER_USERNAME = 'buyerUsername';
    const PROP_COST_VALUE = 'costValue';
    const PROP_ADDRESS = 'address';

    private $orderId;
    private $title;
    private $quantity;
    private $buyerUsername;
    private $costValue;
    private $address;

    /**
     * @param $orderId
     * @param $title
     * @param $quantity
     * @param $buyerUsername
     * @param $costValue
     * @param $address
     */
    public function __construct(
        $orderId,
        $title,
        $quantity,
        $buyerUsername,
        $costValue,
        $address
    ) {
        $this->orderId = $orderId;
        $this->title = $title;
        $this->quantity = $quantity;
        $this->buyerUsername = $buyerUsername;
        $this->costValue = $costValue;
        $this->address = $address;
    }

    /**
     * @inheritDoc
     */
    public function __sleep()
    {
        return [
            static::PROP_ORDER_ID,
            static::PROP_TITLE,
            static::PROP_QUANTITY,
            static::PROP_BUYER_USERNAME,
            static::PROP_COST_VALUE,
            static::PROP_ADDRESS,
        ];
    }

    /**
     * @return mixed
     */
    public function getOrderId()
    {
        return $this->orderId;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @return mixed
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * @return mixed
     */
    public function getBuyerUsername()
    {
        return $this->buyerUsername;
    }

    /**
     * @return mixed
     */
    public function getCostValue()
    {
        return $this->costValue;
    }

    /**
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }
}

$orderResponse = new OrderResponse(...);
var_dump($orderResponse->toArray());

Delete branches in Bitbucket

If you are using a pycharm IDE for development and you already have added Git with it. you can directly delete remote branch from pycharm. From toolbar VCS-->Git-->Branches-->Select branch-->and Delete. It will delete it from remote git server.

Does Python's time.time() return the local or UTC timestamp?

This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])

You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:

>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000

The now differs from utcnow as expected -- otherwise they work the same way:

>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000

You can render the timestamp to the string explicitly:

>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'

Or you can be even more explicit to format the timestamp the way you like:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'

If you want the ISO format, use the .isoformat() method of the object:

>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'

You can use these in variables for calculations and printing without conversions.

>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

What's the syntax for mod in java

Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!

How to print jquery object/array

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

SQL Server - Case Statement

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar. You could put your calculation into a derived table:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

A common table expression would work just as well:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

Show ProgressDialog Android

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            String xmlUrl = urls[0];

            URL u = new URL(xmlUrl);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lengthOfFile = c.getContentLength();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; // total = total + len1
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                xmlContent += buffer;
            }
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Retrieving latest announcements...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }

}

SQL order string as number

This works for me.

select * from tablename
order by cast(columnname as int) asc

How to remove files and directories quickly via terminal (bash shell)

rm -rf *

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Get a list of all git commits, including the 'lost' ones

Like @Kieran 's Answer, but for the console: git log --oneline --all --graph --decorate $(git reflog | awk '{print $1}')

Wait Until File Is Completely Written

It's an old thread, but I'll add some info for other people.

I experienced a similar issue with a program that writes PDF files, sometimes they take 30 seconds to render.. which is the same period that my watcher_FileCreated class waits before copying the file.

The files were not locked.

In this case I checked the size of the PDF and then waited 2 seconds before comparing the new size, if they were unequal the thread would sleep for 30 seconds and try again.