Programs & Examples On #Mixer

Anything related to audio mixers, i.e. hardware or software (virtual) devices used to mix the signals of independent audio sources together in order to produce a single audio signal out of them. Appropriate for questions about the software audio mixing applications commonly found on computers and smartphones.

overlay a smaller image on a larger image python OpenCv

A simple 4on4 pasting function that works-

def paste(background,foreground,pos=(0,0)):
    #get position and crop pasting area if needed
    x = pos[0]
    y = pos[1]
    bgWidth = background.shape[0]
    bgHeight = background.shape[1]
    frWidth = foreground.shape[0]
    frHeight = foreground.shape[1]
    width = bgWidth-x
    height = bgHeight-y
    if frWidth<width:
        width = frWidth
    if frHeight<height:
        height = frHeight
    # normalize alpha channels from 0-255 to 0-1
    alpha_background = background[x:x+width,y:y+height,3] / 255.0
    alpha_foreground = foreground[:width,:height,3] / 255.0
    # set adjusted colors
    for color in range(0, 3):
        fr = alpha_foreground * foreground[:width,:height,color]
        bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
        background[x:x+width,y:y+height,color] = fr+bg
    # set adjusted alpha and denormalize back to 0-255
    background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
    return background

'"SDL.h" no such file or directory found' when compiling

If the header file is /usr/include/sdl/SDL.h and your code has:

#include "SDL.h"

You need to either fix your code:

#include "sdl/SDL.h"

Or tell the preprocessor where to find include files:

CFLAGS = ... -I/usr/include/sdl ...

Moment.js with ReactJS (ES6)

If the other answers fail, importing it as

import moment from 'moment/moment.js'

may work.

Making a triangle shape using xml definitions?

See answer here: Custom arrows without image: Android

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="32dp"
        android:height="24dp"
        android:viewportWidth="32.0"
        android:viewportHeight="24.0">
    <path android:fillColor="#e4e4e8"
          android:pathData="M0 0 h32 l-16 24 Z"/>
</vector>

arrow

Setting HTTP headers

All of the above answers are wrong because they fail to handle the OPTIONS preflight request, the solution is to override the mux router's interface. See AngularJS $http get request failed with custom header (alllowed in CORS)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/save", saveHandler)
    http.Handle("/", &MyServer{r})
    http.ListenAndServe(":8080", nil);

}

type MyServer struct {
    r *mux.Router
}

func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin != "" {
        rw.Header().Set("Access-Control-Allow-Origin", origin)
        rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        rw.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}

UICollectionView spacing margins

To add 10px separation between each section just write this

flowLayout.sectionInset = UIEdgeInsetsMake(0.0, 0.0,10,0);

check if a number already exist in a list in python

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: -

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSet recipe, which is referred to in Python Documentation

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

Vue equivalent of setTimeout?

Kevin Muchwat above has the BEST answer, despite only 10 upvotes and not selected answer.

setTimeout(function () {
    this.basketAddSuccess = false
}.bind(this), 2000)

Let me explain WHY.

"Arrow Function" is ECMA6/ECMA2015. It's perfectly valid in compiled code or controlled client situations (cordova phone apps, Node.js), and it's nice and succinct. It will even probably pass your testing!

However, Microsoft in their infinite wisdom has decided that Internet Explorer WILL NOT EVER SUPPORT ECMA2015!

Their new Edge browser does, but that's not good enough for public facing websites.

Doing a standard function(){} and adding .bind(this) however is the ECMA5.1 (which IS fully supported) syntax for the exact same functionality.

This is also important in ajax/post .then/else calls. At the end of your .then(function){}) you need to bind(this) there as well so: .then(function(){this.flag = true}.bind(this))

I would have added this as a comment to Kevin's response, but for some silly reason it takes less points to post replies than to comment on replies

DO NOT MAKE THE SAME MISTAKE I MADE!

I code on a Mac, and used the 48 points upvoted comment which worked great! Until I got some calls on my scripts failing and I couldn't figure out why. I had to go back and update dozens of calls from arrow syntax to function(){}.bind(this) syntax.

Thankfully I found this thread again and got the right answer. Kevin, I am forever grateful.

As per the "Accepted answer", that has other potential issues dealing with additional libraries (had problems properly accessing/updating Vue properties/functions)

Changing file permission in Python

os.chmod(path, 0444) is the Python command for changing file permissions in Python 2.x. For a combined Python 2 and Python 3 solution, change 0444 to 0o444.

You could always use Python to call the chmod command using subprocess. I think this will only work on Linux though.

import subprocess

subprocess.call(['chmod', '0444', 'path'])

Adding a view controller as a subview in another view controller

Please also check the official documentation on implementing a custom container view controller:

https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html#//apple_ref/doc/uid/TP40007457-CH11-SW1

This documentation has much more detailed information for every instruction and also describes how to do add transitions.

Translated to Swift 3:

func cycleFromViewController(oldVC: UIViewController,
               newVC: UIViewController) {
   // Prepare the two view controllers for the change.
   oldVC.willMove(toParentViewController: nil)
   addChildViewController(newVC)

   // Get the start frame of the new view controller and the end frame
   // for the old view controller. Both rectangles are offscreen.r
   newVC.view.frame = view.frame.offsetBy(dx: view.frame.width, dy: 0)
   let endFrame = view.frame.offsetBy(dx: -view.frame.width, dy: 0)

   // Queue up the transition animation.
   self.transition(from: oldVC, to: newVC, duration: 0.25, animations: { 
        newVC.view.frame = oldVC.view.frame
        oldVC.view.frame = endFrame
    }) { (_: Bool) in
        oldVC.removeFromParentViewController()
        newVC.didMove(toParentViewController: self)
    }
}

Ruby Array find_first object?

Guess you just missed the find method in the docs:

my_array.find {|e| e.satisfies_condition? }

Java dynamic array sizes?

As others have said, you cannot change the size of an existing Java array.

ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:

  • You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
  • An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
  • You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.

If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )

If you only really need an array that grows as you are initializing it, then the solution is something like this.

ArrayList<T> tmp = new ArrayList<T>();
while (...) {
    tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);

Convert utf8-characters to iso-88591 and back in PHP

function parseUtf8ToIso88591(&$string){
     if(!is_null($string)){
            $iso88591_1 = utf8_decode($string);
            $iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $string);
            $string = mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');       
     }
}

Add a new column to existing table in a migration

If you're using Laravel 5, the command would be;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.

php artisan migrate is still the same though.

How do we determine the number of days for a given month in python

Use calendar.monthrange:

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

As @mikhail-pyrev mentions in a comment:

First number is weekday of first day of the month, second number is number of days in said month.

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

What is "overhead"?

A concrete example of overhead is the difference between a "local" procedure call and a "remote" procedure call.

For example, with classic RPC (and many other remote frameworks, like EJB), a function or method call looks the same to a coder whether its a local, in memory call, or a distributed, network call.

For example:

service.function(param1, param2);

Is that a normal method, or a remote method? From what you see here you can't tell.

But you can imagine that the difference in execution times between the two calls are dramatic.

So, while the core implementation will "cost the same", the "overhead" involved is quite different.

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

sql select with column name like

This will show you the table name and column name

select table_name,column_name from information_schema.columns
where column_name like '%breakfast%'

How can I find non-ASCII characters in MySQL?

MySQL provides comprehensive character set management that can help with this kind of problem.

SELECT whatever
  FROM tableName 
 WHERE columnToCheck <> CONVERT(columnToCheck USING ASCII)

The CONVERT(col USING charset) function turns the unconvertable characters into replacement characters. Then, the converted and unconverted text will be unequal.

See this for more discussion. https://dev.mysql.com/doc/refman/8.0/en/charset-repertoire.html

You can use any character set name you wish in place of ASCII. For example, if you want to find out which characters won't render correctly in code page 1257 (Lithuanian, Latvian, Estonian) use CONVERT(columnToCheck USING cp1257)

Improve subplot size/spacing with many subplots in matplotlib

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout

enter image description here


With Tight Layout enter image description here

stop service in android

onDestroyed()

is wrong name for

onDestroy()  

Did you make a mistake only in this question or in your code too?

How to parseInt in Angular.js

<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

Parcelable encountered IOException writing serializable object getactivity()

For me this was resolved by making the variable withing the class transient.

Code before:

public class UserLocation implements Serializable {
   public Location lastKnownLocation;
   public UserLocation() {}
}

code after

public class UserLocation implements Serializable {
    public transient Location lastKnownLocation;
    public UserLocation() {}
}   

How to convert a DataTable to a string in C#?

very vague ....

id bung it into a dataset simply so that i can output it easily as xml ....

failing that why not iterate through its row and column collections and output them?

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, the command is simpler tesseract imagename outputbase digits according to the FAQ. But it doesn't work for me very well.

I turn to try different psm options and find -psm 6 works best for my case.

man tesseract for details.

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

Squash my last X commits together using Git

If you're using GitUp, select the commit you want to merge with its parent and press S. You have to do it once for each commit, but it's much more straightforward than coming up with the correct command line incantation. Especially if it's something you only do once in a while.

How to explicitly obtain post data in Spring MVC?

If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
 //do stuff with valueOne variable here
}

How to parse JSON with VBA without external libraries?

There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.

Let's address the second concern first. You were on the right track. First, replace all instances of sentences with jsentences If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[ as the search string. You can use the VBA Replace method to do this.

Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:

'first, declare the variables you need:
Dim jsent as Variant

'Get arr all setup, then
For Each jsent in arr.jsentences
  MsgBox(jsent.orig)
Next

How to set delay in android?

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

How to create a circle icon button in Flutter?

RawMaterialButton(
  onPressed: () {},
  constraints: BoxConstraints(),
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

note down constraints: BoxConstraints(), it's for not allowing padding in left.

Happy fluttering!!

Convert Unix timestamp into human readable date using MySQL

You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.

Case-insensitive string comparison in C++

I've had good experience using the International Components for Unicode libraries - they're extremely powerful, and provide methods for conversion, locale support, date and time rendering, case mapping (which you don't seem to want), and collation, which includes case- and accent-insensitive comparison (and more). I've only used the C++ version of the libraries, but they appear to have a Java version as well.

Methods exist to perform normalized compares as referred to by @Coincoin, and can even account for locale - for example (and this a sorting example, not strictly equality), traditionally in Spanish (in Spain), the letter combination "ll" sorts between "l" and "m", so "lz" < "ll" < "ma".

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Taking DWins example.

What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".

E.g.

clab = 1.5
cmain = 2
caxis = 1.2

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=clab,    
           col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis) 

You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:

which you then call with setwd("") source("plotcolours.r")

in a file say called plotcolours.r you then store all the e.g. colour or size variables

clab = 1.5
cmain = 2
caxis = 1.2 

for colours could use

darkred<-rgb(113,28,47,maxColorValue=255)

as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.

plot(1,1,col=darkred) 

Gradle: Could not determine java version from '11.0.2'

In my case the JAVA_HOME variable was set to /usr/lib/jvm/jdk-11.0.2/. It was sufficient to unset the variable like this:

$ export JAVA_HOME=

How do you implement a class in C?

I will give a simple example of how OOP should be done in C. I realise this thead is from 2009 but would like to add this anyway.

/// Object.h
typedef struct Object {
    uuid_t uuid;
} Object;

int Object_init(Object *self);
uuid_t Object_get_uuid(Object *self);
int Object_clean(Object *self);

/// Person.h
typedef struct Person {
    Object obj;
    char *name;
} Person;

int Person_init(Person *self, char *name);
int Person_greet(Person *self);
int Person_clean(Person *self);

/// Object.c
#include "object.h"

int Object_init(Object *self)
{
    self->uuid = uuid_new();

    return 0;
}
uuid_t Object_get_uuid(Object *self)
{ // Don't actually create getters in C...
    return self->uuid;
}
int Object_clean(Object *self)
{
    uuid_free(self->uuid);

    return 0;
}

/// Person.c
#include "person.h"

int Person_init(Person *self, char *name)
{
    Object_init(&self->obj); // Or just Object_init(&self);
    self->name = strdup(name);

    return 0;
}
int Person_greet(Person *self)
{
    printf("Hello, %s", self->name);

    return 0;
}
int Person_clean(Person *self)
{
    free(self->name);
    Object_clean(self);

    return 0;
}

/// main.c
int main(void)
{
    Person p;

    Person_init(&p, "John");
    Person_greet(&p);
    Object_get_uuid(&p); // Inherited function
    Person_clean(&p);

    return 0;
}

The basic concept involves placing the 'inherited class' at the top of the struct. This way, accessing the first 4 bytes in the struct also accesses the first 4 bytes in the 'inherited class' (Asuming non-crazy optimalisations). Now, when the pointer of the struct is cast to the 'inherited class', the 'inherited class' can access the 'inherited values' in the same way it would access it's members normally.

This and some naming conventions for constructors, destructors, allocation and deallocarion functions (I recommend init, clean, new, free) will get you a long way.

As for Virtual functions, use function pointers in the struct, possibly with Class_func(...); wrapper too. As for (simple) templates, add a size_t parameter to determine size, require a void* pointer, or require a 'class' type with just the functionality you care about. (e.g. int GetUUID(Object *self); GetUUID(&p);)

unix - count of columns in file

select any row in the file (in the example below, it's the 2nd row) and count the number of columns, where the delimiter is a space:

sed -n 2p text_file.dat | tr ' ' '\n' | wc -l

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.

To get the hour, do (hour % 12) || 12.

This should do it:

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

http://jsfiddle.net/Skwt7/4/

That assumes that AM times are formatted as, eg, 08:00:00. If they are formatted without the leading zero, you would have to test the position of the first colon:

var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;

http://jsfiddle.net/Skwt7/3/

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

If @papigee does solution doesn't work, maybe you don't have the permissions.

I tried @papigee solution but does't work without sudo.

I did :

sudo docker exec -it <container id or name> /bin/sh

How to remove newlines from beginning and end of a string?

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0

Python setup.py develop vs install

From the documentation. The develop will not install the package but it will create a .egg-link in the deployment directory back to the project source code directory.

So it's like installing but instead of copying to the site-packages it adds a symbolic link (the .egg-link acts as a multiplatform symbolic link).

That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop. If you are just installing someone else's package you should use install

How to get a file directory path from file path?

On a related note, if you only have the filename or relative path, dirname on its own won't help. For me, the answer ended up being readlink.

fname='txtfile'    
echo $(dirname "$fname")                # output: .
echo $(readlink -f "$fname")            # output: /home/me/work/txtfile

You can then combine the two to get just the directory.

echo $(dirname $(readlink -f "$fname")) # output: /home/me/work

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

How to specify a local file within html using the file: scheme?

the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.

if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.

Declare a const array

As an alternative, to get around the elements-can-be-modified issue with a readonly array, you can use a static property instead. (The individual elements can still be changed, but these changes will only be made on the local copy of the array.)

public static string[] Titles 
{
    get
    {
        return new string[] { "German", "Spanish", "Corrects", "Wrongs"};
    }
}

Of course, this will not be particularly efficient as a new string array is created each time.

How to index characters in a Golang string?

The general solution to interpreting a char as a string is string("HELLO"[1]).

Rich's solution also works, of course.

C# Remove object from list of objects

You're checking i's UniqueID while i is actually an integer. You should do something like that, if you want to stay with a for loop.

for (int i = 0; i < ChunkList.Capacity; i++)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.Remove(i);
    }
}

You can, and should, however, use linq:

ChunkList.Remove(x => x.UniqueID == ChunkID);

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

How can we programmatically detect which iOS version is device running on?

[[[UIDevice currentDevice] systemVersion] floatValue]

How to prettyprint a JSON file?

You could try pprintjson.


Installation

$ pip3 install pprintjson

Usage

Pretty print JSON from a file using the pprintjson CLI.

$ pprintjson "./path/to/file.json"

Pretty print JSON from a stdin using the pprintjson CLI.

$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson

Pretty print JSON from a string using the pprintjson CLI.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'

Pretty print JSON from a string with an indent of 1.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1

Pretty print JSON from a string and save output to a file output.json.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json

Output

enter image description here

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

Here's a simple way:

=NUMBERVALUE( CONCAT(5.66,"%") )

Just concatenate a % symbol after the number. By itself, this output would be text, so we also tuck the CONCAT function inside the NUMBERVALUE function.

p.s., in old excel, you might need to type the full word "CONCATENATE"

"getaddrinfo failed", what does that mean?

The problem in my case was that I needed to add environment variables for http_proxy and https_proxy.

E.g.,

http_proxy=http://your_proxy:your_port
https_proxy=https://your_proxy:your_port

To set these environment variables in Windows, see the answers to this question.

Cannot push to Git repository on Bitbucket

For errors:

[error] repository access denied. access via a deployment key is read-only. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.

[error] fatal: Could not read from remote repository.

[error] fatal: Unable to find remote helper for 'https'

I solved following this steps:

First install this dependencies:

$ yum install expat expat-devel openssl openssl-devel

Then remove git:

$ yum remove git git-all

Now Build and install Git on last version, in this case:

$ wget https://github.com/git/git/archive/v2.13.0.tar.gz
$ tar zxf v.2.13.0.tar.gz
$ cd git-2.13.0/

Then for the configure:

$ make configure
$ ./configure --with-expat --with-openssl

And finally install like this:

$ make 
$ make install install-doc install-html install-info

that´s it, now configure your repo with https:

$ git remote add origin https://github.com/*user*/*repo*.git
# Verify new remote
$ git remote -v

if you have configured an ssh key in your remote server you have to delete it.

How to determine the encoding of text?

# Function: OpenRead(file)

# A text file can be encoded using:
#   (1) The default operating system code page, Or
#   (2) utf8 with a BOM header
#
#  If a text file is encoded with utf8, and does not have a BOM header,
#  the user can manually add a BOM header to the text file
#  using a text editor such as notepad++, and rerun the python script,
#  otherwise the file is read as a codepage file with the 
#  invalid codepage characters removed

import sys
if int(sys.version[0]) != 3:
    print('Aborted: Python 3.x required')
    sys.exit(1)

def bomType(file):
    """
    returns file encoding string for open() function

    EXAMPLE:
        bom = bomtype(file)
        open(file, encoding=bom, errors='ignore')
    """

    f = open(file, 'rb')
    b = f.read(4)
    f.close()

    if (b[0:3] == b'\xef\xbb\xbf'):
        return "utf8"

    # Python automatically detects endianess if utf-16 bom is present
    # write endianess generally determined by endianess of CPU
    if ((b[0:2] == b'\xfe\xff') or (b[0:2] == b'\xff\xfe')):
        return "utf16"

    if ((b[0:5] == b'\xfe\xff\x00\x00') 
              or (b[0:5] == b'\x00\x00\xff\xfe')):
        return "utf32"

    # If BOM is not provided, then assume its the codepage
    #     used by your operating system
    return "cp1252"
    # For the United States its: cp1252


def OpenRead(file):
    bom = bomType(file)
    return open(file, 'r', encoding=bom, errors='ignore')


#######################
# Testing it
#######################
fout = open("myfile1.txt", "w", encoding="cp1252")
fout.write("* hi there (cp1252)")
fout.close()

fout = open("myfile2.txt", "w", encoding="utf8")
fout.write("\u2022 hi there (utf8)")
fout.close()

# this case is still treated like codepage cp1252
#   (User responsible for making sure that all utf8 files
#   have a BOM header)
fout = open("badboy.txt", "wb")
fout.write(b"hi there.  barf(\x81\x8D\x90\x9D)")
fout.close()

# Read Example file with Bom Detection
fin = OpenRead("myfile1.txt")
L = fin.readline()
print(L)
fin.close()

# Read Example file with Bom Detection
fin = OpenRead("myfile2.txt")
L =fin.readline() 
print(L) #requires QtConsole to view, Cmd.exe is cp1252
fin.close()

# Read CP1252 with a few undefined chars without barfing
fin = OpenRead("badboy.txt")
L =fin.readline() 
print(L)
fin.close()

# Check that bad characters are still in badboy codepage file
fin = open("badboy.txt", "rb")
fin.read(20)
fin.close()

Timeout jQuery effects

I just figured it out below:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

I will keep the post for other users!

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

I have faced the same issue. And this save my life: https://gist.github.com/jtdp/5443498

git diff -p -R --no-color \
| grep -E "^(diff|(old|new) mode)" --color=never  \
| git apply`

How do I remove javascript validation from my eclipse project?

Another reason could be that you acidentically added a Javascript nature to your project unintentionally (i just did this by accident) which enables javascript error checking.

removing this ....javascriptnature from your project fixes that.

(this is ofcourse only if you dont want eclipse to realise you have any JS)

Downloading a file from spring controllers

What I can quickly think of is, generate the pdf and store it in webapp/downloads/< RANDOM-FILENAME>.pdf from the code and send a forward to this file using HttpServletRequest

request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);

or if you can configure your view resolver something like,

  <bean id="pdfViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
              value="org.springframework.web.servlet.view.JstlView" />
    <property name="order" value=”2"/>
    <property name="prefix" value="/downloads/" />
    <property name="suffix" value=".pdf" />
  </bean>

then just return

return "RANDOM-FILENAME";

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

Fling gesture detection on grid layout

Also as a minor enhancement.

The main reason for the try/catch block is that e1 could be null for the initial movement. in addition to the try/catch, include a test for null and return. similar to the following

if (e1 == null || e2 == null) return false;
try {
...
} catch (Exception e) {}
return false;

What is attr_accessor in Ruby?

Attributes and accessor methods

Attributes are class components that can be accessed from outside the object. They are known as properties in many other programming languages. Their values are accessible by using the "dot notation", as in object_name.attribute_name. Unlike Python and a few other languages, Ruby does not allow instance variables to be accessed directly from outside the object.

class Car
  def initialize
    @wheels = 4  # This is an instance variable
  end
end

c = Car.new
c.wheels     # Output: NoMethodError: undefined method `wheels' for #<Car:0x00000000d43500>

In the above example, c is an instance (object) of the Car class. We tried unsuccessfully to read the value of the wheels instance variable from outside the object. What happened is that Ruby attempted to call a method named wheels within the c object, but no such method was defined. In short, object_name.attribute_name tries to call a method named attribute_name within the object. To access the value of the wheels variable from the outside, we need to implement an instance method by that name, which will return the value of that variable when called. That's called an accessor method. In the general programming context, the usual way to access an instance variable from outside the object is to implement accessor methods, also known as getter and setter methods. A getter allows the value of a variable defined within a class to be read from the outside and a setter allows it to be written from the outside.

In the following example, we have added getter and setter methods to the Car class to access the wheels variable from outside the object. This is not the "Ruby way" of defining getters and setters; it serves only to illustrate what getter and setter methods do.

class Car
  def wheels  # getter method
    @wheels
  end

  def wheels=(val)  # setter method
    @wheels = val
  end
end

f = Car.new
f.wheels = 4  # The setter method was invoked
f.wheels  # The getter method was invoked
# Output: => 4

The above example works and similar code is commonly used to create getter and setter methods in other languages. However, Ruby provides a simpler way to do this: three built-in methods called attr_reader, attr_writer and attr_acessor. The attr_reader method makes an instance variable readable from the outside, attr_writer makes it writeable, and attr_acessor makes it readable and writeable.

The above example can be rewritten like this.

class Car
  attr_accessor :wheels
end

f = Car.new
f.wheels = 4
f.wheels  # Output: => 4

In the above example, the wheels attribute will be readable and writable from outside the object. If instead of attr_accessor, we used attr_reader, it would be read-only. If we used attr_writer, it would be write-only. Those three methods are not getters and setters in themselves but, when called, they create getter and setter methods for us. They are methods that dynamically (programmatically) generate other methods; that's called metaprogramming.

The first (longer) example, which does not employ Ruby's built-in methods, should only be used when additional code is required in the getter and setter methods. For instance, a setter method may need to validate data or do some calculation before assigning a value to an instance variable.

It is possible to access (read and write) instance variables from outside the object, by using the instance_variable_get and instance_variable_set built-in methods. However, this is rarely justifiable and usually a bad idea, as bypassing encapsulation tends to wreak all sorts of havoc.

Override back button to act like home button

Working example..

Make sure don't call super.onBackPressed();

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background

Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed

Indent multiple lines quickly in vi

As well as the offered solutions, I like to do things a paragraph at a time with >}

Remove a specific string from an array of string

import java.util.*;

class Array {
    public static void main(String args[]) {
        ArrayList al = new ArrayList();
        al.add("google");
        al.add("microsoft");
        al.add("apple");
        System.out.println(al);
        //i only remove the apple//
        al.remove(2);
        System.out.println(al);
    }
}

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Specify: # encoding= utf-8 at the top of your Python File, It should fix the issue

How to export and import environment variables in windows?

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

React - uncaught TypeError: Cannot read property 'setState' of undefined

You can also use:

<button onClick={()=>this.delta()}>+</button>

Or:

<button onClick={event=>this.delta(event)}>+</button>

If you are passing some params..

Make A List Item Clickable (HTML/CSS)

Ditch the <a href="...">. Put the onclick (all lowercase) handler on the <li> tag itself.

Getting output of system() calls in Ruby

The straightforward way to do this correctly and securely is to use Open3.capture2(), Open3.capture2e(), or Open3.capture3().

Using ruby's backticks and its %x alias are NOT SECURE UNDER ANY CIRCUMSTANCES if used with untrusted data. It is DANGEROUS, plain and simple:

untrusted = "; date; echo"
out = `echo #{untrusted}`                              # BAD

untrusted = '"; date; echo"'
out = `echo "#{untrusted}"`                            # BAD

untrusted = "'; date; echo'"
out = `echo '#{untrusted}'`                            # BAD

The system function, in contrast, escapes arguments properly if used correctly:

ret = system "echo #{untrusted}"                       # BAD
ret = system 'echo', untrusted                         # good

Trouble is, it returns the exit code instead of the output, and capturing the latter is convoluted and messy.

The best answer in this thread so far mentions Open3, but not the functions that are best suited for the task. Open3.capture2, capture2e and capture3 work like system, but returns two or three arguments:

out, err, st = Open3.capture3("echo #{untrusted}")     # BAD
out, err, st = Open3.capture3('echo', untrusted)       # good
out_err, st  = Open3.capture2e('echo', untrusted)      # good
out, st      = Open3.capture2('echo', untrusted)       # good
p st.exitstatus

Another mentions IO.popen(). The syntax can be clumsy in the sense that it wants an array as input, but it works too:

out = IO.popen(['echo', untrusted]).read               # good

For convenience, you can wrap Open3.capture3() in a function, e.g.:

#
# Returns stdout on success, false on failure, nil on error
#
def syscall(*cmd)
  begin
    stdout, stderr, status = Open3.capture3(*cmd)
    status.success? && stdout.slice!(0..-(1 + $/.size)) # strip trailing eol
  rescue
  end
end

Example:

p system('foo')
p syscall('foo')
p system('which', 'foo')
p syscall('which', 'foo')
p system('which', 'which')
p syscall('which', 'which')

Yields the following:

nil
nil
false
false
/usr/bin/which         <— stdout from system('which', 'which')
true                   <- p system('which', 'which')
"/usr/bin/which"       <- p syscall('which', 'which')

How to get the current user's Active Directory details in C#

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}

[email protected] is the UserPrincipalName, but it isn't a required field.

Parse JSON String into a Particular Object Prototype in JavaScript

While, this is not technically what you want, if you know before hand the type of object you want to handle you can use the call/apply methods of the prototype of your known object.

you can change this

alert(fooJSON.test() ); //Prints 12

to this

alert(Foo.prototype.test.call(fooJSON); //Prints 12

How to use local docker images with Minikube?

you can either reuse the docker shell, with eval $(minikube docker-env), alternatively, you can leverage on docker save | docker load across the shells.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

How to add screenshot to READMEs in github repository?

First, create a directory(folder) in the root of your local repo that will contain the screenshots you want added. Let’s call the name of this directory screenshots. Place the images (JPEG, PNG, GIF,` etc) you want to add into this directory.

Android Studio Workspace Screenshot

Secondly, you need to add a link to each image into your README. So, if I have images named 1_ArtistsActivity.png and 2_AlbumsActivity.png in my screenshots directory, I will add their links like so:

 <img src="screenshots/1_ArtistsActivity.png" height="400" alt="Screenshot"/> <img src=“screenshots/2_AlbumsActivity.png" height="400" alt="Screenshot"/>

If you want each screenshot on a separate line, write their links on separate lines. However, it’s better if you write all the links in one line, separated by space only. It might actually not look too good but by doing so GitHub automatically arranges them for you.

Finally, commit your changes and push it!

Skipping Iterations in Python

I think you're looking for continue

JSON post to Spring Controller

You need to include the getters and setters for all the fields that have been defined in the model Test class --

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Passing argument to alias in bash

to use parameters in aliases, i use this method:

alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'

its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:

alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'

so..

you could, if you need to have that variable in there

alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'

of course...

alias mongodb='./path/to/mongodb/'

would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).

I hope that helps you out :)

Possible reason for NGINX 499 error codes

HTTP 499 in Nginx means that the client closed the connection before the server answered the request. In my experience is usually caused by client side timeout. As I know it's an Nginx specific error code.

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

Navigation bar show/hide

One way could be by unchecking Bar Visibility "Shows Navigation Bar" In Attribute Inspector.Hope this help someone.

enter image description here

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

What is the difference between declarative and imperative paradigm in programming?

I just wonder why no one has mentioned Attribute classes as a declarative programming tool in C#. The popular answer of this page has just talked about LINQ as a declarative programming tool.

According to Wikipedia

Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions, logic programming, functional programming, and configuration management systems.

So LINQ, as a functional syntax, is definitely a declarative method, but Attribute classes in C#, as a configuration tool, are declarative too. Here is a good starting point to read more about it: Quick Overview of C# Attribute Programming

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

What does Java option -Xmx stand for?

see here: Java Tool Doc, it says,

-Xmxn
Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. The upper limit for this value will be approximately 4000m on Solaris 7 and Solaris 8 SPARC platforms and 2000m on Solaris 2.6 and x86 platforms, minus overhead amounts. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

So, in simple words, you are setting Java heap memory to a maximum of 1024 MB from the available memory, not more.

Notice there is NO SPACE between -Xmx and 1024m

It does not matter if you use uppercase or lowercase. For example: "-Xmx10G" and "-Xmx10g" do the exact same thing.

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

Live search through table rows

Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.

Here is what i did:

$('input[name="search"]').on('keyup', function() {

        var input, filter, tr, td, i;

        input  = $(this);
        filter = input.val().toUpperCase();
        tr     = $("table tr");

        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    })

Hope it helps somebody.

How to find char in string and get all the indexes?

This is because str.index(ch) will return the index where ch occurs the first time. Try:

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

This will return a list of all indexes you need.

P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing [] to ().

jQuery click event not working in mobile browsers

With this solution, you probably can resolve all mobile clicks problems. Use only "click" function, but add z-index:99 to the element in css:

_x000D_
_x000D_
  $("#test").on('click', function(){_x000D_
    alert("CLICKED!")_x000D_
  });
_x000D_
#test{   _x000D_
  z-index:99;_x000D_
  cursor:pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="test">CLICK ME</div>
_x000D_
_x000D_
_x000D_

Credit:https://foundation.zurb.com/forum/posts/3258-buttons-not-clickable-on-iphone

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had this problem because i was adding bundle and certificate in wrong order so maybe this could help someone else.

Before (which is wrong) :

cat ca_bundle.crt certificate.crt > bundle_chained.crt

After (which is right)

cat certificate.crt ca_bundle.crt > bundle_chained.crt

And Please don't forget to update the appropriate conf (ssl_certificate must now point to the chained crt) as

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     bundle_chained.crt;
    ssl_certificate_key www.example.com.key;
    ...
}

From the nginx manpage:

If the server certificate and the bundle have been concatenated in the wrong order, nginx will fail to start and will display the error message:

SSL_CTX_use_PrivateKey_file(" ... /www.example.com.key") failed
   (SSL: error:0B080074:x509 certificate routines:
    X509_check_private_key:key values mismatch)

javax.persistence.NoResultException: No entity found for query

You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?

if (query.list().size() == 1) 

Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

How to get a list column names and datatypes of a table in PostgreSQL?

Open psql command line and type :

\d+ table_name

How do I programmatically click on an element in JavaScript?

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."

So you should use this method instead:

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

and fire it on an element like this:

element.dispatchEvent(clickEvent);

as shown here.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Allow Apache Through the Firewall

Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp

And reload the firewall:

sudo firewall-cmd --reload

jQuery - What are differences between $(document).ready and $(window).load?

The ready event is always execute at the only html page is loaded to the browser and the functions are executed.... But the load event is executed at the time of all the page contents are loaded to the browser for the page..... we can use $ or jQuery when we use the noconflict() method in jquery scripts...

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

Easiest way to convert a List to a Set in Java

For Java 8 it's very easy:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

In case MySQL Server is up but you are still getting the error:

For anyone who still have this issue, I followed awesome tutorial http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-9-mavericks/

However i still got #1045 error. What really did the trick was to change localhost to 127.0.0.1 at your config.inc.php. Why was it failing if locahost points to 127.0.0.1? I don't know. But it worked.

===== EDIT =====

Long story short, it is because of permissions in mysql. It may be set to accept connections from 127.0.0.1 but not from localhost.

The actual answer for why this isn't responding is here: https://serverfault.com/a/297310

When should I create a destructor?

UPDATE: This question was the subject of my blog in May of 2015. Thanks for the great question! See the blog for a long list of falsehoods that people commonly believe about finalization.

When should I manually create a destructor?

Almost never.

Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually. (Maybe.)

If you make a destructor be extremely careful and understand how the garbage collector works. Destructors are really weird:

  • They don't run on your thread; they run on their own thread. Don't cause deadlocks!
  • An unhandled exception thrown from a destructor is bad news. It's on its own thread; who is going to catch it?
  • A destructor may be called on an object after the constructor starts but before the constructor finishes. A properly written destructor will not rely on invariants established in the constructor.
  • A destructor can "resurrect" an object, making a dead object alive again. That's really weird. Don't do it.
  • A destructor might never run; you can't rely on the object ever being scheduled for finalization. It probably will be, but that's not a guarantee.

Almost nothing that is normally true is true in a destructor. Be really, really careful. Writing a correct destructor is very difficult.

When have you needed to create a destructor?

When testing the part of the compiler that handles destructors. I've never needed to do so in production code. I seldom write objects that manipulate unmanaged resources.

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

It seems that the problem with IE comes when you try and access the iframe via the document.frames object - if you store a reference to the created iframe in a variable then you can access the injected iframe via the variable (my_iframe in the code below).

I've gotten this to work in IE6/7/8

var my_iframe;
var iframeId = "my_iframe_name"
if (navigator.userAgent.indexOf('MSIE') !== -1) {
  // IE wants the name attribute of the iframe set
  my_iframe = document.createElement('<iframe name="' + iframeId + '">');
} else {
  my_iframe = document.createElement('iframe');
}

iframe.setAttribute("src", "javascript:void(0);");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameBorder", "0");
iframe.setAttribute("name", iframeId);

var is = iframe.style;
is.border = is.width = is.height = "0px";

if (document.body) {
  document.body.appendChild(my_iframe);
} else {
  document.appendChild(my_iframe);
}

How to create a date object from string in javascript

Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.

As it states in the topic of the Date object about the argument variant you use:

new Date(year, month, day [, hour, minute, second, millisecond ])

And about the months parameter:

month Integer value representing the month, beginning with 0 for January to 11 for December.

Clearly, then, you should use the month number 10 for November.

P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How to set user environment variables in Windows Server 2008 R2 as a normal user?

In command line prompt:

set __COMPAT_LAYER=RUNASINVOKER
SystemPropertiesAdvanced.exe

Now you can set user environment variables.

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

How to replace ${} placeholders in a text file?

file.tpl:

The following bash function should only replace ${var1} syntax and ignore 
other shell special chars such as `backticks` or $var2 or "double quotes". 
If I have missed anything - let me know.

script.sh:

template(){
    # usage: template file.tpl
    while read -r line ; do
            line=${line//\"/\\\"}
            line=${line//\`/\\\`}
            line=${line//\$/\\\$}
            line=${line//\\\${/\${}
            eval "echo \"$line\""; 
    done < ${1}
}

var1="*replaced*"
var2="*not replaced*"

template file.tpl > result.txt

PHP header() redirect with POST variables

// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

Converting Date and Time To Unix Timestamp

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

Fastest Way of Inserting in Entity Framework

The fastest way would be using bulk insert extension, which I developed

note: this is a commercial product, not free of charge

It uses SqlBulkCopy and custom datareader to get max performance. As a result it is over 20 times faster than using regular insert or AddRange EntityFramework.BulkInsert vs EF AddRange

usage is extremely simple

context.BulkInsert(hugeAmountOfEntities);

JSON.stringify output to div in pretty print way

use style white-space: pre the <pre> tag also modifies the text format which may be undesirable.

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

Version vs build in Xcode

The script to autoincrement the build number in the answer above didn't work for me if the build number is a floating point value, so I modified it a little:

#!/bin/bash    
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=`echo $buildNumber +1|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

Where does mysql store data?

as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir

Design Android EditText to show error message as described by google

Call myTextInputLayout.setError() instead of myEditText.setError().

These container and containment have double functionality on setting errors. Functionality you need is container's one. But you could require minimal version of 23 for that.

HttpClient.GetAsync(...) never returns when using await/async

In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.

public async Task<Stuff> GetStuff(string id)
{
    string path = $"/api/v2/stuff/{id}";
    try
    {
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            string json = await response.Content.ReadAsStringAsync();
            return JsonUtility.FromJson<Stuff>(json);
        }
        else
        {
            Debug.LogError($"Could not retrieve stuff {id}");
        }
    }
    catch (Exception exception)
    {
        Debug.LogError($"Exception when retrieving stuff {exception}");
    }
    return null;
}

How to get logged-in user's name in Access vba?

Public Declare Function GetUserName Lib "advapi32.dll" 
    Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

....

Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String

strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))

Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

How to remove part of a string?

When you need rule based matching, you need to use regex

$string = "REGISTER 11223344 here";
preg_match("/(\d+)/", $string, $match);
$number = $match[1];

That will match the first set of numbers, so if you need to be more specific try:

$string = "REGISTER 11223344 here";
preg_match("/REGISTER (\d+) here/", $string, $match);
$number = $match[1];

How can I use a reportviewer control in an asp.net mvc 3 razor view?

You will not only have to use an asp.net page but

If using the Entity Framework or LinqToSql (if using partial classes) move the data into a separate project, the report designer cannot see the classes.

Move the reports to another project/dll, VS10 has bugs were asp.net projects cannot see object datasources in web apps. Then stream the reports from the dll into your mvc projects aspx page.

This applies for mvc and webform projects. Using sql reports in the local mode is not a pleasent development experience. Also watch your webserver memory if exporting large reports. The reportviewer/export is very poorly designed.

What is the difference between JavaScript and ECMAScript?

ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called "dialects". Wikipedia sheds some light on this.

Open multiple Eclipse workspaces on the Mac

This seems to be the supported native method in OS X:

cd /Applications/eclipse/

open -n Eclipse.app

Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse, might get one GateKeeper stopping access:

"eclipse" can't be opened because it is from an unidentified developer.

Your security preferences allow installation of only apps from the Mac App Store and identified developers.

Even removing the extended attribute com.apple.quarantine does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:

"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?

add onclick function to a submit button

if you need to do something before submitting data, you could use form's onsubmit.

<form method=post onsubmit="return doSomething()">
  <input type=text name=text1>
  <input type=submit>
</form>

Watermark / hint text / placeholder TextBox

you can use GetFocus() and LostFocus() events to do this

here is the example:

    private void txtData1_GetFocus(object sender, RoutedEventArgs e)
    {
        if (txtData1.Text == "TextBox1abc")
        {
            txtData1.Text = string.Empty;
        }
    }

    private void txtData1_LostFocus(object sender, RoutedEventArgs e)
    {
        if (txtData1.Text == string.Empty)
        {
            txtData1.Text = "TextBox1abc";
        }
    }

How do you Programmatically Download a Webpage in Java

Well, you could go with the built-in libraries such as URL and URLConnection, but they don't give very much control.

Personally I'd go with the Apache HTTPClient library.
Edit: HTTPClient has been set to end of life by Apache. The replacement is: HTTP Components

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Sql Server trigger insert values from new row into another table

When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.

Moving Git repository content to another repository preserving history

As per @Dan-Cohn answer Mirror-push is your friend here. This is my go to for migrating repos:

Mirroring a repository

1.Open Git Bash.

2.Create a bare clone of the repository.

$ git clone --bare https://github.com/exampleuser/old-repository.git

3.Mirror-push to the new repository.

$ cd old-repository.git
$ git push --mirror https://github.com/exampleuser/new-repository.git

4.Remove the temporary local repository you created in step 1.

$ cd ..
$ rm -rf old-repository.git

Reference and Credit: https://help.github.com/en/articles/duplicating-a-repository

Adding an external directory to Tomcat classpath

In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see

set CLASSPATH=%JAVA_HOME%\lib\tools.jar

then in catalina.bat, it's used like so

%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% 
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" 
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" 
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat

set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar

How does true/false work in PHP?

think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.

other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.

PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.

Don't understand why UnboundLocalError occurs (closure)

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword).

A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.

In your case you are trying to treat counter as a local variable rather than a bound value. Note that this code, which binds the value of x assigned in the enclosing environment, works fine:

>>> x = 1

>>> def f():
>>>  return x

>>> f()
1

How do I add to the Windows PATH variable using setx? Having weird problems

Steps: 1. Open a command prompt with administrator's rights.

Steps: 2. Run the command: setx /M PATH "path\to;%PATH%"

[Note: Be sure to alter the command so that path\to reflects the folder path from your root.]

Example : setx /M PATH "C:\Program Files;%PATH%"

Git: How to remove remote origin from Git repo

Instead of removing and re-adding, you can do this:

git remote set-url origin git://new.url.here

See this question: How to change the URI (URL) for a remote Git repository?

To remove remote use this:

git remote remove origin

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

How to read and write excel file

For reading a xlsx file we can use Apache POI libs Try this:

public static void readXLSXFile() throws IOException
    {
        InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
        XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);

        XSSFWorkbook test = new XSSFWorkbook(); 

        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row; 
        XSSFCell cell;

        Iterator rows = sheet.rowIterator();

        while (rows.hasNext())
        {
            row=(XSSFRow) rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext())
            {
                cell=(XSSFCell) cells.next();

                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                {
                    System.out.print(cell.getStringCellValue()+" ");
                }
                else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                {
                    System.out.print(cell.getNumericCellValue()+" ");
                }
                else
                {
                    //U Can Handel Boolean, Formula, Errors
                }
            }
            System.out.println();
        }

    }

ERROR 1044 (42000): Access denied for 'root' With All Privileges

First, Identify the user you are logged in as:

 select user();
 select current_user();

The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost in mysql.

Grant_priv to root@localhost. Here is how you can check.

mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host      | user             | password                                  | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root             | ***************************************** | N          | Y          |
| localhost | debian-sys-maint | ***************************************** | Y          | Y          |
| localhost | staging          | ***************************************** | N          | N          |
+-----------+------------------+-------------------------------------------+------------+------------+

You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';

I logged back in, it was fine.

libstdc++.so.6: cannot open shared object file: No such file or directory

/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk

jQuery and AJAX response header

UPDATE 2018 FOR JQUERY 3 AND LATER

I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:

//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
        var jqxhr = $.ajax({
            type: requestType,
            url: urlTo
        });
        //this section is executed when the server responds with no error 
        jqxhr.done(function(){

        });
        //this section is executed when the server responds with error
        jqxhr.fail(function(){

        })
        //this section is always executed
        jqxhr.always(function(){
            console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
        });
    }

How to add a list item to an existing unordered list?

Just to add to this thread - if you are moving an existing item you will need to use clone and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).

Example: $("#content ul").append($('.existing_li').clone(true));

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

ImportError: No module named scipy

This may be too basic (and perhaps assumable), but -

Fedora users can use:

sudo dnf install python-scipy

and then (For python3.x):

pip3 install scipy

or (For python2.7):

pip2 install scipy

JavaScript file upload size validation

If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.

Set the Ie 'Document Mode' to 'Standards':

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

Than, use the 'size' javascript method to get the uploaded file's size:

<script type="text/javascript">
    var uploadedFile = document.getElementById('imageUpload');
    var fileSize = uploadedFile.files[0].size;
    alert(fileSize); 
</script>

It works for me.

how to customize `show processlist` in mysql?

If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here

http://www.dbasquare.com/2012/03/28/how-to-work-with-a-long-process-list-in-mysql/

Isn't it exactly what you need?

prevent iphone default keyboard when focusing an <input>

So here is my solution (similar to John Vance's answer):

First go here and get a function to detect mobile browsers.

http://detectmobilebrowsers.com/

They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.

Your HTML page (pseudo code):

If Mobile Then
    <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
    <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />

JQuery:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max  
    });
});

This way you can still use native date selectors in mobile while still setting the min and max dates either way.

The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.

However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.

To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max,
        showOn: "both",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select date"
    });
});

Note: you will have to find a suitable image.

How do I install and use curl on Windows?

The simplest tutorial for setting up cURL on Windows is the Making cURL work on Windows 7. It only have 3 easy steps.

Store JSON object in data attribute in HTML jQuery

This code is working fine for me.

Encode data with btoa

let data_str = btoa(JSON.stringify(jsonData));
$("#target_id").attr('data-json', data_str);

And then decode it with atob

let tourData = $(this).data("json");
tourData = atob(tourData);

Image style height and width not taken in outlook mails

This worked for me:

src="{0}"  width=30 height=30 style="border:0;"

Nothing else has worked so far.

Broken references in Virtualenvs

A update version @Chris Wedgwood's answer for keeping site-packages (keeping packages installed)

cd ~/.virtualenv/name_of_broken_venv


mv lib/python2.7/site-packages ./    
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

This project references NuGet package(s) that are missing on this computer

I easily solve this problem by right clicking on my solution and then clicking on the Enable NuGet Package Restore option

(P.S: Ensure that you have the Nuget Install From Tools--> Extensions and Update--> Nuget Package Manager for Visual Studio 2013. If not install this extention first)

Hope it helps.

What does "var" mean in C#?

"var" means the compiler will determine the explicit type of the variable, based on usage. For example,

var myVar = new Connection();

would give you a variable of type Connection.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Converting a string to a date in DB2

Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...

DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))

I will still accept any answers that are better than this one!

Should I use px or rem value units in my CSS?

Half (but only half) snarky answer (the other half is bitter disdain of the reality of bureaucracy):

Use vh

Everything is always sized to browser window.

Always allow scroll down, but disable horizontal scroll.

Set body width to be a static 50vh, and never code css that floats or breaks out of the parent div. (If they try to mock up something that looks like it does, clever use of a background gif can throw them off track.) And style only using tables so everything is held rigidly into place as expected. Include a javascript function to undo any ctrl+/- activity the user may do.

Users will hate you, because the site doesn't flow differently based on what they're using (such as text being too small to read on phones). Your coworkers will hate you because nobody in their right mind does this and it will likely break their work (though not yours). Your programming professors will hate you because this is not a good idea. Your UX designer will hate you because it will reveal the corners they cut in designing UX mock-ups that they have to do in order to meet deadlines.

Nearly everyone will hate you, except the people who tell you to make things match the mock-up and to do so quickly. Those people, however (which generally include the project managers), will be ecstatic by your accuracy and fast turn around time. And everyone knows their opinion is the only one that matters to your paycheck.

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

CSS :not(:last-child):after selector

You can try this, I know is not the answers you are looking for but the concept is the same.

Where you are setting the styles for all the children and then removing it from the last child.

Code Snippet

li
  margin-right: 10px

  &:last-child
    margin-right: 0

Image

enter image description here

openpyxl - adjust column width size

I have a problem with merged_cells and autosize not work correctly, if you have the same problem, you can solve with the next code:

for col in worksheet.columns:
    max_length = 0
    column = col[0].column # Get the column name
    for cell in col:
        if cell.coordinate in worksheet.merged_cells: # not check merge_cells
            continue
        try: # Necessary to avoid error on empty cells
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.2
    worksheet.column_dimensions[column].width = adjusted_width

How to trim a string after a specific character in java

This is the simplest method you can do and reduce your efforts. just paste this function in your class and call it anywhere:

you can do this by creating a substring.

simple exampe is here:

_x000D_
_x000D_
public static String removeTillWord(String input, String word) {
    return input.substring(input.indexOf(word));
}

removeTillWord("Your String", "\");
_x000D_
_x000D_
_x000D_

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

How do I use method overloading in Python?

I write my answer in Python 2.7:

In Python, method overloading is not possible; if you really want access the same function with different features, I suggest you to go for method overriding.

class Base(): # Base class
    '''def add(self,a,b):
        s=a+b
        print s'''

    def add(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c

        sum =a+b+c
        print sum

class Derived(Base): # Derived class
    def add(self,a,b): # overriding method
        sum=a+b
        print sum



add_fun_1=Base() #instance creation for Base class
add_fun_2=Derived()#instance creation for Derived class

add_fun_1.add(4,2,5) # function with 3 arguments
add_fun_2.add(4,2)   # function with 2 arguments

What's the best way to limit text length of EditText in Android

For anyone else wondering how to achieve this, here is my extended EditText class EditTextNumeric.

.setMaxLength(int) - sets maximum number of digits

.setMaxValue(int) - limit maximum integer value

.setMin(int) - limit minimum integer value

.getValue() - get integer value

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;

public class EditTextNumeric extends EditText {
    protected int max_value = Integer.MAX_VALUE;
    protected int min_value = Integer.MIN_VALUE;

    // constructor
    public EditTextNumeric(Context context) {
        super(context);
        this.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    // checks whether the limits are set and corrects them if not within limits
    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        if (max_value != Integer.MAX_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) > max_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(max_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        if (min_value != Integer.MIN_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) < min_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(min_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        super.onTextChanged(text, start, before, after);
    }

    // set the max number of digits the user can enter
    public void setMaxLength(int length) {
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(length);
        this.setFilters(FilterArray);
    }

    // set the maximum integer value the user can enter.
    // if exeeded, input value will become equal to the set limit
    public void setMaxValue(int value) {
        max_value = value;
    }
    // set the minimum integer value the user can enter.
    // if entered value is inferior, input value will become equal to the set limit
    public void setMinValue(int value) {
        min_value = value;
    }

    // returns integer value or 0 if errorous value
    public int getValue() {
        try {
            return Integer.parseInt(this.getText().toString());
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}

Example usage:

final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);

All other methods and attributes that apply to EditText, of course work too.

Determine installed PowerShell version

You can look at the built in variable, $psversiontable. If it doesn't exist, you have V1. If it does exist, it will give you all the info you need.

1 >  $psversiontable

Name                           Value                                           
----                           -----                                           
CLRVersion                     2.0.50727.4927                                  
BuildVersion                   6.1.7600.16385                                  
PSVersion                      2.0                                             
WSManStackVersion              2.0                                             
PSCompatibleVersions           {1.0, 2.0}                                      
SerializationVersion           1.1.0.1                                         
PSRemotingProtocolVersion      2.1    

How can I get the current screen orientation?

if you want to override that onConfigurationChanged method and still want it to do the basic stuff then consider using super.onConfigyrationChanged() as the first statement in the overriden method.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().

How do I debug jquery AJAX calls?

2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

Anchor links in Angularjs?

$anchorScroll is indeed the answer to this, but there's a much better way to use it in more recent versions of Angular.

Now, $anchorScroll accepts the hash as an optional argument, so you don't have to change $location.hash at all. (documentation)

This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set $location.hash(id), before $anchorScroll could do its magic.

Here is how to use it... first, in the directive or controller:

$scope.scrollTo = function (id) {
  $anchorScroll(id);  
}

and then in the view:

<a href="" ng-click="scrollTo(id)">Text</a>

Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):

  .run(function ($anchorScroll) {
      //this will make anchorScroll scroll to the div minus 50px
      $anchorScroll.yOffset = 50;
  });

C Macro definition to determine big endian or little endian machine?

If you dump the preprocessor #defines

gcc -dM -E - < /dev/null
g++ -dM -E -x c++ - < /dev/null

You can usually find stuff that will help you. With compile time logic.

#define __LITTLE_ENDIAN__ 1
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

Various compilers may have different defines however.

/bin/sh: pushd: not found

here is a method to point

sh -> bash

run this command on terminal

sudo dpkg-reconfigure dash

After this you should see

ls -l /bin/sh

point to /bin/bash (and not to /bin/dash)

Reference

Javascript swap array elements

Flow

not inplace solution

let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);

_x000D_
_x000D_
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);

console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
_x000D_
_x000D_
_x000D_

and inplace solution

_x000D_
_x000D_
let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];

console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
_x000D_
_x000D_
_x000D_

In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)

ReactJS: "Uncaught SyntaxError: Unexpected token <"

If you have something like

Uncaught SyntaxError: embedded: Unexpected token

You probably missed a comma in a place like this:

  var CommentForm = React.createClass({
  getInitialState: function() {
      return {author: '', text: ''};

  }, // <---- DON'T FORGET THE COMMA

  render: function() {
      return (
      <form className="commentForm">
          <input type="text" placeholder="Nombre" />
          <input type="text" placeholder="Qué opina" />
          <input type="submit" value="Publicar" />
      </form>
      )
  }
  });

Check if a string contains an element from a list (of strings)

If speed is critical, you might want to look for the Aho-Corasick algorithm for sets of patterns.

It's a trie with failure links, that is, complexity is O(n+m+k), where n is the length of the input text, m the cumulative length of the patterns and k the number of matches. You just have to modify the algorithm to terminate after the first match is found.

How to get 'System.Web.Http, Version=5.2.3.0?

The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:

Install-Package Microsoft.AspNet.Mvc -Version 5.2.3

https://www.nuget.org/packages/microsoft.aspnet.mvc

Easy way to turn JavaScript array into comma-separated list?

Use the built-in Array.toString method

var arr = ['one', 'two', 'three'];
arr.toString();  // 'one,two,three'

MDN on Array.toString()

Sum of Numbers C++

mystycs, you are using the variable i to control your loop, however you are editing the value of i within the loop:

for (int i=0; i < positiveInteger; i++)
{
    i = startingNumber + 1;
    cout << i;
}

Try this instead:

int sum = 0;

for (int i=0; i < positiveInteger; i++)
{
    sum = sum + i;
    cout << sum << " " << i;
}

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

If you are dealing with a table and one of the dates happens to be null, you can code it like this:

  @{
     if (Model.SomeCollection[i].date_due == null)
       {
         <td><input type='date' id="@("dd" + i)" name="dd" /></td>
       }
       else
       {
         <td><input type='date' value="@Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="@("dd" + i)" name="dd" /></td>
       }
   }

How to embed images in email

As you are aware, everything passed as email message has to be textualized.

  • You must create an email with a multipart/mime message.
  • If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the <img /> tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"

--boundary-example
Content-Type: text/html; charset="US-ASCII"

... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">

--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64

R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...

--boundary-example--

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the <IMG> at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

Hope this helps.

spark submit add multiple jars in classpath

if you are using properties file you can add following line there:

spark.jars=jars/your_jar1.jar,...

assuming that

<your root from where you run spark-submit>
  |
  |-jars
      |-your_jar1.jar

Advantage of switch over if-else statement

Use switch.

In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.

In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

Making div content responsive

Not a lot to go on there, but I think what you're looking for is to flip the width and max-width values:

#container2 {
  width: 90%;
  max-width: 960px;
  /* etc, etc... */
}

That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

Rollback one specific migration in Laravel

If you look in your migrations table, then you’ll see each migration has a batch number. So when you roll back, it rolls back each migration that was part of the last batch.

If you only want to roll back the very last migration, then just increment the batch number by one. Then next time you run the rollback command, it’ll only roll back that one migration as it’s in a “batch” of its own.

Alternatively, from Laravel 5.3 onwards, you can just run:

php artisan migrate:rollback --step=1

That will rollback the last migration, no matter what its batch number is.

PHP: Call to undefined function: simplexml_load_string()

For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:

extension=php_xmlrpc.dll

Then simply install php7.0-xml:

sudo apt-get install php7.0-xml

And restart PHP:

sudo service php7.0-fpm restart

And restart Apache:

sudo service apache2 restart

If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).

How to make jQuery UI nav menu horizontal?

I just been for 3 days looking for a jquery UI and CSS solution, I merge some code I saw, fix a little, and finally (along the other codes) I could make it work!

http://jsfiddle.net/Moatilliatta/97m6ty1a/

<ul id="nav" class="testnav">
    <li><a class="clk" href="#">Item 1</a></li>
    <li><a class="clk" href="#">Item 2</a></li>
    <li><a class="clk" href="#">Item 3</a>
        <ul class="sub-menu">
            <li><a href="#">Item 3-1</a>
                <ul class="sub-menu">
                    <li><a href="#">Item 3-11</a></li>
                    <li><a href="#">Item 3-12</a>
                        <ul>
                            <li><a href="#">Item 3-111</a></li>                         
                            <li><a href="#">Item 3-112</a>
                                <ul>
                                    <li><a href="#">Item 3-1111</a></li>                            
                                    <li><a href="#">Item 3-1112</a></li>                            
                                    <li><a href="#">Item 3-1113</a>
                                        <ul>
                                            <li><a href="#">Item 3-11131</a></li>                           
                                            <li><a href="#">Item 3-11132</a></li>                           
                                        </ul>
                                    </li>                           
                                </ul>
                            </li>
                            <li><a href="#">Item 3-113</a></li>
                        </ul>
                    </li>
                    <li><a href="#">Item 3-13</a></li>
                </ul>
            </li>
            <li><a href="#">Item 3-2</a>
                <ul>
                    <li><a href="#."> Item 3-21 </a></li>
                    <li><a href="#."> Item 3-22 </a></li>
                    <li><a href="#."> Item 3-23 </a></li>
                </ul>   
            </li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a class="clk" href="#">Item 4</a>
        <ul class="sub-menu">
            <li><a href="#">Item 4-1</a>
                <ul class="sub-menu">
                    <li><a href="#."> Item 4-11 </a></li>
                    <li><a href="#."> Item 4-12 </a></li>
                    <li><a href="#."> Item 4-13 </a>
                        <ul>
                            <li><a href="#."> Item 4-131 </a></li>
                            <li><a href="#."> Item 4-132 </a></li>
                            <li><a href="#."> Item 4-133 </a></li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href="#">Item 4-2</a></li>
            <li><a href="#">Item 4-3</a></li>
        </ul>
    </li>
    <li><a class="clk" href="#">Item 5</a></li>
</ul>

javascript

$(document).ready(function(){

var menu = "#nav";
var position = {my: "left top", at: "left bottom"};

$(menu).menu({

    position: position,
    blur: function() {
        $(this).menu("option", "position", position);
        },
    focus: function(e, ui) {

        if ($(menu).get(0) !== $(ui).get(0).item.parent().get(0)) {
            $(this).menu("option", "position", {my: "left top", at: "right top"});
            }
    }
});     });

CSS

.ui-menu {width: auto;}.ui-menu:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}.ui-menu .ui-menu-item {display: inline-block;margin: 0;padding: 0;width: auto;}#nav{text-align: center;font-size: 12px;}#nav li {display: inline-block;}#nav li a span.ui-icon-carat-1-e {float:right;position:static;margin-top:2px;width:16px;height:16px;background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -64px -16px;}#nav li ul li {width: 120px;border-bottom: 1px solid #ccc;}#nav li ul {width: 120px; }.ui-menu .ui-menu-item li a span.ui-icon-carat-1-e {background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -32px -16px !important;

Can I run CUDA on Intel's integrated graphics processor?

Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.

Link: http://www.pgroup.com/products/pgiworkstation.htm

Difference between "as $key => $value" and "as $value" in PHP foreach

A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  
} 


Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  
} 

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

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.

Enforcing the type of the indexed members of a Typescript object?

interface AccountSelectParams {
  ...
}
const params = { ... };

const tmpParams: { [key in keyof AccountSelectParams]: any } | undefined = {};
  for (const key of Object.keys(params)) {
    const customKey = (key as keyof typeof params);
    if (key in params && params[customKey] && !this.state[customKey]) {
      tmpParams[customKey] = params[customKey];
    }
  }

please commented if you get the idea of this concept