Programs & Examples On #Non unicode

Unicode is intended to be a universal character set for describing all the characters required for written text incorporating all writing systems, technical symbols and punctuation. But unicode isn't supported on every system, and many other character sets exist.

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

At some point, you're trying to convert an nvarchar column to a varchar column (or vice-versa).

Moreover, why is everything (supposedly) nvarchar(max)? That's a code smell if I ever saw one. Are you aware of how SQL Server stores those columns? They use pointers to where the column is stored from the actual rows, since they don't fit within the 8k pages.

SSIS Convert Between Unicode and Non-Unicode Error

I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.

Removing the NULL value solved my issue.

Cheers, Ahmed

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

https://github.com/davemorrissey/subsampling-scale-image-view

How to properly upgrade node using nvm

? TWO Simple Solutions:

To install the latest version of node and reinstall the old version packages just run the following command.

nvm install node --reinstall-packages-from=node

To install the latest lts (long term support) version of node and reinstall the old version packages just run the following command.

nvm install --lts /* --reinstall-packages-from=node

Here's a GIF to support this answer.

nvm

How do you access the element HTML from within an Angular attribute directive?

This is because the content of

<p myHighlight>Highlight me!</p>

has not been rendered when the constructor of the HighlightDirective is called so there is no content yet.

If you implement the AfterContentInit hook you will get the element and its content.

import { Directive, ElementRef, AfterContentInit } from '@angular/core';

@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {

    constructor(private el: ElementRef) {
        //el.nativeElement.style.backgroundColor = 'yellow';
    }

    ngAfterContentInit(){
        //you can get to the element content here 
        //this.el.nativeElement
    }
}

How to read an entire file to a string using C#?

you can use :

 public static void ReadFileToEnd()
{
    try
    {
    //provide to reader your complete text file
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line = sr.ReadToEnd();
            Console.WriteLine(line);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

MySQL OPTIMIZE all tables?

Do all the necessary procedures for fixing all tables in all the databases with a simple shell script:

#!/bin/bash
mysqlcheck --all-databases
mysqlcheck --all-databases -o
mysqlcheck --all-databases --auto-repair
mysqlcheck --all-databases --analyze

git repo says it's up-to-date after pull but files are not updated

Try this:

 git fetch --all
 git reset --hard origin/master

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Please let me know if you have any questions!

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

Even I have experience some more strange things, I can see there is no dll in GAC from where the dll is loading but windows > Module shows system.dll version=4.0.0.0 loaded

Populate dropdown select with array using jQuery

function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}

Get all inherited classes of an abstract class

It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport) for each one.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){
    this.name=name;
  },
  print: function(){
    console.log(this.name);
  }
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

Replace values in list using Python

Here's another way:

>>> L = range (11)
>>> map(lambda x: x if x%2 else None, L)
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can use the :before pseudo-selector to insert content in front of the list item. You can find an example on Quirksmode, at http://www.quirksmode.org/css/beforeafter.html. I use this to insert giant quotes around blockquotes...

HTH.

Xcode Error: "The app ID cannot be registered to your development team."

I encountered the same problem when I was trying to compile a sample project provided by Apple. In the end I figured out that apparently they pre-compiled the sample code before shipping them to developers, so the binary had their signature.

The way to solve it is simple, just delete all the built binaries and re-compile using your own bundle identifier and you should be fine.

Just go to the menu bar, click on [Product] -> [Clean Build Folder] to delete all compiled binaries

Clean Build Folder

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Get Time from Getdate()

select convert(varchar(10), GETDATE(), 108)

returned 17:36:56 when I ran it a few moments ago.

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

How to validate an email address using a regular expression?

I've been using this touched up version of your regex for a while and it hasn't left me with too many surprises. I've never encountered an apostrophe in an email yet so it doesn't validate that. It does validate Jean+Franç[email protected] and ?@??.??.????.??????? but not weird abuse of those non alphanumeric characters [email protected].

(?!^[.+&'_-]*@.*$)(^[_\w\d+&'-]+(\.[_\w\d+&'-]*)*@[\w\d-]+(\.[\w\d-]+)*\.(([\d]{1,3})|([\w]{2,}))$)

It does support IP addresses [email protected] but I haven't refined it enough to deal with bogus IP ranges such as 999.999.999.1.

It also supports all the TLDs over 3 characters which stops [email protected] which I think the original let through. I've been beat, there are too many tlds now over 3 characters.

I know acrosman has abandoned his regex but this flavour lives on.

How do CSS triangles work?

The borders use an angled edge where they intersect (45° angle with equal width borders, but changing the border widths can skew the angle).

Border example

_x000D_
_x000D_
div {_x000D_
  width: 60px;_x000D_
  border-width: 30px;_x000D_
  border-color: red blue green yellow;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Have a look to the jsFiddle.

By hiding certain borders, you can get the triangle effect (as you can see above by making the different portions different colours). transparent is often used as an edge colour to achieve the triangle shape.

How to Find the Default Charset/Encoding in Java?

Is this a bug or feature?

Looks like undefined behaviour. I know that, in practice, you can change the default encoding using a command-line property, but I don't think what happens when you do this is defined.

Bug ID: 4153515 on problems setting this property:

This is not a bug. The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

The preferred way to change the default encoding used by the VM and the runtime system is to change the locale of the underlying platform before starting your Java program.

I cringe when I see people setting the encoding on the command line - you don't know what code that is going to affect.

If you do not want to use the default encoding, set the encoding you do want explicitly via the appropriate method/constructor.

How to delete all files from a specific folder?

Try this:

foreach (string file in Directory.GetFiles(@"c:\directory\"))
  File.Delete(file);

In Excel, sum all values in one column in each row where another column is a specific value

If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

=SUMIF(B:B,"No",A:A)

or

=SUMIFS(A:A,B:B,"No")

Here is an example that will display the amounts paid and outstanding for a small set of sample data.

 A         B            C                   D
 Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
 $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
 $200      No           
 $300      No
 $400      Yes
 $500      No

Result of Excel calculations

When is the init() function run?

init will be called everywhere uses its package(no matter blank import or import), but only one time.

this is a package:

package demo

import (
    "some/logs"
)

var count int

func init() {
    logs.Debug(count)
}

// Do do
func Do() {
    logs.Debug("dd")
}

any package(main package or any test package) import it as blank :

_ "printfcoder.com/we/models/demo"

or import it using it func:

"printfcoder.com/we/models/demo"

func someFunc(){
   demo.Do()
}

the init will log 0 only one time. the first package using it, its init func will run before the package's init. So:

A calls B, B calls C, all of them have init func, the C's init will be run first before B's, B's before A's.

How do I setup the dotenv file in Node.js?

i had similar problem. i solved it by trim. Please check, path.resolve may add additional space to end of path.

var path = require('path');
const envPath = path.resolve(process.cwd()+'/config','.env.'+process.env.NODE_ENV).trim()
require('dotenv').config({ path: envPath })

my package script is like this to use multiple .env:

 "scripts": {
    "start": "set NODE_ENV=development && nodemon ./bin/www",
    "prod": "set NODE_ENV=production && node ./bin/www"
  },

One liner for If string is not null or empty else

You can achieve this with pattern matching with the switch expression in C#8/9

FooTextBox.Text = strFoo switch
{
    { Length: >0 } s => s, // If the length of the string is greater than 0 
    _ => "0" // Anything else
};

Check if all values in list are greater than a certain number

I write this function

def larger(x, than=0):
    if not x or min(x) > than:
        return True
    return False

Then

print larger([5, 6, 7], than=5)  # False
print larger([6, 7, 8], than=5)  # True
print larger([], than=5)  # True
print larger([6, 7, 8, None], than=5)  # False


Empty list on min() will raise ValueError. So I added if not x in condition.

Setting initial values on load with Select2 with Ajax

Late :( but I think this will solve your problem.

 $("#controlId").val(SampleData [0].id).trigger("change");

After the data binding

 $("#controlId").select2({
        placeholder:"Select somthing",
        data: SampleData // data from ajax controll
    });
    $("#controlId").val(SampleData[0].id).trigger("change");

Get all object attributes in Python?

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

How to do ToString for a possibly null object?

I disagree with that this:

String s = myObj == null ? "" : myObj.ToString();

is a hack in any way. I think it's a good example of clear code. It's absolutely obvious what you want to achieve and that you're expecting null.

UPDATE:

I see now that you were not saying that this was a hack. But it's implied in the question that you think this way is not the way to go. In my mind it's definitely the clearest solution.

CSS3 Transform Skew One Side

Maybe you want to use CSS "clip-path" (Works with transparency and background)

"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

Generator: http://bennettfeely.com/clippy/

Example:

_x000D_
_x000D_
/* With percent */_x000D_
.element-percent {_x000D_
  background: red;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
  background: blue;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
  background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
_x000D_
_x000D_

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How to drop columns using Rails migration

There are two good ways to do this:

remove_column

You can simply use remove_column, like so:

remove_column :users, :first_name

This is fine if you only need to make a single change to your schema.

change_table block

You can also do this using a change_table block, like so:

change_table :users do |t|
  t.remove :first_name
end

I prefer this as I find it more legible, and you can make several changes at once.

Here's the full list of supported change_table methods:

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Darken background image on hover

Try following code:

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.2;
}

.image:hover{
    opacity:1;
}

What is the best java image processing library/approach?

I know this question is quite old, but as new software comes out it does help to get some new links to projects that might be interesting for folks.

imgscalr is pure-Java image resizing (and simple ops like padding, cropping, rotating, brighten/dimming, etc.) library that is painfully simple to use - a single class consists of a set of simple graphics operations all defined as static methods that you pass an image and get back a result.

The most basic example of using the library would look like this:

BufferedImage thumbnail = Scalr.resize(image, 150);

And a more typical usage to generate image thumbnails using a few quality tweaks and the like might look like this:

import static org.imgscalr.Scalr.*;

public static BufferedImage createThumbnail(BufferedImage img) {
    // Create quickly, then smooth and brighten it.
    img = resize(img, Method.SPEED, 125, OP_ANTIALIAS, OP_BRIGHTER);

    // Let's add a little border before we return result.
    return pad(img, 4);
}

All image-processing operations use the raw Java2D pipeline (which is hardware accelerated on major platforms) and won't introduce the pain of calling out via JNI like library contention in your code.

imgscalr has also been deployed in large-scale productions in quite a few places - the inclusion of the AsyncScalr class makes it a perfect drop-in for any server-side image processing.

There are numerous tweaks to image-quality you can use to trade off between speed and quality with the highest ULTRA_QUALITY mode providing a scaled result that looks better than GIMP's Lancoz3 implementation.

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

How to change indentation in Visual Studio Code?

Simplified explanation with pictures for those that googled "Change indentation in VS Code"

Step 1: Click on Preferences > Settings

enter image description here

Step 2: The setting you are looking for is "Detect Indentation", begin typing that. Click on "Editor: Tab Size"

enter image description here

Step 3: Scroll down to "Editor: Tab Size" and type in 2 (or whatever you need).

enter image description here



Changes are automatically saved

enter image description here

Example of my changes

enter image description here

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

In my case it was a matter of a mis-directed reference. Project referenced the output of another project but the latter did not output the file where the former was looking for.

Connect to mysql on Amazon EC2 from a remote server

It could be that you have not configured the Amazon Security Group assigned to your EC2 Instance to accept incoming requests on port 3306 (default port for MySQL).

If this is the case then you can easily open up the port for the security group in a few button clicks:

1) Log into you AWS Console and go to 'EC2'

2) On the left hand menu under 'Network & Security' go to 'Security Groups'

3) Check the Security Group in question

4) Click on 'Inbound tab'

5) Choose 'MYSQL' from drop down list and click 'Add Rule'

Might not be the reason but worth a go...

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

How to put a jpg or png image into a button in HTML

It should be

<input type="image" id="myimage" src="[...]" />

So "image" instead of "submit". It will still be a button which submits on click.

If your image is bigger than the button which is shown; let's say the image is 200x200 pixels; add this to your stylesheet:

#myimage {
    height: 200px;
    width: 200px;
}

or directly in the button tag:

<input type="image" id="myimage" style="height:200px;width:200px;" src="[...]" />

Note however that resizing the image like this might not yield ideal results; if e.g. your image is much smaller than you want it to be shown, you will see the single pixels; if on the other hand it is much bigger, you are wasting precious bandwidth of your users. So resizing the picture itself to the actual size is preferrable over rescaling via stylesheets!

Converting between java.time.LocalDateTime and java.util.Date

Everything is here : http://blog.progs.be/542/date-to-java-time

The answer with "round-tripping" is not exact : when you do

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

if your system timezone is not UTC/GMT, you change the time !

Difference between spring @Controller and @RestController annotation

As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody is active by default, so all the Java objects are serialized to JSON representation in the response body.

Converting string to number in javascript/jQuery

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

m2eclipse error

I had same problem with Eclipse 3.7.2 (Indigo) and maven 3.0.4.

In my case, the problem was caused by missing maven-resources-plugin-2.4.3.jar in {user.home}\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3 folder. (no idea why maven didn't update it)

Solution:

1.) add dependency to pom.xml

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.4.3</version>
</dependency>

2.) run mvn install from Eclipse or from command line

3.) refresh the project in eclipse (F5)

4.) run Maven > Update Project Configuration... on project (right click)

JAR file is downloaded to local repository and there are no errors in WS.

How to validate a credit card number

Maybe have a look at this solution: https://codepen.io/quinlo/pen/YONMEa

//pop in the appropriate card icon when detected
cardnumber_mask.on("accept", function () {
    console.log(cardnumber_mask.masked.currentMask.cardtype);
    switch (cardnumber_mask.masked.currentMask.cardtype) {
        case 'american express':
            ccicon.innerHTML = amex;
            ccsingle.innerHTML = amex_single;
            swapColor('green');
            break;
        case 'visa':
            ccicon.innerHTML = visa;
            ccsingle.innerHTML = visa_single;
            swapColor('lime');
            break;
        case 'diners':
            ccicon.innerHTML = diners;
            ccsingle.innerHTML = diners_single;
            swapColor('orange');
            break;
        case 'discover':
            ccicon.innerHTML = discover;
            ccsingle.innerHTML = discover_single;
            swapColor('purple');
            break;
        case ('jcb' || 'jcb15'):
            ccicon.innerHTML = jcb;
            ccsingle.innerHTML = jcb_single;
            swapColor('red');
            break;
        case 'maestro':
            ccicon.innerHTML = maestro;
            ccsingle.innerHTML = maestro_single;
            swapColor('yellow');
            break;
        case 'mastercard':
            ccicon.innerHTML = mastercard;
            ccsingle.innerHTML = mastercard_single;
            swapColor('lightblue');

            break;
        case 'unionpay':
            ccicon.innerHTML = unionpay;
            ccsingle.innerHTML = unionpay_single;
            swapColor('cyan');
            break;
        default:
            ccicon.innerHTML = '';
            ccsingle.innerHTML = '';
            swapColor('grey');
            break;
    }

});

Array initialization syntax when not in a declaration

I can't answer the why part.

But if you want something dynamic then why don't you consider Collection ArrayList.

ArrrayList can be of any Object type.

And if as an compulsion you want it as an array you can use the toArray() method on it.

For example:

            ArrayList<String> al = new ArrayList<String>();
            al.add("one");
            al.add("two");
            String[] strArray = (String[]) al.toArray(new String[0]);

I hope this might help you.

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

Download/Stream file from URL - asp.net

I do this quite a bit and thought I could add a simpler answer. I set it up as a simple class here, but I run this every evening to collect financial data on companies I'm following.

class WebPage
{
    public static string Get(string uri)
    {
        string results = "N/A";

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            results = sr.ReadToEnd();
            sr.Close();
        }
        catch (Exception ex)
        {
            results = ex.Message;
        }
        return results;
    }
}

In this case I pass in a url and it returns the page as HTML. If you want to do something different with the stream instead you can easily change this.

You use it like this:

string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");

Detect click event inside iframe

If anyone is interested in a "quick reproducible" version of the accepted answer, see below. Credits to a friend who is not on SO. This answer can also be integrated in the accepted answer with an edit,... (It has to run on a (local) server).

<html>
<head>
<title>SO</title>
<meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<style type="text/css">
html,
body,
#filecontainer {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe src="http://localhost/tmp/fileWithLink.html" id="filecontainer"></iframe>

<script type="text/javascript">
$('#filecontainer').load(function(){

  var iframe = $('#filecontainer').contents();

  iframe.find("a").click(function(){
    var test = $(this);
    alert(test.html());
  });
});
</script>
</body>
</html>

fileWithLink.html

<html>
<body>
<a href="https://stackoverflow.com/">SOreadytohelp</a>
</body>
</html>

ADB No Devices Found

  1. Go to device manager and check hardware id's.
  2. Check if the usb.inf file has the device listed in it
  3. If not, add the device hardware id and install it from the device manager.

How I can print to stderr in C?

If you don't want to modify current codes and just for debug usage.

Add this macro:

#define printf(args...) fprintf(stderr, ##args)
//under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
//under MSVC

Change stderr to stdout if you want to roll back.

It's helpful for debug, but it's not a good practice.

No module named 'pymysql'

After trying a few things, and coming across PyMySQL Github, this worked:

sudo pip install PyMySQL

And to import use:

import pymysql

How to draw checkbox or tick mark in GitHub Markdown table?

Following is how I draw a checkbox in a table!

| Checkbox Experiments | [ ] unchecked header  | [x] checked header  |
| ---------------------|:---------------------:|:-------------------:|
| checkbox             | [ ] row               | [x] row             |


Displays like this:
enter image description here

what is an illegal reflective access

Just look at setAccessible() method used to access private fields and methods:

https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean-

https://docs.oracle.com/javase/9/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean-

Now there is a lot more conditions required for this method to work. The only reason it doesn't break almost all of older software is that modules autogenerated from plain JARs are very permissive (open and export everything for everyone).

Angular ui-grid dynamically calculate height of the grid

I use ui-grid - v3.0.0-rc.20 because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if is optional to wait until your data is set before rendering.

_x000D_
_x000D_
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
    ..._x000D_
    _x000D_
    $scope.gridData = {_x000D_
      rowHeight: 30, // set row height, this is default size_x000D_
      ..._x000D_
    };_x000D_
  _x000D_
    ..._x000D_
_x000D_
    $scope.getTableHeight = function() {_x000D_
       var rowHeight = 30; // your row height_x000D_
       var headerHeight = 30; // your header height_x000D_
       return {_x000D_
          height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
       };_x000D_
    };_x000D_
      _x000D_
    ...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
_x000D_
_x000D_

What does the @Valid annotation indicate in Spring?

Just adding to the above answer, In a web application @valid is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull, @Email(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results. bindingResult.hasErrors() will tell if any validation failed.

PHP - Notice: Undefined index:

Before you extract values from $_POST, you should check if they exist. You could use the isset function for this (http://php.net/manual/en/function.isset.php)

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

Click in OK button inside an Alert (Selenium IDE)

about Selenium IDE, I am not an expert but you have to add the line "choose ok on next confirmation" before the event which trigger the alert/confirm dialog box as you can see into this screenshot:

Selenium IDE order matter

Serializing and submitting a form with jQuery and PHP

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

Similarity String Comparison in Java

I translated the Levenshtein distance algorithm into JavaScript:

String.prototype.LevenshteinDistance = function (s2) {
    var array = new Array(this.length + 1);
    for (var i = 0; i < this.length + 1; i++)
        array[i] = new Array(s2.length + 1);

    for (var i = 0; i < this.length + 1; i++)
        array[i][0] = i;
    for (var j = 0; j < s2.length + 1; j++)
        array[0][j] = j;

    for (var i = 1; i < this.length + 1; i++) {
        for (var j = 1; j < s2.length + 1; j++) {
            if (this[i - 1] == s2[j - 1]) array[i][j] = array[i - 1][j - 1];
            else {
                array[i][j] = Math.min(array[i][j - 1] + 1, array[i - 1][j] + 1);
                array[i][j] = Math.min(array[i][j], array[i - 1][j - 1] + 1);
            }
        }
    }
    return array[this.length][s2.length];
};

Simple JavaScript Checkbox Validation

If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:

html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">

script:
<script type="text/Javascript">
    function deleteData() {
        if(!document.getElementById('Delete').checked){
            alert('Checkbox not checked');
            return false;
        }
</script>

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

At runtime, find all classes in a Java application that extend a base class

One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):

public class Dog extends Animal{

static
{
   Animal a = new Dog();
   //add a to the List
}

It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

Being au fait with patterns as defined by (say) the GOF book, and naming objects after these gets me a long way in naming classes, organising them and communicating intent. Most people will understand this nomenclature (or at least a major part of it).

Java Reflection Performance

Yes there is a performance hit when using Reflection but a possible workaround for optimization is caching the method:

  Method md = null;     // Call while looking up the method at each iteration.
      millis = System.currentTimeMillis( );
      for (idx = 0; idx < CALL_AMOUNT; idx++) {
        md = ri.getClass( ).getMethod("getValue", null);
        md.invoke(ri, null);
      }

      System.out.println("Calling method " + CALL_AMOUNT+ " times reflexively with lookup took " + (System.currentTimeMillis( ) - millis) + " millis");



      // Call using a cache of the method.

      md = ri.getClass( ).getMethod("getValue", null);
      millis = System.currentTimeMillis( );
      for (idx = 0; idx < CALL_AMOUNT; idx++) {
        md.invoke(ri, null);
      }
      System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with cache took " + (System.currentTimeMillis( ) - millis) + " millis");

will result in:

[java] Calling method 1000000 times reflexively with lookup took 5618 millis

[java] Calling method 1000000 times reflexively with cache took 270 millis

Proper use of errors

Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

EvalError --- Creates an instance representing an error that occurs regarding the global function eval().

InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

Returning from a void function

Neither is more correct, so take your pick. The empty return; statement is provided to allow a return in a void function from somewhere other than the end. No other reason I believe.

REST API error return good practices

If the client quota is exceeded it is a server error, avoid 5xx in this instance.

How to apply color in Markdown?

I like the idea of redefining existing tags if they're unused due to the fact that the text is cleaner, at the expense of existing tags. The inline styling works but creates a lot of noise when reading the raw text.

Using VSCode I've found that custom single-letter tags, supported by a small <style> section at the top, works well with a minimum of noise, especially for spot colour, e.g.

<style>
r { color: Red }
o { color: Orange }
g { color: Green }
</style>

# TODOs:

- <r>TODO:</r> Important thing to do
- <o>TODO:</o> Less important thing to do
- <g>DONE:</g> Breath deeply and improve karma

My use-case is orgmode-ish in-app note taking during development but I guess it might work elsewhere?

Error when deploying an artifact in Nexus

For 400 error, check the repository "Deployment policy" usually its "Disable redeploy". Most of the time your library version is already there that is why you received a message "Could not PUT put 'https://yoururl/some.jar'. Received status code 400 from server: Repository does not allow updating assets: "your repository name"

So, you have a few options to resolve this. 1- allow redeploy 2- delete the version from your repository which you are trying to upload 3- change the version number

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

Try

dropdown.selectedOptions[0].text

_x000D_
_x000D_
function read() {_x000D_
  console.log( dropdown.selectedOptions[0].text );_x000D_
}
_x000D_
<select id="dropdown">_x000D_
  <option value="1">First</option>_x000D_
  <option value="2">Second</option>_x000D_
</select>_x000D_
<button onclick="read()">read</button>
_x000D_
_x000D_
_x000D_

How to TryParse for Enum value?

I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)

Bootstrap 4 - Inline List?

The html code you written is absolutely perfect

<ul class="nav navbar-nav list-inline">
 <li class="list-inline-item">FB</li>
 <li class="list-inline-item">G+</li>
 <li class="list-inline-item">T</li>
 </ul>

The reasons that could be possible is
1. Check out the CSS for class name "nav" or "navbar-nav" may be over writing it, try to remove and debug the class names in the ul element.
2. Check any of the child element(a tag or "social-icon" class) is using block level CSS style
3. Check out your using a HTML5 !DOCTYPE html
4. Place your bootstrap.css link at the last before closing your head tag
5. Change text-xs-center to text-center because xs is dropped in Bootstrap 4.

This One will work perfectly fine

<!-- Use this inside Head tag-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>



<!-- Use this inside Body tag-->
<div  class="container">
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">T</a></li>
</ul>
</div>

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

"Specified argument was out of the range of valid values"

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero

php static function

In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.

Apache won't run in xampp

Take a look at this site:

http://www.lukebrowning.com/blog/nt-kernel-system-using-port-80/

In my case, it was the SQL Server Reporting Service, but others have seen IIS or the Web Deployment Agent Service.

Open a cmd window and run services.msc, find the service, and stop it. Then try to start Apache. If it works, disable the other service.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Network usage top/htop on Linux

Also iftop:

display bandwidth usage on an interface

iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...

Paramiko's SSHClient with SFTP

paramiko.SFTPClient

Sample Usage:

import paramiko
paramiko.util.log_to_file("paramiko.log")

# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"
transport.connect(None,username,password)

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)

# Close
if sftp: sftp.close()
if transport: transport.close()

How do I simulate a hover with a touch in touch enabled browsers?

All you need to do is bind touchstart on a parent. Something like this will work:

$('body').on('touchstart', function() {});

You don't need to do anything in the function, leave it empty. This will be enough to get hovers on touch, so a touch behaves more like :hover and less like :active. iOS magic.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

The recommended way to do this is to use LocationClient:

First, define location update interval values. Adjust this to your needs.

private static final int MILLISECONDS_PER_SECOND = 1000;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

Have your Activity implement GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, and LocationListener.

public class LocationActivity extends Activity implements 
GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {}

Then, set up a LocationClientin the onCreate() method of your Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationClient = new LocationClient(this, this, this);

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}

Add the required methods to your Activity; onConnected() is the method that is called when the LocationClientconnects. onLocationChanged() is where you'll retrieve the most up-to-date location.

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.w(TAG, "Location client connection failed");
}

@Override
public void onConnected(Bundle dataBundle) {
    Log.d(TAG, "Location client connected");
    mLocationClient.requestLocationUpdates(mLocationRequest, this); 
}

@Override
public void onDisconnected() {
    Log.d(TAG, "Location client disconnected");
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        Log.d(TAG, "Updated Location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()));
    } else {
        Log.d(TAG, "Updated location NULL");
    } 
}     

Be sure to connect/disconnect the LocationClient so it's only using extra battery when absolutely necessary and so the GPS doesn't run indefinitely. The LocationClient must be connected in order to get data from it.

public void onResume() {
    super.onResume();
    mLocationClient.connect();
}

public void onStop() {
    if (mLocationClient.isConnected()) {
        mLocationClient.removeLocationUpdates(this);
    }
    mLocationClient.disconnect();
    super.onStop();
}

Get the user's location. First try using the LocationClient; if that fails, fall back to the LocationManager.

public Location getLocation() {
    if (mLocationClient != null && mLocationClient.isConnected()) {
        return mLocationClient.getLastLocation();
    } else {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (lastKnownLocationGPS != null) {
                return lastKnownLocationGPS;
            } else {
                return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
        } else {
            return null;
        }
    }
}

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

How do I import material design library to Android Studio?

build.gradle

implementation 'com.google.android.material:material:1.2.0-alpha02'

styles.xml

 <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

Open source PDF library for C/C++ application?

Try wkhtmltopdf

Software features

Cross platform. Open source. Convert any web pages into PDF documents using webkit. You can add headers and footers. TOC generation. Batch mode conversions. Can run on Linux server with an XServer (the X11 client libs must be installed). Can be directly used by PHP or Python via bindings to libwkhtmltox.

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

My solution, having encountered the same error message, was even simpler than the ones above, I just updated the to basicHttpsBinding>

  <bindings>
    <basicHttpsBinding>
    <binding name="ShipServiceSoap" maxBufferPoolSize="512000" maxReceivedMessageSize="512000" />
    </basicHttpsBinding>
    </bindings>

And the same in the section below:

  <client>
    <endpoint address="https://s.asmx" binding="basicHttpsBinding" bindingConfiguration="ShipServiceSoap" contract="..ServiceSoap" name="ShipServiceSoap" />
    </client>

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

Launch Minecraft from command line - username and password as prefix

For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely

Besides setting some basic variables near the top after the functions, it calls a get_classpath that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json, and loops over the libraries array, checking to see if each object (within the array), is supposed to be added to the classpath (cp variable). whether this library is added to the java classpath is governed by the should_use_library function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar). this extra prepended string is handled by get_natives_string and is empty if it doesn't apply to the current library

tested on Linux, distribution Arch Linux

#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess


"""Debug output
"""
def debug(str):
    if os.getenv('DEBUG') != None:
        print(str)

"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
    arch = ""
    if platform.architecture()[0] == "64bit":
        arch = "64"
    elif platform.architecture()[0] == "32bit":
        arch = "32"
    else:
        raise Exception("Architecture not supported")

    nativesFile=""
    if not "natives" in lib:
        return nativesFile

    # i've never seen ${arch}, but leave it in just in case
    if "windows" in lib["natives"] and platform.system() == 'Windows':
        nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
    elif "osx" in lib["natives"] and platform.system() == 'Darwin':
        nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
    elif "linux" in lib["natives"] and platform.system() == "Linux":
        nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
    else:
        raise Exception("Platform not supported")

    return nativesFile


"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
    def rule_says_yes(rule):
        useLib = None

        if rule["action"] == "allow":
            useLib = False
        elif rule["action"] == "disallow":
            useLib = True

        if "os" in rule:
            for key, value in rule["os"].items():
                os = platform.system()
                if key == "name":
                    if value == "windows" and os != 'Windows':
                        return useLib
                    elif value == "osx" and os != 'Darwin':
                        return useLib
                    elif value == "linux" and os != 'Linux':
                        return useLib
                elif key == "arch":
                    if value == "x86" and platform.architecture()[0] != "32bit":
                        return useLib

        return not useLib

    if not "rules" in lib:
        return True

    shouldUseLibrary = False
    for i in lib["rules"]:
        if rule_says_yes(i):
            return True

    return shouldUseLibrary

"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
    cp = []

    for i in lib["libraries"]:
        if not should_use_library(i):
            continue

        libDomain, libName, libVersion = i["name"].split(":")
        jarPath = os.path.join(mcDir, "libraries", *
                               libDomain.split('.'), libName, libVersion)

        native = get_natives_string(i)
        jarFile = libName + "-" + libVersion + ".jar"
        if native != "":
            jarFile = libName + "-" + libVersion + "-" + native + ".jar"

        cp.append(os.path.join(jarPath, jarFile))

    cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))

    return os.pathsep.join(cp)

version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'

mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
    Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']

debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)

subprocess.call([
    '/usr/bin/java',
    f'-Djava.library.path={nativesDir}',
    '-Dminecraft.launcher.brand=custom-launcher',
    '-Dminecraft.launcher.version=2.1',
    '-cp',
    classPath,
    'net.minecraft.client.main.Main',
    '--username',
    username,
    '--version',
    version,
    '--gameDir',
    mcDir,
    '--assetsDir',
    os.path.join(mcDir, 'assets'),
    '--assetIndex',
    assetIndex,
    '--uuid',
    uuid,
    '--accessToken',
    accessToken,
    '--userType',
    'mojang',
    '--versionType',
    'release'
])

Passing arrays as parameters in bash

Just to add to the accepted answer, as I found it doesn't work well if the array contents are someting like:

RUN_COMMANDS=(
  "command1 param1... paramN"
  "command2 param1... paramN"
)

In this case, each member of the array gets split, so the array the function sees is equivalent to:

RUN_COMMANDS=(
    "command1"
    "param1"
     ...
    "command2"
    ...
)

To get this case to work, the way I found is to pass the variable name to the function, then use eval:

function () {
    eval 'COMMANDS=( "${'"$1"'[@]}" )'
    for COMMAND in "${COMMANDS[@]}"; do
        echo $COMMAND
    done
}

function RUN_COMMANDS

Just my 2©

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

how to use LIKE with column name

declare @LkeVal as Varchar(100)
declare @LkeSelect Varchar(100)

Set @LkeSelect = (select top 1 <column> from <table> where <column> = 'value')
Set @LkeVal = '%' + @LkeSelect

select * from <table2> where <column2> like(''+@LkeVal+'');

How to access global variables

I suggest use the common way of import.

First I will explain the way it called "relative import" maybe this way cause of some error

Second I will explain the common way of import.

FIRST:

In go version >= 1.12 there is some new tips about import file and somethings changed.

1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"

2- You have to use uppercase when you want to import a file!

3- Use Uppercase for variables, structures and functions that you want to import in another files

Notice: There is no way to import the main.go in another file.

file directory is:

root
|_____main.go
|_____model
          |_____example.go

this is a example.go:

package model

import (
    "time"
)

var StartTime = time.Now()

and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase

package main

import (
    Mod "./model"
    "fmt"
)

func main() {
    fmt.Println(Mod.StartTime)
}

NOTE!!!

NOTE: I don't recommend this this type of import!

SECOND:

(normal import)

the better way import file is:

your structure should be like this:

root
|_____github.com
         |_________Your-account-name-in-github
         |                |__________Your-project-name
         |                                |________main.go
         |                                |________handlers
         |                                |________models
         |               
         |_________gorilla
                         |__________sessions

and this is a example:

package main

import (
    "github.com/gorilla/sessions"
)

func main(){
     //you can use sessions here
}

so you can import "github.com/gorilla/sessions" in every where that you want...just import it.

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

What is Bootstrap?

By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".

But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.

A few core principles which contributed to Bootstrap's success:

  • it's reusable
  • it's flexible (i.e: allows custom grid systems, changing responsiveness breakpoints, column gutter sizes or state colors with ease; as a rule of thumb, most settings are controlled by global variables)
  • it's intuitive
  • it's modular (both JavaScript and (S)CSS use a modular approach; one can easily find tutorials on making custom Bootstrap builds, to include only the parts they need)
  • has above average cross-browser compatibility
  • web accessibility out of the box (screenreader ready)
  • it's fairly well documented

It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.


By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:

Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.

Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.


Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)

Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.

Select random lines from a file

My preferred option is very fast, I sampled a tab-delimited data file with 13 columns, 23.1M rows, 2.0GB uncompressed.

# randomly sample select 5% of lines in file
# including header row, exclude blank lines, new seed

time \
awk 'BEGIN  {srand()} 
     !/^$/  { if (rand() <= .05 || FNR==1) print > "data-sample.txt"}' data.txt

# awk  tsv004  3.76s user 1.46s system 91% cpu 5.716 total

What is the best way to test for an empty string with jquery-out-of-the-box?

if(!my_string){ 
// stuff 
}

and

if(my_string !== "")

if you want to accept null but reject empty

EDIT: woops, forgot your condition is if it IS empty

jQuery Change event on an <input> element - any way to retain previous value?

A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here

e.g

<script>
    //look no global needed:)

    $(document).ready(function(){
        // Get the initial value
       var $el = $('#myInputElement');
       $el.data('oldVal',  $el.val() );


       $el.change(function(){
            //store new value
            var $this = $(this);
            var newValue = $this.data('newVal', $this.val());
       })
       .focus(function(){
            // Get the value when input gains focus
            var oldValue = $(this).data('oldVal');
       });
    });
</script>
<input id="myInputElement" type="text">

Eclipse jump to closing brace

Place the cursor next to an opening or closing brace and punch Ctrl + Shift + P to find the matching brace. If Eclipse can't find one you'll get a "No matching bracket found" message.

edit: as mentioned by Romaintaz below, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.

HTTP GET in VB.NET

Use the WebRequest class

This is to get an image:

Try
    Dim _WebRequest As System.Net.WebRequest = Nothing
    _WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

Try
    _NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to determine if object is in array

You can just use the equality operator: ==. Objects are checked by reference by default, so you don't even need to use the === operator.

try this, just make sure you're using the correct variable reference in the place of car1:

var i, car, l = cars.length;

for (i = 0; i < l; i++)
{
  if ((car = cars[i]) == car1)
  {
    break;
  }
  else car = null;
}

Edit to add:

An array extension was mentioned, so here's the code for it:

Array.prototype.contains = Array.prototype.contains || function(obj)
{
  var i, l = this.length;
  for (i = 0; i < l; i++)
  {
    if (this[i] == obj) return true;
  }
  return false;
};

Note that I'm caching the length value, as the Array's length property is actually an accessor, which is marginally slower than an internal variable.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

private final static attribute vs private final attribute

Reading the answers I found no real test really getting to the point. Here are my 2 cents :

public class ConstTest
{

    private final int         value             = 10;
    private static final int  valueStatic       = 20;
    private final File        valueObject       = new File("");
    private static final File valueObjectStatic = new File("");

    public void printAddresses() {


        System.out.println("final int address " +
                ObjectUtils.identityToString(value));
        System.out.println("final static int address " +
                ObjectUtils.identityToString(valueStatic));
        System.out.println("final file address " + 
                ObjectUtils.identityToString(valueObject));
        System.out.println("final static file address " + 
                ObjectUtils.identityToString(valueObjectStatic));
    }


    public static void main(final String args[]) {


        final ConstTest firstObj = new ConstTest();
        final ConstTest sndObj = new ConstTest();

        firstObj.printAdresses();
        sndObj.printAdresses();
    }

}

Results for first object :

final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@6c22c95b
final static file address java.io.File@5fd1acd3

Results for 2nd object :

final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@3ea981ca
final static file address java.io.File@5fd1acd3

Conclusion :

As I thought java makes a difference between primitive and other types. Primitive types in Java are always "cached", same for strings literals (not new String objects), so no difference between static and non-static members.

However there is a memory duplication for non-static members if they are not instance of a primitive type.

Changing value of valueStatic to 10 will even go further as Java will give the same addresses to the two int variables.

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

If you need a recursive search, you have a variety of options. You should consider ack.

Failing that, if you have GNU find and xargs:

find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null

The use of /dev/null ensures you get file names printed; the -print0 and -0 deals with file names containing spaces (newlines, etc).

If you don't have obstreperous names (with spaces etc), you can use:

find . -name '*.*[ch]' -print | xargs grep hello /dev/null

This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find and xargs.

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

Synchronous XMLHttpRequest warning and <script>

Even the latest jQuery has that line, so you have these options:

  • Change the source of jQuery yourself - but maybe there is a good reason for its usage
  • Live with the warning, please note that this option is deprecated and not obsolete.
  • Change your code, so it does not use this function

I think number 2 is the most sensible course of action in this case.

By the way if you haven't already tried, try this out: $.ajaxSetup({async:true});, but I don't think it will work.

Is it a bad practice to use an if-statement without curly braces?

It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:

if(statement)
{
    do this;
}
else
{
    do this;
}

However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:

if statement:
    do this
else:
    do this

While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Adding iOS UITableView HeaderView (not section header)

UITableView has a tableHeaderView property. Set that to whatever view you want up there.

Use a new UIView as a container, add a text label and an image view to that new UIView, then set tableHeaderView to the new view.

For example, in a UITableViewController:

-(void)viewDidLoad
{
     // ...
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:imageView];
     UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:labelView];
     self.tableView.tableHeaderView = headerView;
     [imageView release];
     [labelView release];
     [headerView release];
     // ...
} 

How to join two JavaScript Objects, without using JQUERY

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

How to create an object property from a variable value in JavaScript?

Oneliner:

obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);

Or:

attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);

Anything shorter?

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

How do I clear all options in a dropdown box?

This is a short way:

document.getElementById('mySelect').innerText = null;

One line, no for, no JQuery, simple.

What's a simple way to get a text input popup dialog box on an iPhone

Swift 3:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
     textField.placeholder = "Enter text:"
})

self.present(alert, animated: true, completion: nil)

Renaming column names of a DataFrame in Spark Scala

For those of you interested in PySpark version (actually it's same in Scala - see comment below) :

    merchants_df_renamed = merchants_df.toDF(
        'merchant_id', 'category', 'subcategory', 'merchant')

    merchants_df_renamed.printSchema()

Result:

root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)

Restoring Nuget References?

I suffered from this issue too a lot, in my case Downloading missing NuGet was checked (but it is not restoring them) and i can not uninstall & re-install because i modified some of the installed packages ... so:

I just cleared the cached and rebuild and it worked. (Tools-Option-Nuget Package Manager - General)

also this link helps https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore.

PHP is_numeric or preg_match 0-9 validation

is_numeric would accept "-0.5e+12" as a valid ID.

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

Removing object properties with Lodash

Here I have used omit() for the respective 'key' which you want to remove... by using the Lodash library:

var credentials = [{
        fname: "xyz",
        lname: "abc",
        age: 23
}]

let result = _.map(credentials, object => {
                       return _.omit(object, ['fname', 'lname'])
                   })

console.log('result', result)

CSS: how to get scrollbars for div inside container of fixed height

Code from the above answer by Dutchie432

.FixedHeightContainer {
    float:right;
    height: 250px;
    width:250px; 
    padding:3px; 
    background:#f00;
}

.Content {
    height:224px;
    overflow:auto;
    background:#fff;
}

Use PHP to create, edit and delete crontab jobs?

You can put your file to /etc/cron.d/ in cron format. Add some unique prefix to the filenaname To list script-specific cron jobs simply work with a list of files with a unique prefix. Delete the file when you want to disable the job.

How to sort rows of HTML table that are called from MySQL

It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.

In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)

Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.

You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.

A field initializer cannot reference the nonstatic field, method, or property

you can use like this

private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 

Removing input background colour for Chrome autocomplete?

A possible workaround for the moment is to set a "strong" inside shadow:

input:-webkit-autofill {
    -webkit-box-shadow:0 0 0 50px white inset; /* Change the color to your own background color */
    -webkit-text-fill-color: #333;
}

input:-webkit-autofill:focus {
    -webkit-box-shadow: /*your box-shadow*/,0 0 0 50px white inset;
    -webkit-text-fill-color: #333;
}  

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Bulk Insert Correctly Quoted CSV File in SQL Server

Make sure you have enabled TextQualified option and set it to be ".

Vertical and horizontal align (middle and center) with CSS

This blog post describes two methods of centering a div both horizontally and vertically. One uses only CSS and will work with divs that have a fixed size; the other uses jQuery and will work divs for which you do not know the size in advance.

I've duplicated the CSS and jQuery examples from the blog post's demo here:

CSS

Assuming you have a div with a class of .classname, the css below should work.

The left:50%; top:50%; sets the top left corner of the div to the center of the screen; the margin:-75px 0 0 -135px; moves it to the left and up by half of the width and height of the fixed-size div respectively.

.className{
    width:270px;
    height:150px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-75px 0 0 -135px;
}

jQuery

$(document).ready(function(){
    $(window).resize(function(){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    // To initially run the function:
    $(window).resize();
});

Here's a demo of the techniques in practice.

How can I get current date in Android?

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

This one is the best answer...

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Exec : display stdout "live"

There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn and the { stdio: 'inherit' } option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone.

Simply do this:

var spawn = require('child_process').spawn;

spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });

Credit to @MorganTouvereyQuilling for pointing this out in this comment.

What causes this error? "Runtime error 380: Invalid property value"

2017 I know... but someone is facing this problem during their code maintenance.

This error happened when I tried:

maskedbox.Mask = "#.###"
maskedbox.Text = "12345678"

To fix that, just set PromptInclude property to "false".

Visual studio equivalent of java System.out

In System.Diagnostics,

Debug.Write()
Debug.WriteLine()

etc. will print to the Output window in VS.

SQL Column definition : default value and not null redundant?

I would say not.

If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.

With not null set, then you can't insert a null value into the field as it'll throw an error.

Think of it as a fail safe mechanism to prevent nulls.

How to properly set the 100% DIV height to match document/window height?

I figured it out myself with the help of someone's answer. But he deleted it for some reason.

Here's the solution:

  1. remove all CSS height hacks and 100% heights
  2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
  3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
  4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

    $(function(){
        var windowH = $(window).height();
        var wrapperH = $('#wrapper').height();
        if(windowH > wrapperH) {                            
            $('#wrapper').css({'height':($(window).height())+'px'});
        }                                                                               
        $(window).resize(function(){
            var windowH = $(window).height();
            var wrapperH = $('#wrapper').height();
            var differenceH = windowH - wrapperH;
            var newH = wrapperH + differenceH;
            var truecontentH = $('#truecontent').height();
            if(windowH > truecontentH) {
                $('#wrapper').css('height', (newH)+'px');
            }
    
        })          
    });
    

Get original URL referer with PHP?

Store it either in a cookie (if it's acceptable for your situation), or in a session variable.

session_start();

if ( !isset( $_SESSION["origURL"] ) )
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];

Render partial from different folder (not shared)

For readers using ASP.NET Core 2.1 or later and wanting to use Partial Tag Helper syntax, try this:

<partial name="~/Views/Folder/_PartialName.cshtml" />

The tilde (~) is optional.

The information at https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper is helpful too.

Aligning textviews on the left and right edges in Android layout

It can be done with LinearLayout (less overhead and more control than the Relative Layout option). Give the second view the remaining space so gravity can work. Tested back to API 16.

Proof

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Aligned left" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout> 

If you want to limit the size of the first text view, do this:

Adjust weights as required. Relative layout won't allow you to set a percentage weight like this, only a fixed dp of one of the views

Proof 2

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Aligned left but too long and would squash the other view" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout>

How to add element to C++ array?

Initialize all your array elements to null first, then look for the null to find the empty slot

How do I check if a string is a number (float)?

For int use this:

>>> "1221323".isdigit()
True

But for float we need some tricks ;-). Every float number has one point...

>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False

Also for negative numbers just add lstrip():

>>> '-12'.lstrip('-')
'12'

And now we get a universal way:

>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False

Convert month name to month number in SQL Server

I recently had a similar experience (sql server 2012). I did not have the luxury of controlling the input, I just had a requirement to report on it. Luckily the dates were entered with leading 3 character alpha month abbreviations, so this made it simple & quick:

TRY_CONVERT(DATETIME,REPLACE(obs.DateValueText,SUBSTRING(obs.DateValueText,1,3),CHARINDEX(SUBSTRING(obs.DateValueText,1,3),'...JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC')/4)) 

It worked for 12 hour:
Feb-14-2015 5:00:00 PM 2015-02-14 17:00:00.000
and 24 hour times:
Sep-27-2013 22:45 2013-09-27 22:45:00.000

(thanks ryanyuyu)

What is your favorite C programming trick?

using __FILE__ and __LINE__ for debugging

#define WHERE fprintf(stderr,"[LOG]%s:%d\n",__FILE__,__LINE__);

JavaScript onclick redirect

Remove 'javascript:' from your code and it should work.

Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).

Strings in C, how to get subString

Doing it all in two fell swoops:

char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;

Launch Pycharm from command line (terminal)

Inside the IDE, you can click in:

Tools/Create Command-line Launcher...

Create Command-line Launcher

How do I install PyCrypto on Windows?

It's possible to build PyCrypto using the Windows 7 SDK toolkits. There are two versions of the Windows 7 SDK. The original version (for .Net 3.5) includes the VS 2008 command-line compilers. Both 32- and 64-bit compilers can be installed.

The first step is to compile mpir to provide fast arithmetic. I've documented the process I use in the gmpy library. Detailed instructions for building mpir using the SDK compiler can be found at sdk_build

The key steps to use the SDK compilers from a DOS prompt are:

1) Run either vcvars32.bat or vcvars64.bat as appropriate.

2) At the prompt, execute "set MSSdk=1"

3) At the prompt, execute "set DISTUTILS_USE_SDK=1"

This should allow "python setup.py install" to succeed assuming there are no other issues with the C code. But I vaaguely remember that I had to edit a couple of PyCrypto files to enable mpir and to find the mpir libraries but I don't have my Windows system up at the moment. It will be a couple of days before I'll have time to recreate the steps. If you haven't reported success by then, I'll post the PyCrypto steps. The steps will assume you were able to compile mpir.

I hope this helps.

WPF: Grid with column/row margin/padding?

You could write your own GridWithMargin class, inherited from Grid, and override the ArrangeOverride method to apply the margins

MySQL: Insert datetime into other datetime field

According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals

So, in your case, the command should be as follows:

UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1

Content Type application/soap+xml; charset=utf-8 was not supported by service

I was getting same error while using WebServiceTemplate spring ws [err] org.springframework.ws.client.WebServiceTransportException: Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. [415] [err] at org.springframework.ws.client.core.WebServiceTemplate.handleError(WebServiceTemplate.java:665). The WSDL which i was using has soap1.2 protocol and by default the protocol is soap1.1 . When i changed the protocol using below code, it was working

 MessageFactory msgFactory = MessageFactory.newInstance(javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL);
     SaajSoapMessageFactory saajSoapMessageFactory = new SaajSoapMessageFactory(msgFactory);
     saajSoapMessageFactory.setSoapVersion(SoapVersion.SOAP_12);
     getWebServiceTemplate().setMessageFactory(saajSoapMessageFactory);

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

What is logits, softmax and softmax_cross_entropy_with_logits?

Short version:

Suppose you have two tensors, where y_hat contains computed scores for each class (for example, from y = W*x +b) and y_true contains one-hot encoded true labels.

y_hat  = ... # Predicted label, e.g. y = tf.matmul(X, W) + b
y_true = ... # True label, one-hot encoded

If you interpret the scores in y_hat as unnormalized log probabilities, then they are logits.

Additionally, the total cross-entropy loss computed in this manner:

y_hat_softmax = tf.nn.softmax(y_hat)
total_loss = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), [1]))

is essentially equivalent to the total cross-entropy loss computed with the function softmax_cross_entropy_with_logits():

total_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))

Long version:

In the output layer of your neural network, you will probably compute an array that contains the class scores for each of your training instances, such as from a computation y_hat = W*x + b. To serve as an example, below I've created a y_hat as a 2 x 3 array, where the rows correspond to the training instances and the columns correspond to classes. So here there are 2 training instances and 3 classes.

import tensorflow as tf
import numpy as np

sess = tf.Session()

# Create example y_hat.
y_hat = tf.convert_to_tensor(np.array([[0.5, 1.5, 0.1],[2.2, 1.3, 1.7]]))
sess.run(y_hat)
# array([[ 0.5,  1.5,  0.1],
#        [ 2.2,  1.3,  1.7]])

Note that the values are not normalized (i.e. the rows don't add up to 1). In order to normalize them, we can apply the softmax function, which interprets the input as unnormalized log probabilities (aka logits) and outputs normalized linear probabilities.

y_hat_softmax = tf.nn.softmax(y_hat)
sess.run(y_hat_softmax)
# array([[ 0.227863  ,  0.61939586,  0.15274114],
#        [ 0.49674623,  0.20196195,  0.30129182]])

It's important to fully understand what the softmax output is saying. Below I've shown a table that more clearly represents the output above. It can be seen that, for example, the probability of training instance 1 being "Class 2" is 0.619. The class probabilities for each training instance are normalized, so the sum of each row is 1.0.

                      Pr(Class 1)  Pr(Class 2)  Pr(Class 3)
                    ,--------------------------------------
Training instance 1 | 0.227863   | 0.61939586 | 0.15274114
Training instance 2 | 0.49674623 | 0.20196195 | 0.30129182

So now we have class probabilities for each training instance, where we can take the argmax() of each row to generate a final classification. From above, we may generate that training instance 1 belongs to "Class 2" and training instance 2 belongs to "Class 1".

Are these classifications correct? We need to measure against the true labels from the training set. You will need a one-hot encoded y_true array, where again the rows are training instances and columns are classes. Below I've created an example y_true one-hot array where the true label for training instance 1 is "Class 2" and the true label for training instance 2 is "Class 3".

y_true = tf.convert_to_tensor(np.array([[0.0, 1.0, 0.0],[0.0, 0.0, 1.0]]))
sess.run(y_true)
# array([[ 0.,  1.,  0.],
#        [ 0.,  0.,  1.]])

Is the probability distribution in y_hat_softmax close to the probability distribution in y_true? We can use cross-entropy loss to measure the error.

Formula for cross-entropy loss

We can compute the cross-entropy loss on a row-wise basis and see the results. Below we can see that training instance 1 has a loss of 0.479, while training instance 2 has a higher loss of 1.200. This result makes sense because in our example above, y_hat_softmax showed that training instance 1's highest probability was for "Class 2", which matches training instance 1 in y_true; however, the prediction for training instance 2 showed a highest probability for "Class 1", which does not match the true class "Class 3".

loss_per_instance_1 = -tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1])
sess.run(loss_per_instance_1)
# array([ 0.4790107 ,  1.19967598])

What we really want is the total loss over all the training instances. So we can compute:

total_loss_1 = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1]))
sess.run(total_loss_1)
# 0.83934333897877944

Using softmax_cross_entropy_with_logits()

We can instead compute the total cross entropy loss using the tf.nn.softmax_cross_entropy_with_logits() function, as shown below.

loss_per_instance_2 = tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true)
sess.run(loss_per_instance_2)
# array([ 0.4790107 ,  1.19967598])

total_loss_2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))
sess.run(total_loss_2)
# 0.83934333897877922

Note that total_loss_1 and total_loss_2 produce essentially equivalent results with some small differences in the very final digits. However, you might as well use the second approach: it takes one less line of code and accumulates less numerical error because the softmax is done for you inside of softmax_cross_entropy_with_logits().

PHP Pass variable to next page

**page 1**
<form action="exapmple.php?variable_name=$value" method="POST"> 
    <button>
        <input  type="hidden" name="x">
    </button>
</form>`

page 2

if(isset($_POST['x'])) {
    $new_value=$_GET['variable_name'];
}

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Convert a list to a string in C#

The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.

You could try something like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)

What is Type-safe?

Concept:

To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like

  1. no wrong data type e.g. can't save or initialized a variable of string type with integer
  2. Out of bound indexes are not accessible
  3. Allow only the specific memory location

so it is all about the safety of the types of your storage in terms of variables.

How to set default Checked in checkbox ReactJS?

If the checkbox is created only with React.createElement then the property defaultChecked is used.

React.createElement('input',{type: 'checkbox', defaultChecked: false});

Credit to @nash_ag

Find the min/max element of an array in JavaScript

You can use lodash's methods

_.max([4, 2, 8, 6]);
returns => 8

https://lodash.com/docs/4.17.15#max

_.min([4, 2, 8, 6]);
returns => 2

https://lodash.com/docs/4.17.15#min

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

Paste a multi-line Java String in Eclipse

See: Multiple-line-syntax

It also support variables in multiline string, for example:

String name="zzg";
String lines = ""/**~!{
    SELECT * 
        FROM user
        WHERE name="$name"
}*/;
System.out.println(lines);

Output:

SELECT * 
    FROM user
    WHERE name="zzg"

Does JavaScript have the interface type (such as Java's 'interface')?

Javascript does not have interfaces. But it can be duck-typed, an example can be found here:

http://reinsbrain.blogspot.com/2008/10/interface-in-javascript.html

Set start value for column with autoincrement

Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:

SET IDENTITY_INSERT Orders ON

-- do inserts here

SET IDENTITY_INSERT Orders OFF

This insert will reset the identity to the last inserted value. From MSDN:

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

AngularJS: How do I manually set input to $valid in controller?

The answers above didn't help me solve my problem. After a long search I bumped into this partial solution.

I've finally solved my problem with this code to set the input field manually to ng-invalid (to set to ng-valid set it to 'true'):

$scope.myForm.inputName.$setValidity('required', false);

Rename Oracle Table or View

ALTER TABLE mytable RENAME TO othertable

In Oracle 10g also:

RENAME mytable TO othertable

How can I check if a View exists in a Database?

IN SQL Server ,

declare @ViewName nvarchar(20)='ViewNameExample'

if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
begin
    -- Your SQL Code goes here ...

end

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

I had same problem, the solution was so easy

Right click on solotion install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"

boom that's it ;)

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

PHP Session data not being saved

A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.

I've had this issue before where I had a blank line before session_start() which caused it not to work properly.

C++ Boost: undefined reference to boost::system::generic_category()

This answer actually helped when using Boost and cmake.

Adding add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY) for cmake file.

My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.12)
project(proj)

set(CMAKE_CXX_STANDARD 17)


set(SHARED_DIR "${CMAKE_SOURCE_DIR}/../shared")

set(BOOST_LATEST_DIR            "${SHARED_DIR}/boost_1_68_0")
set(BOOST_LATEST_BIN_DIR        "${BOOST_LATEST_DIR}/stage/lib")
set(BOOST_LATEST_INCLUDE_DIR    "${BOOST_LATEST_DIR}/boost")
set(BOOST_SYSTEM                "${BOOST_LATEST_BIN_DIR}/libboost_system.so")
set(BOOST_FS                    "${BOOST_LATEST_BIN_DIR}/libboost_filesystem.so")
set(BOOST_THREAD                "${BOOST_LATEST_BIN_DIR}/libboost_thread.so")

set(HYRISE_SQL_PARSER_DIR           "${SHARED_DIR}/hyrise_sql_parser")
set(HYRISE_SQL_PARSER_BIN_DIR       "${HYRISE_SQL_PARSER_DIR}")
set(HYRISE_SQL_PARSER_INCLUDE_DIR   "${HYRISE_SQL_PARSER_DIR}/src")
set(HYRISE_SQLPARSER                "${HYRISE_SQL_PARSER_BIN_DIR}/libsqlparser.so")


include_directories(${CMAKE_SOURCE_DIR} ${BOOST_LATEST_INCLUDE_DIR} ${HYRISE_SQL_PARSER_INCLUDE_DIR})

set(BOOST_LIBRARYDIR "/usr/lib/x86_64-linux-gnu/")
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)

find_package(Boost 1.68.0 REQUIRED COMPONENTS system thread filesystem)

add_executable(proj main.cpp row/row.cpp row/row.h table/table.cpp table/table.h page/page.cpp page/page.h
        processor/processor.cpp processor/processor.h engine_instance.cpp engine_instance.h utils.h
        meta_command.h terminal/terminal.cpp terminal/terminal.h)


if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(proj PUBLIC Boost::system Boost::filesystem Boost::thread ${HYRISE_SQLPARSER})
endif()

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

Same issue presented. My solution was to put the correct storyboard value in the Main Storyboard drop down. I had renamed mainstoryboard.storyboard, but not reset the deployment info.

C# Connecting Through Proxy

            var getHtmlWeb = new HtmlWeb() { AutoDetectEncoding = false, OverrideEncoding = Encoding.GetEncoding("iso-8859-2") };

            WebProxy myproxy = new WebProxy("127.0.0.1:8888", false);
            NetworkCredential cred = (NetworkCredential)CredentialCache.DefaultCredentials;
            var document = getHtmlWeb.Load("URL", "GET", myproxy, cred);

How to develop Desktop Apps using HTML/CSS/JavaScript?

It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.

One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.

You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.

How do I generate a random number between two variables that I have stored?

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

Hope this helps - Luke

Remove all occurrences of a value from a list?

hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
     if hello[item] == ' ': 
#if there is a match, rebuild the list with the list before the item + the list after the item
         hello = hello[:item] + hello [item + 1:]
print hello

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Returning binary file from controller in ASP.NET Web API

You could try

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

Adding a css class to select using @Html.DropDownList()

There are some options in constructors look, if you don't have dropdownList and you wanna insert CSS class you can use like

@Html.DropDownList("Country", null, "Choose-Category", new {@class="form-control"})

in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class if you don't wanna select any default option so simple replace "Choose-Category" with ""

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

Swift: Sort array of objects alphabetically

Sorted array Swift 4.2

arrayOfRaces = arrayOfItems.sorted(by: { ($0["raceName"] as! String) < ($1["raceName"] as! String) })

SQL Server : fetching records between two dates?

Your question didnt ask how to use BETWEEN correctly, rather asked for help with the unexpectedly truncated results...

As mentioned/hinting at in the other answers, the problem is that you have time segments in addition to the dates.

In my experience, using date diff is worth the extra wear/tear on the keyboard. It allows you to express exactly what you want, and you are covered.

select * 
from xxx 
where datediff(d, '2012-10-26', dates) >=0
and  datediff(d, dates,'2012-10-27') >=0

using datediff, if the first date is before the second date, you get a positive number. There are several ways to write the above, for instance always having the field first, then the constant. Just flipping the operator. Its a matter of personal preference.

you can be explicit about whether you want to be inclusive or exclusive of the endpoints by dropping one or both equal signs.

BETWEEN will work in your case, because the endpoints are both assumed to be midnight (ie DATEs). If your endpoints were also DATETIME, using BETWEEN may require even more casting. In my mind DATEDIFF was put in our lives to insulate us from those issues.

Newline character in StringBuilder

Just create an extension for the StringBuilder class:

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

Echo tab characters in bash script

If you want to use echo "a\tb" in a script, you run the script as:

# sh -e myscript.sh

Alternatively, you can give to myscript.sh the execution permission, and then run the script.

# chmod +x myscript.sh
# ./myscript.sh

PHP Warning: Module already loaded in Unknown on line 0

In my case I had uncoment the ;extension=php_curl.so in php.ini, but Ubuntu was already calling this extension somewhere else.

To find this "somewhere else", on php.ini will informe. On my case: /etc/php/7.1/apache2/conf.d/20-curl.ini was the path.

So now we edit this file (terminal):

sudo nano /etc/php/7.1/apache2/conf.d/20-curl.ini

Comment the ;extension=php_curl.so

Save file and restart apache:

sudo systemctl restart apache2

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }