Programs & Examples On #Ninject

NInject is a dependency injection framework for .NET applications.

How do the major C# DI/IoC frameworks compare?

See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.

I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.

From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.

Creating a singleton in Python

After struggling with this for some time I eventually came up with the following, so that the config object would only be loaded once, when called up from separate modules. The metaclass allows a global class instance to be stored in the builtins dict, which at present appears to be the neatest way of storing a proper program global.

import builtins

# -----------------------------------------------------------------------------
# So..... you would expect that a class would be "global" in scope, however
#   when different modules use this,
#   EACH ONE effectively has its own class namespace.  
#   In order to get around this, we use a metaclass to intercept
#   "new" and provide the "truly global metaclass instance" if it already exists

class MetaConfig(type):
    def __new__(cls, name, bases, dct):
        try:
            class_inst = builtins.CONFIG_singleton

        except AttributeError:
            class_inst = super().__new__(cls, name, bases, dct)
            builtins.CONFIG_singleton = class_inst
            class_inst.do_load()

        return class_inst

# -----------------------------------------------------------------------------

class Config(metaclass=MetaConfig):

    config_attr = None

    @classmethod
    def do_load(cls):
        ...<load-cfg-from-file>...

How to display text in pygame?

There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.

Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.

You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

how to get current location in google map android

public class MainActivity extends ActionBarActivity implements
    ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
}
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

If you cannot find the process locking the table (cause it is alreay dead), it may be a thread still cleaning up like this

section TRANSACTION of

show engine innodb status;

at the end

---TRANSACTION 1135701157, ACTIVE 6768 sec
MySQL thread id 5208136, OS thread handle 0x7f2982e91700, query id 882213399 xxxIPxxx 82.235.36.49 my_user cleaning up

as mentionned in a comment in Clear transaction deadlock?

you can try killing the transaction thread directly, here with

 KILL 5208136;

worked for me.

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

Most efficient conversion of ResultSet to JSON?

A simpler solution (based on code in question):

JSONArray json = new JSONArray();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
  int numColumns = rsmd.getColumnCount();
  JSONObject obj = new JSONObject();
  for (int i=1; i<=numColumns; i++) {
    String column_name = rsmd.getColumnName(i);
    obj.put(column_name, rs.getObject(column_name));
  }
  json.put(obj);
}
return json;

Bootstrap 4, How do I center-align a button?

you can also just wrap with an H class or P class with a text-center attribute

Can I use a min-height for table, tr or td?

The solution without div is used a pseudo element like ::after into first td in row with min-height. Save your HTML clean.

table tr td:first-child::after {
   content: "";
   display: inline-block;
   vertical-align: top;
   min-height: 60px;
}

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

How to install and use "make" in Windows?

If you're using Windows 10, it is built into the Linux subsystem feature. Just launch a Bash prompt (press the Windows key, then type bash and choose "Bash on Ubuntu on Windows"), cd to the directory you want to make and type make.

FWIW, the Windows drives are found in /mnt, e.g. C:\ drive is /mnt/c in Bash.

If Bash isn't available from your start menu, here are instructions for turning on that Windows feature (64-bit Windows only):

https://docs.microsoft.com/en-us/windows/wsl/install-win10

right click context menu for datagridview

  • Put a context menu on your form, name it, set captions etc. using the built-in editor
  • Link it to your grid using the grid property ContextMenuStrip
  • For your grid, create an event to handle CellContextMenuStripNeeded
  • The Event Args e has useful properties e.ColumnIndex, e.RowIndex.

I believe that e.RowIndex is what you are asking for.

Suggestion: when user causes your event CellContextMenuStripNeeded to fire, use e.RowIndex to get data from your grid, such as the ID. Store the ID as the menu event's tag item.

Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.

How to use both onclick and target="_blank"

The window.open method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();

}

and

onclick="Javascript: openYourRequiredPage()"

You can use

method="post"

or

method="get"

As you wish

Can I use wget to check , but not download

You can use the following option to check for the files:

wget --delete-after URL

How to preview an image before and after upload?

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

Check this Article : Using FileReader() preview image before uploading.

What is the difference between Bootstrap .container and .container-fluid classes?

Quick version: .container has one fixed width for each screen size in bootstrap (xs,sm,md,lg); .container-fluid expands to fill the available width.


The difference between container and container-fluid comes from these lines of CSS:

@media (min-width: 568px) {
  .container {
    width: 550px;
  }
}
@media (min-width: 992px) {
  .container {
    width: 970px;
  }
}
@media (min-width: 1200px) {
  .container {
    width: 1170px;
  }
}

Depending on the width of the viewport that the webpage is being viewed on, the container class gives its div a specific fixed width. These lines don't exist in any form for container-fluid, so its width changes every time the viewport width changes.

So for example, say your browser window is 1000px wide. As it's greater than the min-width of 992px, your .container element will have a width of 970px. You then slowly widen your browser window. The width of your .container won't change until you get to 1200px, at which it will jump to 1170px wide and stay that way for any larger browser widths.

Your .container-fluid element, on the other hand, will constantly resize as you make even the smallest changes to your browser width.

Close application and launch home screen on Android

I use this:

1) The parent activity call the secondary activity with the method "startActivityForResult"

2) In the secondary activity when is closing:

int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();

3) And in the parent activity override the method "onActivityResult":

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    int exitCode = 1;
    if(resultCode == exitCode) {
        super.setResult(exitCode); // use this if you have more than 2 activities
        finish();
    }
}

This works fine for me.

What does body-parser do with express?

These are all a matter of convenience.

Basically, if the question were 'Do we need to use body-parser?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.

This is kind of the same as asking 'Do we need to use express to begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.

On the surface - body-parser makes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.

How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace.

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \\s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.


To start with regular expressions here you can find a nice tutorial.

Notes

abc…    Letters
123…    Digits
\d      Any Digit
\D      Any Non-digit character
.       Any Character
\.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
\w      Any Alphanumeric character
\W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
\s      Any Whitespace
\S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

belongs_to through associations

A belongs_to association cannot have a :through option. You're better off caching the question_id on Choice and adding a unique index to the table (especially because validates_uniqueness_of is prone to race conditions).

If you're paranoid, add a custom validation to Choice that confirms that the answer's question_id matches, but it sounds like the end user should never be given the opportunity to submit data that would create this kind of mismatch.

ADB - Android - Getting the name of the current activity

dumpsys window windows gives more detail about the current activity:

adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
  mCurrentFocus=Window{41d2c970 u0 com.android.launcher/com.android.launcher2.Launcher}
  mFocusedApp=AppWindowToken{4203c170 token=Token{41b77280 ActivityRecord{41b77a28 u0 com.android.launcher/com.android.launcher2.Launcher t3}}}

However in order to find the process ID (e.g. to kill the current activity), use dumpsys activity, and grep on "top-activity":

adb shell "dumpsys activity | grep top-activity"
    Proc # 0: fore  F/A/T  trm: 0 3074:com.android.launcher/u0a8 (top-activity)

adb shell "kill 3074"

Disable asp.net button after click to prevent double clicking

Here is a solution that works for the asp.net button object. On the front end, add these attributes to your asp:Button definition:

<asp:Button ... OnClientClick="this.disabled=true;" UseSubmitBehavior="false" />

In the back end, in the click event handler method call, add this code to the end (preferably in a finally block)

myButton.Enabled = true;

Java: Best way to iterate through a Collection (here ArrayList)

None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.

The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.

Unit testing private methods in C#

In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS

Disabling user input for UITextfield in swift

In swift 5, I used following code to disable the textfield

override func viewDidLoad() {
   super.viewDidLoad()
   self.textfield.isEnabled = false
   //e.g
   self.design.isEnabled = false
}

How do implement a breadth first traversal?

Use the following algorithm to traverse in breadth first search-

  1. First add the root node into the queue with the put method.
  2. Iterate while the queue is not empty.
  3. Get the first node in the queue, and then print its value.
  4. Add both left and right children into the queue (if the current nodehas children).
  5. Done. We will print the value of each node, level by level,by poping/removing the element

Code is written below-

    Queue<TreeNode> queue= new LinkedList<>();
    private void breadthWiseTraversal(TreeNode root) {
        if(root==null){
            return;
        }
        TreeNode temp = root;
        queue.clear();
        ((LinkedList<TreeNode>) queue).add(temp);
        while(!queue.isEmpty()){
            TreeNode ref= queue.remove();
            System.out.print(ref.data+" ");
            if(ref.left!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.left);
            }
            if(ref.right!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.right);
            }
        }
    }

What are the differences between a superkey and a candidate key?

A super key is any combination of columns that uniquely identifies a row in a table. A candidate key is a super key which cannot have any columns removed from it without losing the unique identification property. This property is sometimes known as minimality or (better) irreducibility.

A super key ? a primary key in general. The primary key is simply a candidate key chosen to be the main key. However, in dependency theory, candidate keys are important and the primary key is not more important than any of the other candidate keys. Non-primary candidate keys are also known as alternative keys.

Consider this table of Elements:

CREATE TABLE elements
(
    atomic_number   INTEGER NOT NULL PRIMARY KEY
                    CHECK (atomic_number > 0 AND atomic_number < 120),
    symbol          CHAR(3) NOT NULL UNIQUE,
    name            CHAR(20) NOT NULL UNIQUE,
    atomic_weight   DECIMAL(8,4) NOT NULL,
    period          SMALLINT NOT NULL
                    CHECK (period BETWEEN 1 AND 7),
    group           CHAR(2) NOT NULL
                    -- 'L' for Lanthanoids, 'A' for Actinoids
                    CHECK (group IN ('1', '2', 'L', 'A', '3', '4', '5', '6',
                                     '7', '8', '9', '10', '11', '12', '13',
                                     '14', '15', '16', '17', '18')),
    stable          CHAR(1) DEFAULT 'Y' NOT NULL
                    CHECK (stable IN ('Y', 'N'))
);

It has three unique identifiers - atomic number, element name, and symbol. Each of these, therefore, is a candidate key. Further, unless you are dealing with a table that can only ever hold one row of data (in which case the empty set (of columns) is a candidate key), you cannot have a smaller-than-one-column candidate key, so the candidate keys are irreducible.

Consider a key made up of { atomic number, element name, symbol }. If you supply a consistent set of values for these three fields (say { 6, Carbon, C }), then you uniquely identify the entry for an element - Carbon. However, this is very much a super key that is not a candidate key because it is not irreducible; you can eliminate any two of the three fields without losing the unique identification property.

As another example, consider a key made up of { atomic number, period, group }. Again, this is a unique identifier for a row; { 6, 2, 14 } identifies Carbon (again). If it were not for the Lanthanoids and Actinoids, then the combination of { period, group } would be unique, but because of them, it is not. However, as before, atomic number on its own is sufficient to uniquely identify an element, so this is a super key and not a candidate key.

Property getters and setters

In order to override setter and getter for swift variables use the below given code

var temX : Int? 
var x: Int?{

    set(newX){
       temX = newX
    }

    get{
        return temX
    }
}

We need to keep the value of variable in a temporary variable, since trying to access the same variable whose getter/setter is being overridden will result in infinite loops.

We can invoke the setter simply like this

x = 10

Getter will be invoked on firing below given line of code

var newVar = x

NodeJS w/Express Error: Cannot GET /

var path = require('path');

Change app.use(express.static(__dirname + '/default.htm')); to app.use(express.static(path.join(__dirname + '/default.htm')));.

Also, make sure you point it to the right path of you default.html.

Docker: Multiple Dockerfiles in project

Author Note

This answer is out of date. Fig not longer exists and has been replaced by Docker compose. Accepted answers cannot be deleted ....

Docker Compose supports the building of project hierachy. So it's now easy to support a Dockerfile in each sub directory.

+-- docker-compose.yml
+-- project1
¦   +-- Dockerfile
+-- project2
    +-- Dockerfile

Original answer

I just create a directory containing a Dockerfile for each component. Example:

When building the containers just give the directory name and Docker will select the correct Dockerfile.

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

How do I delete multiple rows in Entity Framework (without foreach)

For anyone using EF5, following extension library can be used: https://github.com/loresoft/EntityFramework.Extended

context.Widgets.Delete(w => w.WidgetId == widgetId);

HTML anchor link - href and onclick both?

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

iPhone viewWillAppear not firing

I'm not 100% sure on this, but I think that adding a view to the view hierarchy directly means calling -addSubview: on the view controller's view (e.g., [viewController.view addSubview:anotherViewController.view]) instead of pushing a new view controller onto the navigation controller's stack.

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Press ENTER to change working directory

InstallUtil.exe C:\MyService\Release\ReminderService.exe

Press ENTER

How do I get the Git commit count?

The following command prints the total number of commits on the current branch.

git shortlog -s -n  | awk '{ sum += $1; } END { print sum; }' "$@"

It is made up of two parts:

  1. Print the total logs number grouped by author (git shortlog -s -n)

    Example output

      1445  John C
      1398  Tom D
      1376  Chrsitopher P
       166  Justin T
       166  You
    
  2. Sum up the total commit number of each author, i.e. the first argument of each line, and print the result out (awk '{ sum += $1; } END { print sum; }' "$@")

    Using the same example as above it will sum up 1445 + 1398 + 1376 + 166 + 166. Therefore the output will be:

      4,551
    

How do you append rows to a table using jQuery?

I always use this code below for more readable

$('table').append([
'<tr>',
    '<td>My Item 1</td>',
    '<td>My Item 2</td>',
    '<td>My Item 3</td>',
    '<td>My Item 4</td>',
'</tr>'
].join(''));

or if it have tbody

$('table').find('tbody').append([
'<tr>',
    '<td>My Item 1</td>',
    '<td>My Item 2</td>',
    '<td>My Item 3</td>',
    '<td>My Item 4</td>',
'</tr>'
].join(''));

Accessing certain pixel RGB value in openCV

The current version allows the cv::Mat::at function to handle 3 dimensions. So for a Mat object m, m.at<uchar>(0,0,0) should work.

How do you install an APK file in the Android emulator?

I might be wrong, but on Windows I simply drag and drop the .apk into Android Emulator. I mean, doing all mentioned above seems to be a lot of work.

In laymans terms, what does 'static' mean in Java?

The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.

Java is an object oriented language and by default most code that you write requires an instance of the object to be used.

public class SomeObject {
    public int someField;
    public void someMethod() { };
    public Class SomeInnerClass { };
}

In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObject anInstance = new SomeObject();
        anInstance.someField = 7;
        anInstance.someMethod();
        //Non-static inner classes are usually not created outside of the
        //class instance so you don't normally see this syntax
        SomeInnerClass blah = anInstance.new SomeInnerClass();
    }
}

If I declare those things static then they do not require an enclosing instance.

public class SomeObjectWithStaticStuff {
    public static int someField;
    public static void someMethod() { };
    public static Class SomeInnerClass { };
}

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someMethod();
        SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
        //Or you can also do this if your imports are correct
        SomeInnerClass blah2 = new SomeInnerClass();
    }
}

Declaring something static has several implications.

First, there can only ever one value of a static field throughout your entire application.

public class SomeOtherObject {
    public void doSomeStuff() {
        //Two objects, two different values
        SomeObject instanceOne = new SomeObject();
        SomeObject instanceTwo = new SomeObject();
        instanceOne.someField = 7;
        instanceTwo.someField = 10;
        //Static object, only ever one value
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
    }
}

The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).

public class SomeObjectWithStaticStuff {
    private int nonStaticField;
    private void nonStaticMethod() { };

    public static void someStaticMethod() {
        nonStaticField = 7; //Not allowed
        this.nonStaticField = 7; //Not allowed, can never use *this* in static
        nonStaticMethod(); //Not allowed
        super.someSuperMethod(); //Not allowed, can never use *super* in static
    }

    public static class SomeStaticInnerClass {

        public void doStuff() {
            someStaticField = 7; //Not allowed
            nonStaticMethod(); //Not allowed
            someStaticMethod(); //This is ok
        }

    }
}

The static keyword can also be applied to inner interfaces, annotations, and enums.

public class SomeObject {
    public static interface SomeInterface { };
    public static @interface SomeAnnotation { };
    public static enum SomeEnum { };
}

In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.

This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?

There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.

//SomeStaticThing.java
public class SomeStaticThing {
    public static int StaticCounterOne = 0;
}

//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
    public static int StaticCounterTwo = 0;
}

//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;

public class SomeOtherClass {
    public void doStuff() {
        StaticCounterOne++; //Ok
        StaticCounterTwo++; //Not ok
        SomeOtherStaticThing.StaticCounterTwo++; //Ok
    }
}

Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.

public class SomeObject {

    private static int x;

    static {
        x = 7;
    }
}

How to send an email from JavaScript

_x000D_
_x000D_
function send() {_x000D_
  setTimeout(function() {_x000D_
    window.open("mailto:" + document.getElementById('email').value + "?subject=" + document.getElementById('subject').value + "&body=" + document.getElementById('message').value);_x000D_
  }, 320);_x000D_
}
_x000D_
input {_x000D_
  text-align: center;_x000D_
  border-top: none;_x000D_
  border-right: none;_x000D_
  border-left: none;_x000D_
  height: 10vw;_x000D_
  font-size: 2vw;_x000D_
  width: 100vw;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
  text-align: center;_x000D_
  border-top: none;_x000D_
  border-right: none;_x000D_
  border-left: none;_x000D_
  border-radius: 5px;_x000D_
  width: 100vw;_x000D_
  height: 50vh;_x000D_
  font-size: 2vw;_x000D_
}_x000D_
_x000D_
button {_x000D_
  border: none;_x000D_
  background-color: white;_x000D_
  position: fixed;_x000D_
  right: 5px;_x000D_
  top: 5px;_x000D_
  transition: transform .5s;_x000D_
}_x000D_
_x000D_
input:focus {_x000D_
  outline: none;_x000D_
  color: orange;_x000D_
  border-radius: 3px;_x000D_
}_x000D_
_x000D_
textarea:focus {_x000D_
  outline: none;_x000D_
  color: orange;_x000D_
  border-radius: 7px;_x000D_
}_x000D_
_x000D_
button:focus {_x000D_
  outline: none;_x000D_
  transform: scale(0);_x000D_
  transform: rotate(360deg);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Send Email</title>_x000D_
</head>_x000D_
_x000D_
<body align=center>_x000D_
  <input id="email" type="email" placeholder="[email protected]"></input><br><br>_x000D_
  <input id="subject" placeholder="Subject"></input><br>_x000D_
  <textarea id="message" placeholder="Message"></textarea><br>_x000D_
  <button id="send" onclick="send()"><img src=https://www.dropbox.com/s/chxcszvnrdjh1zm/send.png?dl=1 width=50px height=50px></img></button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Detach (move) subdirectory into separate Git repository

The original question wants XYZ/ABC/(*files) to become ABC/ABC/(*files). After implementing the accepted answer for my own code, I noticed that it actually changes XYZ/ABC/(*files) into ABC/(*files). The filter-branch man page even says,

The result will contain that directory (and only that) as its project root."

In other words, it promotes the top-level folder "up" one level. That's an important distinction because, for example, in my history I had renamed a top-level folder. By promoting folders "up" one level, git loses continuity at the commit where I did the rename.

I lost contiuity after filter-branch

My answer to the question then is to make 2 copies of the repository and manually delete the folder(s) you want to keep in each. The man page backs me up with this:

[...] avoid using [this command] if a simple single commit would suffice to fix your problem

jQuery using append with effects

Having effects on append won't work because the content the browser displays is updated as soon as the div is appended. So, to combine Mark B's and Steerpike's answers:

Style the div you're appending as hidden before you actually append it. You can do it with inline or external CSS script, or just create the div as

<div id="new_div" style="display: none;"> ... </div>

Then you can chain effects to your append (demo):

$('#new_div').appendTo('#original_div').show('slow');

Or (demo):

var $new = $('#new_div');
$('#original_div').append($new);
$new.show('slow');

How to get current working directory in Java?

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();

MySQL, create a simple function

MySQL function example:

Open the mysql terminal:

el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>

Drop the function if it already exists

mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Create the function

mysql> create function hello(id INT)
    -> returns CHAR(50)
    -> return 'foobar';
Query OK, 0 rows affected (0.01 sec)

Create a simple table to test it out with

mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)

Insert three values into the table yar

mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

Select all the values from yar, run our function hello each time:

mysql> select id, hello(5) from yar;
+------+----------+
| id   | hello(5) |
+------+----------+
|    5 | foobar   |
|    7 | foobar   |
|    9 | foobar   |
+------+----------+
3 rows in set (0.01 sec)

Verbalize and internalize what just happened:

You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50) containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5) for each row returned by yar.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

When trying to translate Excel file with .xlsx suffix, you need to add additional jar, xmlbeansxxx.jar. xxxx is version, such as xmlbeans-2.3.0.jar

How to check if a symlink exists

Maybe this is what you are looking for. To check if a file exist and is not a link.

Try this command:

file="/usr/mda" 
[ -f $file ] && [ ! -L $file ] && echo "$file exists and is not a symlink"

SQL Server - transactions roll back on error?

Here the code with getting the error message working with MSSQL Server 2016:

BEGIN TRY
    BEGIN TRANSACTION 
        -- Do your stuff that might fail here
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN

        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
        DECLARE @ErrorState INT = ERROR_STATE()

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH

When to use dynamic vs. static libraries

If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables. Otherwise, definitely make it static.

There are several disadvantages of using a dll. There is additional overhead for loading and unloading it. There is also an additional dependency. If you change the dll to make it incompatible with your executalbes, they will stop working. On the other hand, if you change a static library, your compiled executables using the old version will not be affected.

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

How can javascript upload a blob?

I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.

Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

How to copy a file to another path?

I tried to copy an xml file from one location to another. Here is my code:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

How to delete history of last 10 commands in shell?

history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;

Brute but functional

How to remove the URL from the printing page?

This helped me: Print page without links

@media print {
    a[href]:after {
        content: none !important;
    }
}

Why does an onclick property set with setAttribute fail to work in IE?

function CheckBrowser(){
    if(navigator.userAgent.match(/Android/i)!=null||
        navigator.userAgent.match(/BlackBerry/i)!=null||
        navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||
        navigator.userAgent.match(/Nokia/i)!=null||
        navigator.userAgent.match(/Opera M/i)!=null||
        navigator.userAgent.match(/Chrome/i)!=null)
        {
            return 'OTHER';
    }else{
            return 'IE';
    }
}


function AddButt(i){
    var new_butt = document.createElement('input');
    new_butt.setAttribute('type','button');
    new_butt.setAttribute('value','Delete Item');
    new_butt.setAttribute('id', 'answer_del_'+i);
    if(CheckBrowser()=='IE'){
        new_butt.setAttribute("onclick", function() { DelElemAnswer(i) });
    }else{
        new_butt.setAttribute('onclick','javascript:DelElemAnswer('+i+');');
    }
}

How to automatically generate unique id in SQL like UID12345678?

Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

How to pass multiple parameters in json format to a web service using jquery?

This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:

data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"

Make sure your JSON is properly formed?

How to set height property for SPAN

span { display: table-cell; height: (your-height + px); vertical-align: middle; }

For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.

$(this).attr("id") not working

Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

function showHideOther(obj){ 
    var sel = obj.options[obj.selectedIndex].value;
    var ID = obj.id;

    if (sel == 'other') { 
        $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}

rmagick gem install "Can't find Magick-config"

I had to specify version 6

brew install imagemagick@6
brew link --overwrite --force imagemagick@6

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

How can I get the ID of an element using jQuery?

$('selector').attr('id') will return the id of the first matched element. Reference.

If your matched set contains more than one element, you can use the conventional .each iterator to return an array containing each of the ids:

var retval = []
$('selector').each(function(){
  retval.push($(this).attr('id'))
})
return retval

Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map shortcut.

return $('.selector').map(function(index,dom){return dom.id})

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

How to get method parameter names?

Python 3.5+:

DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() instead

So previously:

func_args = inspect.getargspec(function).args

Now:

func_args = list(inspect.signature(function).parameters.keys())

To test:

'arg' in list(inspect.signature(function).parameters.keys())

Given that we have function 'function' which takes argument 'arg', this will evaluate as True, otherwise as False.

Example from the Python console:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
>>> import inspect
>>> 'iterable' in list(inspect.signature(sum).parameters.keys())
True

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Get query string parameters url values with jQuery / Javascript (querystring)

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

How to get base URL in Web API controller?

  1. Add a reference to System.Web using System.Web;

  2. Get the host or any other component of the url you want string host = HttpContext.Current.Request.Url.Host;

How do I load a file into the python console?

Open command prompt in the folder in which you files to be imported are present. when you type 'python', python terminal will be opened. Now you can use

import script_name
Note: no .py extension to be used while importing.
How can I open a cmd window in a specific location?

Convert int to ASCII and back in Python

What about BASE58 encoding the URL? Like for example flickr does.

# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' 
url = ''
while node_id >= 58:
    div, mod = divmod(node_id, 58)
    url = BASE58[mod] + url
    node_id = int(div)

return 'http://short.com/%s' % BASE58[node_id] + url

Turning that back into a number isn't a big deal either.

How do I change the font size of a UILabel in Swift?

In Swift 3 again...

myLabel.font = myLabel.font.withSize(18)

How to get the list of properties of a class?

I am also facing this kind of requirement.

From this discussion I got another Idea,

Obj.GetType().GetProperties()[0].Name

This is also showing the property name.

Obj.GetType().GetProperties().Count();

this showing number of properties.

Thanks to all. This is nice discussion.

Bootstrap dropdown sub menu missing

Updated 2018

The dropdown-submenu has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..

"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342

But, with a little extra CSS you can get the same functionality.

Bootstrap 4 (navbar submenu on hover)

.navbar-nav li:hover > ul.dropdown-menu {
    display: block;
}
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
}

Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)


Bootstrap 3

Here is an example that uses 3.0 RC 1: http://bootply.com/71520

Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684

CSS

.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
    margin-left:-1px;
    -webkit-border-radius:0 6px 6px 6px;
    -moz-border-radius:0 6px 6px 6px;
    border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
    display:block;
}
.dropdown-submenu>a:after {
    display:block;
    content:" ";
    float:right;
    width:0;
    height:0;
    border-color:transparent;
    border-style:solid;
    border-width:5px 0 5px 5px;
    border-left-color:#cccccc;
    margin-top:5px;
    margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
    border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
    float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
    left:-100%;
    margin-left:10px;
    -webkit-border-radius:6px 0 6px 6px;
    -moz-border-radius:6px 0 6px 6px;
    border-radius:6px 0 6px 6px;
}

Sample Markup

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">  
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
                <li class="menu-item dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li class="menu-item dropdown dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
                            <ul class="dropdown-menu">
                                <li class="menu-item ">
                                    <a href="#">Link 1</a>
                                </li>
                                <li class="menu-item dropdown dropdown-submenu">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a href="#">Link 3</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div>

P.S. - Example in navbar that adjusts left position: http://bootply.com/92442

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

Picasso v/s Imageloader v/s Fresco vs Glide

Fresco sources | off site
(-)

  • Huge size of library
  • No Callback with View, Bitmap parameters
  • SimpleDraweeView doesn't support wrap_content
  • Huge size of cache
    (+)
  • Pretty fast image loader (for small && medium images)
  • A lot of functionality(streaming, drawing tools, memory management, etc)
  • Possibility to setup directly in xml (for example round corners)
  • GIF support
  • WebP and Animated Webp support


Picasso sources | off site
(-)

  • Slow loading big images from internet into ListView
    (+)
  • Tinny size of library
  • Small size of cache
  • Simple to use
  • UI does not freeze
  • WebP support


Glide sources

(-)

  • Big size of library
    (+)
  • Tinny size of cache
  • Simple to use
  • GIF support
  • WebP support
  • Fast loading big images from internet into ListView
  • UI does not freeze
  • BitmapPool to re-use memory and thus lesser GC events


Universal Image Loader sources

(-)

  • Limited functionality (limited image processing)
  • Project support has stopped since 27.11.2015
    (+)
  • Tinny size of library
  • Simple to use

Tested by me on SGS2 (Android 4.1) (WiFi 8.43 Mbps)
Official versions for Java, not for Xamarin!
October 19 2015

I prefer to use Glide.
Read more here.
How to write cache to External Storage (SD Card) with Glide.

HTML5 validation when the input type is not "submit"

You should use form tag enclosing your inputs. And input type submit.
This works.

<form id="testform">
<input type="text" id="example" name="example"  required>
<button type="submit"  onclick="submitform()" id="save">Save</button>
</form>

Since HTML5 Validation works only with submit button you have to keep it there. You can avoid the form submission though when valid by preventing the default action by writing event handler for form.

document.getElementById('testform').onsubmit= function(e){
     e.preventDefault();
}

This will give your validation when invalid and will not submit form when valid.

How does strtok() split the string into tokens in C?

the strtok runtime function works like this

the first time you call strtok you provide a string that you want to tokenize

char s[] = "this is a string";

in the above string space seems to be a good delimiter between words so lets use that:

char* p = strtok(s, " ");

what happens now is that 's' is searched until the space character is found, the first token is returned ('this') and p points to that token (string)

in order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to your previous passed string:

p = strtok(NULL," ");

p now points to 'is'

and so on until no more spaces can be found, then the last string is returned as the last token 'string'.

more conveniently you could write it like this instead to print out all tokens:

for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
  puts(p);
}

EDIT:

If you want to store the returned values from strtok you need to copy the token to another buffer e.g. strdup(p); since the original string (pointed to by the static pointer inside strtok) is modified between iterations in order to return the token.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

Put empty value if the value does not exist or null.

value={ this.state.value || "" }

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

After much pulling out of hair I discovered that the foreach loops were the culprits. What needs to happen is to call EF but return it into an IList<T> of that target type then loop on the IList<T>.

Example:

IList<Client> clientList = from a in _dbFeed.Client.Include("Auto") select a;
foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
{
   var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
    // ...
}

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

Simply Refer this URL and download and save required dll files @ this location:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies

URL is: https://github.com/NN---/vssdk2013/find/master

View a file in a different Git branch without changing branches

git show somebranch:path/to/your/file

you can also do multiple files and have them concatenated:

git show branchA~10:fileA branchB^^:fileB

You do not have to provide the full path to the file, relative paths are acceptable e.g.:

git show branchA~10:../src/hello.c

If you want to get the file in the local directory (revert just one file) you can checkout:

git checkout somebranch^^^ -- path/to/file

load json into variable

_x000D_
_x000D_
var itens = null;_x000D_
$.getJSON("yourfile.json", function(data) {_x000D_
  itens = data;_x000D_
  itens.forEach(function(item) {_x000D_
    console.log(item);_x000D_
  });_x000D_
});_x000D_
console.log(itens);
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to sort an object array by date property?

i was able to achieve sorting using below lines:

array.sort(function(a, b)
{
   if (a.DueDate > b.DueDate) return 1;
   if (a.DueDate < b.DueDate) return -1;
})

join list of lists in python

Sadly, Python doesn't have a simple way to flatten lists. Try this:

def flatten(some_list):
    for element in some_list:
        if type(element) in (tuple, list):
            for item in flatten(element):
                yield item
        else:
            yield element

Which will recursively flatten a list; you can then do

result = []
[ result.extend(el) for el in x] 

for el in flatten(result):
      print el

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

If anyone needs to do this in Excel without VBA, here is a way:

=SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")

where colNum is the column number

And in VBA:

Function GetColumnName(colNum As Integer) As String
    Dim d As Integer
    Dim m As Integer
    Dim name As String
    d = colNum
    name = ""
    Do While (d > 0)
        m = (d - 1) Mod 26
        name = Chr(65 + m) + name
        d = Int((d - m) / 26)
    Loop
    GetColumnName = name
End Function

Error during installing HAXM, VT-X not working

If you are still having issues, try running these steps from VMware to disable credential guard. Worked for me, finally. Steps and link are posted below, not taking credit for them.

Original content from https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2146361

To disable Device Guard or Credential Guard on Itanium based computers:

  1. Disable the group policy setting that was used to enable Credential Guard.

    On the host operating system, click Start > Run, type gpedit.msc, and click Ok. The Local group Policy Editor opens.

    Go to Local Computer Policy > Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security.

    Select Disabled.

  2. Go to Control Panel > Programs and Features > Turn Windows features on or off to turn off Hyper-V. [ remove a program on Windows 8 or earlier]

  3. Select Do not restart.

  4. Delete the related EFI variables by launching a command prompt on the host machine using an Administrator account and run these commands:

    enter code here

    mountvol X: /s

    copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y

    bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"

    bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:

    mountvol X: /d

Note: Ensure X is an unused drive, else change to another drive.

  1. Restart the host.

  2. Accept the prompt on the boot screen to disable Device Guard or Credential Guard.

You should be able to install and start HAXM now

Best way to format if statement with multiple conditions

The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.

I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".

If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line

Eg.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}

How do I get the number of days between two dates in JavaScript?

I found this question when I want do some calculate on two date, but the date have hours and minutes value, I modified @michael-liu 's answer to fit my requirement, and it passed my test.

diff days 2012-12-31 23:00 and 2013-01-01 01:00 should equal 1. (2 hour) diff days 2012-12-31 01:00 and 2013-01-01 23:00 should equal 1. (46 hour)

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
    return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}

How do I correctly clean up a Python object?

It seems that the idiomatic way to do this is to provide a close() method (or similar), and call it explicitely.

Double decimal formatting in Java

With Java 8, you can use format method..: -

System.out.format("%.2f", 4.0); // OR

System.out.printf("%.2f", 4.0); 
  • f is used for floating point value..
  • 2 after decimal denotes, number of decimal places after .

For most Java versions, you can use DecimalFormat: -

    DecimalFormat formatter = new DecimalFormat("#0.00");
    double d = 4.0;
    System.out.println(formatter.format(d));

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Array vs. Object efficiency in JavaScript

The short version: Arrays are mostly faster than objects. But there is no 100% correct solution.

Update 2017 - Test and Results

var a1 = [{id: 29938, name: 'name1'}, {id: 32994, name: 'name1'}];

var a2 = [];
a2[29938] = {id: 29938, name: 'name1'};
a2[32994] = {id: 32994, name: 'name1'};

var o = {};
o['29938'] = {id: 29938, name: 'name1'};
o['32994'] = {id: 32994, name: 'name1'};

for (var f = 0; f < 2000; f++) {
    var newNo = Math.floor(Math.random()*60000+10000);
    if (!o[newNo.toString()]) o[newNo.toString()] = {id: newNo, name: 'test'};
    if (!a2[newNo]) a2[newNo] = {id: newNo, name: 'test' };
    a1.push({id: newNo, name: 'test'});
}

test setup test results

Original Post - Explanation

There are some misconceptions in your question.

There are no associative arrays in Javascript. Only Arrays and Objects.

These are arrays:

var a1 = [1, 2, 3];
var a2 = ["a", "b", "c"];
var a3 = [];
a3[0] = "a";
a3[1] = "b";
a3[2] = "c";

This is an array, too:

var a3 = [];
a3[29938] = "a";
a3[32994] = "b";

It's basically an array with holes in it, because every array does have continous indexing. It's slower than arrays without holes. But iterating manually through the array is even slower (mostly).

This is an object:

var a3 = {};
a3[29938] = "a";
a3[32994] = "b";

Here is a performance test of three possibilities:

Lookup Array vs Holey Array vs Object Performance Test

An excellent read about these topics at Smashing Magazine: Writing fast memory efficient JavaScript

What's wrong with foreign keys?

Bigger question is: would you drive with a blindfold on? That’s how it is if you develop a system without referential constraints. Keep in mind, that business requirements change, application design changes, respective logical assumptions in the code changes, logic itself can be refactored, and so on. In general, constraints in databases are put in place under contemporary logical assumptions, seemingly correct for particular set of logical assertions and assumptions.

Through the lifecycle of an application, referential and data checks constraints police data collection via the application, especially when new requirements drive logical application changes.

To the subject of this listing - a foreign key does not by itself "improve performance", nor does it "degrade performance" significantly from a standpoint of real-time transaction processing system. However, there is an aggregated cost for constraint checking in HIGH volume "batch" system. So, here is the difference, real-time vs. batch transaction process; batch processing - where aggreated cost, incured by constraint checks, of a sequentially processed batch poses a performance hit.

In a well designed system, data consistency checks would be done "before" processing a batch through (nevertheless, there is a cost associated here also); therefore, foreign key constraint checks are not required during load time. In fact all constraints, including foreign key, should be temporarily disabled till the batch is processed.

QUERY PERFORMANCE - if tables are joined on foreign keys, be cognizant of the fact that foreign key columns are NOT INDEXED (though the respective primary key is indexed by definition). By indexing a foreign key, for that matter, by indexing any key, and joining tables on indexed helps with better performances, not by joining on non-indexed key with foreign key constraint on it.

Changing subjects, if a database is just supporting website display/rendering content/etc and recording clicks, then a database with full constraints on all tables is over kill for such purposes. Think about it. Most websites don’t even use a database for such. For similar requirements, where data is just being recorded and not referenced per say, use an in-memory database, which does not have constraints. This doesn’t mean that there is no data model, yes logical model, but no physical data model.

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

dotnet ef not found in .NET Core 3

For everyone using .NET Core CLI on MinGW MSYS. After installing using

dotnet tool install --global dotnet-ef

add this line to to bashrc file c:\msys64\home\username\ .bashrc (location depend on your setup)

export PATH=$PATH:/c/Users/username/.dotnet/tools

Getting attributes of a class

Try the inspect module. getmembers and the various tests should be helpful.

EDIT:

For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

It's even easier than everything suggested above. Data attributes in MVC which include dashes (-) are catered for with the use of underscore (_).

<%= Html.ActionLink("« Previous", "Search",
 new { keyword = Model.Keyword, page = Model.currPage - 1},
 new { @class = "prev", data_details = "Some Details"   })%>

I see JohnnyO already mentioned this.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

You can use this

if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) 
    {
        // for iOS 8
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [application registerForRemoteNotifications];
    }
    else
    {
        // for iOS < 8
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

    // RESET THE BADGE COUNT 
    application.applicationIconBadgeNumber = 0;

Open terminal here in Mac OS finder

If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items. I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):


on main(filelist)
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end main

Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.

How to convert int to float in python?

You can just multiply 1.0

>>> 1.0*144/314
0.4585987261146497

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

It is a RAM related issue. The documentation is self explanatory:

You are trying to allocate >3GB of RAM to the VM. This requires: (a) a 64 bit host system; and (b) true hardware pass-through ie VT-x.

Fast solution

Allocate less than 3GB for the virtual machine.

Complete solution

  1. Make sure your system is 64 bit.
  2. Enable virtualisation in your host machine. You can find how to do it here or there are many other resources available on Google.

Is it possible to Turn page programmatically in UIPageViewController?

This code worked nicely for me, thanks.

This is what i did with it. Some methods for stepping forward or backwards and one for going directly to a particular page. Its for a 6 page document in portrait view. It will work ok if you paste it into the implementation of the RootController of the pageViewController template.

-(IBAction)pageGoto:(id)sender {

    //get page to go to
    NSUInteger pageToGoTo = 4;

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers   objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //get the page(s) to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo - 1) storyboard:self.storyboard];

    DataViewController *secondPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, secondPageViewController, nil];


    //check which direction to animate page turn then turn page accordingly
    if (retreivedIndex < (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
    }

    if (retreivedIndex > (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
    }

}


-(IBAction)pageFoward:(id)sender {

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex < 5){

        //get the page to go to
        DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex + 1) storyboard:self.storyboard];

        //put it(or them if in landscape view) in an array
        NSArray *theViewControllers = nil;    
        theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

        //add page view
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    }

}


-(IBAction)pageBack:(id)sender {


    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex > 0){

    //get the page to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex - 1) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

    //add page view
    [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];

    }

}

Download files in laravel using Response::download

File downloads are super simple in Laravel 5.

As @Ashwani mentioned Laravel 5 allows file downloads with response()->download() to return file for download. We no longer need to mess with any headers. To return a file we simply:

return response()->download(public_path('file_path/from_public_dir.pdf'));

from within the controller.


Reusable Download Route/Controller

Now let's make a reusable file download route and controller so we can server up any file in our public/files directory.

Create the controller:

php artisan make:controller --plain DownloadsController

Create the route in app/Http/routes.php:

Route::get('/download/{file}', 'DownloadsController@download');

Make download method in app/Http/Controllers/DownloadsController:

class DownloadsController extends Controller
{
  public function download($file_name) {
    $file_path = public_path('files/'.$file_name);
    return response()->download($file_path);
  }
}

Now simply drops some files in the public/files directory and you can server them up by linking to /download/filename.ext:

<a href="/download/filename.ext">File Name</a> // update to your own "filename.ext"

If you pulled in Laravel Collective's Html package you can use the Html facade:

{!! Html::link('download/filename.ext', 'File Name') !!}

How do I jump to a closing bracket in Visual Studio Code?

The shortcut is:

Windows/English Ctrl+Shift+\

Windows/German Ctrl+Shift+^

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

Remove a JSON attribute

Simple:

delete myObj.test.key1;

CodeIgniter - how to catch DB errors?

I have created an simple library for that:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class exceptions {

    public function checkForError() {
        get_instance()->load->database();
        $error = get_instance()->db->error();
        if ($error['code'])
            throw new MySQLException($error);
    }
}

abstract class UserException extends Exception {
    public abstract function getUserMessage();
}

class MySQLException extends UserException {
    private $errorNumber;
    private $errorMessage;

    public function __construct(array $error) {
        $this->errorNumber = "Error Code(" . $error['code'] . ")";
        $this->errorMessage = $error['message'];
    }

    public function getUserMessage() {
        return array(
            "error" => array (
                "code" => $this->errorNumber,
                "message" => $this->errorMessage
            )
        );
    }

}

The example query:

function insertId($id){
    $data = array(
        'id' => $id,
    );

    $this->db->insert('test', $data);
    $this->exceptions->checkForError();
    return $this->db->insert_id();
}

And I can catch it this way in my controller:

 try {
     $this->insertThings->insertId("1");
 } catch (UserException $error){
     //do whatever you want when there is an mysql error

 }

Java: Retrieving an element from a HashSet

One of the easiest ways is to convert to Array:

for(int i = 0; i < set.size(); i++) {
    System.out.println(set.toArray()[i]);
}

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

long __builtin_expect(long EXP, long C);

This construct tells the compiler that the expression EXP most likely will have the value C. The return value is EXP. __builtin_expect is meant to be used in an conditional expression. In almost all cases will it be used in the context of boolean expressions in which case it is much more convenient to define two helper macros:

#define unlikely(expr) __builtin_expect(!!(expr), 0)
#define likely(expr) __builtin_expect(!!(expr), 1)

These macros can then be used as in

if (likely(a > 1))

Reference: https://www.akkadia.org/drepper/cpumemory.pdf

String vs. StringBuilder

String and StringBuilder are actually both immutable, the StringBuilder has built in buffers which allow its size to be managed more efficiently. When the StringBuilder needs to resize is when it is re-allocated on the heap. By default it is sized to 16 characters, you can set this in the constructor.

eg.

StringBuilder sb = new StringBuilder(50);

How to programmatically send SMS on the iPhone?

Add the MessageUI.Framework and use the following code

#import <MessageUI/MessageUI.h> 

And then:

if ([MFMessageComposeViewController canSendText]) {
  MFMessageComposeViewController *messageComposer =
  [[MFMessageComposeViewController alloc] init];
  NSString *message = @"Your Message here";
  [messageComposer setBody:message];
  messageComposer.messageComposeDelegate = self;
  [self presentViewController:messageComposer animated:YES completion:nil];
}

and the delegate method -

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
             didFinishWithResult:(MessageComposeResult)result {
      [self dismissViewControllerAnimated:YES completion:nil];
 }

Failure during conversion to COFF: file invalid or corrupt

I had this issue after installing dotnetframework4.5.
Open path below:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" ( in 64 bits machine)
or
"C:\Program Files\Microsoft Visual Studio 10.0\VC\bin" (in 32 bits machine)
In this path find file cvtres.exe and rename it to cvtres1.exe then compile your project again.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Git: Installing Git in PATH with GitHub client for Windows

GitHub for Windows does indeed install its own version of Git, but it doesn't add it to the PATH variable, which is easy enough to do. Here's instructions on how to do it:

  1. Get the Git URL

    We need to get the url of the Git \cmd directory your computer. Git is located here:

    C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd\git.exe
    

    So on your computer, replace <user> with your user and find out what the <guid> is for your computer. (The guid may change each time GitHub updates PortableGit, but they're working on a solution to that.)

    Copy it and paste it into a command prompt (right-click > paste to paste in the terminal) to verify that it works. You should see the Git help response that lists common Git commands. If you see The system cannot find the path specified. Then the URL isn’t right. Once you have it right, create the link to the directory using this format:

    ;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd
    

    (Note: \cmd at the end, not \cmd\git.exe anymore!)

    On my system, it’s this, yours will be different:

    ;C:\Users\brenton\AppData\Local\GitHub\PortableGit_7eaa494e16ae7b397b2422033as45d8ff6ac2010\cmd
    
  2. Edit the PATH Variable

    Navigate to the Environmental Variables Editor (instructions) and find the Path variable in the “System Variables” section. Click Edit… and paste the URL of Git to the end of that string. Save! It might be easier to pull this into Notepad to do the edit, just make sure you put one semicolon before you paste in the URL. If it doesn't work it’s probably because this path got messed up either with a space in there somewhere (should be no spaces around the semicolon) or a semicolon at the end (semicolons should only separate URLs, no semicolon at beginning or end of string).

If it worked, you should be able to close & reopen a terminal and type git and it will give you that same git help file. Then installing the Linter should work. (Atom > File > Settings > Packages > Linter)

Deleting Row in SQLite in Android

But the Accepted answer Not worked for me. I think String should be In SQL, strings must be quoted. So, in my case this worked for me against the accepted answer :

 database.delete(TABLE_DAILY_NOTES, WORK_ENTRY_CLUMN_NAME + "='" + workEntry+"'", null);

Understanding esModuleInterop in tsconfig file

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

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

How to install SQL Server Management Studio 2012 (SSMS) Express?

You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).

As the page states

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

So install this and use the management studio included with it.

How do I concatenate two lists in Python?

With Python 3.3+ you can use yield from:

listone = [1,2,3]
listtwo = [4,5,6]

def merge(l1, l2):
    yield from l1
    yield from l2

>>> list(merge(listone, listtwo))
[1, 2, 3, 4, 5, 6]

Or, if you want to support an arbitrary number of iterators:

def merge(*iters):
    for it in iters:
        yield from it

>>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
[1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]

How to prevent page scrolling when scrolling a DIV element?

In the solution above there is a little mistake regarding Firefox. In Firefox "DOMMouseScroll" event has no e.detail property,to get this property you should write the following 'e.originalEvent.detail'.

Here is a working solution for Firefox:

$.fn.isolatedScroll = function() {
    this.on('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.originalEvent.detail,
            bottomOverflow = (this.scrollTop + $(this).outerHeight() - this.scrollHeight) >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

How to delete an SMS from the inbox in Android programmatically?

Using suggestions from others, I think I got it to work:

(using SDK v1 R2)

It's not perfect, since i need to delete the entire conversation, but for our purposes, it's a sufficient compromise as we will at least know all messages will be looked at and verified. Our flow will probably need to then listen for the message, capture for the message we want, do a query to get the thread_id of the recently inbounded message and do the delete() call.

In our Activity:

Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null); 
int id = c.getInt(0);
int thread_id = c.getInt(1); //get the thread_id
getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread_id),null,null);

Note: I wasn't able to do a delete on content://sms/inbox/ or content://sms/all/

Looks like the thread takes precedence, which makes sense, but the error message only emboldened me to be angrier. When trying the delete on sms/inbox/ or sms/all/, you will probably get:

java.lang.IllegalArgumentException: Unknown URL
    at com.android.providers.telephony.SmsProvider.delete(SmsProvider.java:510)
    at android.content.ContentProvider$Transport.delete(ContentProvider.java:149)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:149)

For additional reference too, make sure to put this into your manifest for your intent receiver:

<receiver android:name=".intent.MySmsReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
    </intent-filter>
</receiver>

Note the receiver tag does not look like this:

<receiver android:name=".intent.MySmsReceiver" 
    android:permission="android.permission.RECEIVE_SMS">

When I had those settings, android gave me some crazy permissions exceptions that didn't allow android.phone to hand off the received SMS to my intent. So, DO NOT put that RECEIVE_SMS permission attribute in your intent! Hopefully someone wiser than me can tell me why that was the case.

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

Just found this answer from another link,

npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

The name 'controlname' does not exist in the current context

In my case I had to hunt through the 417 "controlname not found" errors to find an actual error: I had replaced a DLL but not updated the version number in the web.config. Fixed that and built successfully, 3 minutes after that all the other errors had resolved themselves.

Check if a div does NOT exist with javascript

All these answers do NOT take into account that you asked specifically about a DIV element.

document.querySelector("div#the-div-id")

@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How do I get the current location of an iframe?

I like your server side idea, even if my proposed implementation of it sounds a little bit ghetto.

You could set the .innerHTML of the iframe to the HTML contents you grab server side. Depending on how you grab this, you will have to pay attention to relative versus absolute paths.

Plus, depending on how the page you are grabbing interacts with other pages, this could totally not work (cookies being set for the page you are grabbing won't work across domains, maybe state is being tracked in Javascript... Lots of reasons this might not work.)

I don't believe that tracking the current state of the page you are trying to mirror is theoretically possible, but I'm not sure. The site could track all sorts of things server side, you won't have access to this state. Imagine the case where on a page load a variable is set to a random value server-side, how would you capture this state?

Do these ideas help with anything?

-Brian J. Stinar-

Problems when trying to load a package in R due to rJava

If you have this error in RStudio, use Lauren's environmental code above and change your R version to the 32 bit version in Tools, Global Options. There should be both 32bit and 64bit R options if you have a newer version. This will require a restart of R, and limit your memory options. Installing the 64 bit version of the jre won't be required though.

Difficulty with ng-model, ng-repeat, and inputs

I tried the solution above for my problem at it worked like a charm. Thanks!

http://jsfiddle.net/leighboone/wn9Ym/7/

Here is my version of that:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.models = [{
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }];

}

and my HTML

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
         <h1>Fun with Fields and ngModel</h1>
        <p>names: {{models}}</p>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th></th>
                    <th>Feature 1</td>
                    <th>Feature 2</th>
                    <th>Feature 3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Device</td>
                   <td ng-repeat="modelCheck in models" class=""> <span>
                                    {{modelCheck.checked}}
                                </span>

                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Which devices?</label>
                    </td>
                    <td ng-repeat="model in models">{{model.name}}
                        <input type="checkbox" class="checkbox inline" ng-model="model.checked" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

What is a superfast way to read large files line-by-line in VBA?

You can use Scripting.FileSystemObject to do that thing. From the Reference:

The ReadLine method allows a script to read individual lines in a text file. To use this method, open the text file, and then set up a Do Loop that continues until the AtEndOfStream property is True. (This simply means that you have reached the end of the file.) Within the Do Loop, call the ReadLine method, store the contents of the first line in a variable, and then perform some action. When the script loops around, it will automatically drop down a line and read the second line of the file into the variable. This will continue until each line has been read (or until the script specifically exits the loop).

And a quick example:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ServerList.txt", 1)
Do Until objFile.AtEndOfStream
 strLine = objFile.ReadLine
 MsgBox strLine
Loop
objFile.Close

How can I do string interpolation in JavaScript?

Since ES6, you can use template literals:

_x000D_
_x000D_
const age = 3_x000D_
console.log(`I'm ${age} years old!`)
_x000D_
_x000D_
_x000D_

P.S. Note the use of backticks: ``.

Why can't variables be declared in a switch statement?

Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization.

The correct way to handle this is to define a scope specific to that case statement and define your variable within it:

switch (val)
{   
case VAL:  
{
  // This will work
  int newVal = 42;  
  break;
}
case ANOTHER_VAL:  
...
break;
}

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

python
>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code

#!<path_from_which_python_command>

jQuery hasClass() - check for more than one class

here's an answer that does follow the syntax of

$(element).hasAnyOfClasses("class1","class2","class3")
(function($){
    $.fn.hasAnyOfClasses = function(){
        for(var i= 0, il=arguments.length; i<il; i++){
            if($self.hasClass(arguments[i])) return true;
        }
        return false;
    }
})(jQuery);

it's not the fastest, but its unambiguous and the solution i prefer. bench: http://jsperf.com/hasclasstest/10

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

How to add parameters to a HTTP GET request in Android?

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

How to check if an item is selected from an HTML drop down list?

I believe this is the most simple in all aspects unless you call the validate function be other means. With no/null/empty value to your first option is easier to validate. You could also eliminate the first option and start with the most popular card type.

<form name="myForm">
<select id="cardtype" name="cards">
<option value="">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

<input type="submit" name="submit" class="button" value="SUBMIT" onmouseover="validate()"></form>

<script>
function validate() {
 if (document.myform.cards.value == "") {
    alert("Please select a card type");
    document.myForm.cards.focus();
}
</script>

What is the shortcut in IntelliJ IDEA to find method / functions?

If you just want to look for methods:

On mac OS X 10.5+ binding, it is Alt + ? + O

By Default XWin Key binding, it is Shift + Ctrl + Alt + N

You can also press double SHIFT then, you can search anything (not only method, but also class, files, and actions)

How do I get the Back Button to work with an AngularJS ui-router state machine?

Note

The answers that suggest using variations of $window.history.back() have all missed a crucial part of the question: How to restore the application's state to the correct state-location as the history jumps (back/forward/refresh). With that in mind; please, read on.


Yes, it is possible to have the browser back/forward (history) and refresh whilst running a pure ui-router state-machine but it takes a bit of doing.

You need several components:

  • Unique URLs. The browser only enables the back/forward buttons when you change urls, so you must generate a unique url per visited state. These urls need not contain any state information though.

  • A Session Service. Each generated url is correlated to a particular state so you need a way to store your url-state pairs so that you can retrieve the state information after your angular app has been restarted by back / forward or refresh clicks.

  • A State History. A simple dictionary of ui-router states keyed by unique url. If you can rely on HTML5 then you can use the HTML5 History API, but if, like me, you can't then you can implement it yourself in a few lines of code (see below).

  • A Location Service. Finally, you need to be able manage both ui-router state changes, triggered internally by your code, and normal browser url changes typically triggered by the user clicking browser buttons or typing stuff into the browser bar. This can all get a bit tricky because it is easy to get confused about what triggered what.

Here is my implementation of each of these requirements. I have bundled everything up into three services:

The Session Service

class SessionService

    setStorage:(key, value) ->
        json =  if value is undefined then null else JSON.stringify value
        sessionStorage.setItem key, json

    getStorage:(key)->
        JSON.parse sessionStorage.getItem key

    clear: ->
        @setStorage(key, null) for key of sessionStorage

    stateHistory:(value=null) ->
        @accessor 'stateHistory', value

    # other properties goes here

    accessor:(name, value)->
        return @getStorage name unless value?
        @setStorage name, value

angular
.module 'app.Services'
.service 'sessionService', SessionService

This is a wrapper for the javascript sessionStorage object. I have cut it down for clarity here. For a full explanation of this please see: How do I handle page refreshing with an AngularJS Single Page Application

The State History Service

class StateHistoryService
    @$inject:['sessionService']
    constructor:(@sessionService) ->

    set:(key, state)->
        history = @sessionService.stateHistory() ? {}
        history[key] = state
        @sessionService.stateHistory history

    get:(key)->
        @sessionService.stateHistory()?[key]

angular
.module 'app.Services'
.service 'stateHistoryService', StateHistoryService

The StateHistoryService looks after the storage and retrieval of historical states keyed by generated, unique urls. It is really just a convenience wrapper for a dictionary style object.

The State Location Service

class StateLocationService
    preventCall:[]
    @$inject:['$location','$state', 'stateHistoryService']
    constructor:(@location, @state, @stateHistoryService) ->

    locationChange: ->
        return if @preventCall.pop('locationChange')?
        entry = @stateHistoryService.get @location.url()
        return unless entry?
        @preventCall.push 'stateChange'
        @state.go entry.name, entry.params, {location:false}

    stateChange: ->
        return if @preventCall.pop('stateChange')?
        entry = {name: @state.current.name, params: @state.params}
        #generate your site specific, unique url here
        url = "/#{@state.params.subscriptionUrl}/#{Math.guid().substr(0,8)}"
        @stateHistoryService.set url, entry
        @preventCall.push 'locationChange'
        @location.url url

angular
.module 'app.Services'
.service 'stateLocationService', StateLocationService

The StateLocationService handles two events:

  • locationChange. This is called when the browsers location is changed, typically when the back/forward/refresh button is pressed or when the app first starts or when the user types in a url. If a state for the current location.url exists in the StateHistoryService then it is used to restore the state via ui-router's $state.go.

  • stateChange. This is called when you move state internally. The current state's name and params are stored in the StateHistoryService keyed by a generated url. This generated url can be anything you want, it may or may not identify the state in a human readable way. In my case I am using a state param plus a randomly generated sequence of digits derived from a guid (see foot for the guid generator snippet). The generated url is displayed in the browser bar and, crucially, added to the browser's internal history stack using @location.url url. Its adding the url to the browser's history stack that enables the forward / back buttons.

The big problem with this technique is that calling @location.url url in the stateChange method will trigger the $locationChangeSuccess event and so call the locationChange method. Equally calling the @state.go from locationChange will trigger the $stateChangeSuccess event and so the stateChange method. This gets very confusing and messes up the browser history no end.

The solution is very simple. You can see the preventCall array being used as a stack (pop and push). Each time one of the methods is called it prevents the other method being called one-time-only. This technique does not interfere with the correct triggering of the $ events and keeps everything straight.

Now all we need to do is call the HistoryService methods at the appropriate time in the state transition life-cycle. This is done in the AngularJS Apps .run method, like this:

Angular app.run

angular
.module 'app', ['ui.router']
.run ($rootScope, stateLocationService) ->

    $rootScope.$on '$stateChangeSuccess', (event, toState, toParams) ->
        stateLocationService.stateChange()

    $rootScope.$on '$locationChangeSuccess', ->
        stateLocationService.locationChange()

Generate a Guid

Math.guid = ->
    s4 = -> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
    "#{s4()}#{s4()}-#{s4()}-#{s4()}-#{s4()}-#{s4()}#{s4()}#{s4()}"

With all this in place, the forward / back buttons and the refresh button all work as expected.

What's the difference between "static" and "static inline" function?

One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline functions from output by default, but will keep plain static functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline for static functions in headers.

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

How to run a function when the page is loaded?

window.onload = function() { ... etc. is not a great answer.

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

A more robust answer here:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Some code I have been using, I forget where I found it to give the author credit.

function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}

Hope this helps :)

How to output oracle sql result into a file in windows?

spool "D:\test\test.txt"

select  
  a.ename  
from  
  employee a  
inner join department b  
on  
(  
  a.dept_id = b.dept_id  
)  
;  
spool off  

This query will spool the sql result in D:\test\test.txt

Log4j, configuring a Web App to use a relative path

My suggestion is the log file should always be logged above the root context of the webApp, so in case we redeploy the webApp, we don't want to override the existing log files.

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

What's the difference between using CGFloat and float?

CGFloat is a regular float on 32-bit systems and a double on 64-bit systems

typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit

So you won't get any performance penalty.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

CURL to access a page that requires a login from a different page

After some googling I found this:

curl -c cookie.txt -d "LoginName=someuser" -d "password=somepass" https://oursite/a
curl -b cookie.txt https://oursite/b

No idea if it works, but it might lead you in the right direction.

What's the difference between :: (double colon) and -> (arrow) in PHP?

When the left part is an object instance, you use ->. Otherwise, you use ::.

This means that -> is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while :: is usually used to access static members (though in a few special cases, it's used to access instance members).

In general, :: is used for scope resolution, and it may have either a class name, parent, self, or (in PHP 5.3) static to its left. parent refers to the scope of the superclass of the class where it's used; self refers to the scope of the class where it's used; static refers to the "called scope" (see late static bindings).

The rule is that a call with :: is an instance call if and only if:

  • the target method is not declared as static and
  • there is a compatible object context at the time of the call, meaning these must be true:
    1. the call is made from a context where $this exists and
    2. the class of $this is either the class of the method being called or a subclass of it.

Example:

class A {
    public function func_instance() {
        echo "in ", __METHOD__, "\n";
    }
    public function callDynamic() {
        echo "in ", __METHOD__, "\n";
        B::dyn();
    }

}

class B extends A {
    public static $prop_static = 'B::$prop_static value';
    public $prop_instance = 'B::$prop_instance value';

    public function func_instance() {
        echo "in ", __METHOD__, "\n";
        /* this is one exception where :: is required to access an
         * instance member.
         * The super implementation of func_instance is being
         * accessed here */
        parent::func_instance();
        A::func_instance(); //same as the statement above
    }

    public static function func_static() {
        echo "in ", __METHOD__, "\n";
    }

    public function __call($name, $arguments) {
        echo "in dynamic $name (__call)", "\n";
    }

    public static function __callStatic($name, $arguments) {
        echo "in dynamic $name (__callStatic)", "\n";
    }

}

echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";

echo '$b->func_instance():', "\n", $b->func_instance(), "\n";

/* This is more tricky
 * in the first case, a static call is made because $this is an
 * instance of A, so B::dyn() is a method of an incompatible class
 */
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
 * instance of B (despite the fact we are in a method of A), so
 * B::dyn() is a method of a compatible class (namely, it's the
 * same class as the object's)
 */
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";

Output:

B::$prop_static: B::$prop_static value
B::func_static(): in B::func_static

$b->prop_instance: B::$prop_instance value
$b->func_static(): in B::func_static

$b->func_instance():
in B::func_instance
in A::func_instance
in A::func_instance

$a->dyn():
in A::callDynamic
in dynamic dyn (__callStatic)

$b->dyn():
in A::callDynamic
in dynamic dyn (__call)

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.

So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.

Wait one second in running program

Busy waiting won't be a severe drawback if it is short. In my case there was the need to give visual feedback to the user by flashing a control (it is a chart control that can be copied to clipboard, which changes its background for some milliseconds). It works fine this way:

using System.Threading;
...
Clipboard.SetImage(bm);   // some code
distribution_chart.BackColor = Color.Gray;
Application.DoEvents();   // ensure repaint, may be not needed
Thread.Sleep(50);
distribution_chart.BackColor = Color.OldLace;
....

Fastest way to check a string is alphanumeric in Java

I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6

Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2() function is marginally faster than isAlphanumeric(). One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.

public class QuickTest extends TestCase {

    private final int reps = 1000000;

    public void testRegexp() {
        for(int i = 0; i < reps; i++)
            ("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
    }

public void testIsAlphanumeric() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric("ab4r3rgf"+i);
}

public void testIsAlphanumeric2() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric2("ab4r3rgf"+i);
}

    public boolean isAlphanumeric(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isLetterOrDigit(c))
                return false;
        }

        return true;
    }

    public boolean isAlphanumeric2(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
                return false;
        }
        return true;
    }

}

IsNothing versus Is Nothing

I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".

I find this easier to read...

If printDialog IsNot Nothing Then
    'blah
End If

than this...

If Not obj Is Nothing Then
    'blah
End If

How to solve privileges issues when restore PostgreSQL Database

To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:

root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.

postgres=# \du
               List of roles
    Role name    | Attributes  | Member of
-----------------+-------------+-----------
 <user-name>    | Superuser   | {}
                 : Create DB
 postgres       | Superuser   | {}
                 : Create role
                 : Create DB

postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#

So connect to the database under a Superuser account sudo -u postgres psql and execute a ALTER ROLE <user-name> Superuser; statement.

Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

How to use subList()

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

How to create dispatch queue in Swift 3

You can create dispatch queue using this code in swift 3.0

DispatchQueue.main.async
 {
   /*Write your code here*/
 }

   /* or */

let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)                   
DispatchQueue.main.asyncAfter(deadline: delayTime)
{
  /*Write your code here*/
}

Combating AngularJS executing controller twice

In my case it was because of the url pattern I used

my url was like /ui/project/:parameter1/:parameter2.

I didn't need paramerter2 in all cases of state change. In cases where I didn't need the second parameter my url would be like /ui/project/:parameter1/. And so whenever I had a state change I will have my controller refreshed twice.

The solution was to set parameter2 as empty string and do the state change.

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

How to draw a rounded Rectangle on HTML Canvas?

I needed to do the same thing and created a method to do it.

_x000D_
_x000D_
// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Draw using default border radius, 
// stroke it but no fill (function's default values)
roundRect(ctx, 5, 5, 50, 50);
// To change the color on the rectangle, just manipulate the context
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 255, 0, .5)";
roundRect(ctx, 100, 5, 100, 100, 20, true);
// Manipulate it again
ctx.strokeStyle = "#0f0";
ctx.fillStyle = "#ddd";
// Different radii for each corner, others default to 0
roundRect(ctx, 300, 5, 200, 100, {
  tl: 50,
  br: 25
}, true);

/**
 * Draws a rounded rectangle using the current state of the canvas.
 * If you omit the last three params, it will draw a rectangle
 * outline with a 5 pixel border radius
 * @param {CanvasRenderingContext2D} ctx
 * @param {Number} x The top left x coordinate
 * @param {Number} y The top left y coordinate
 * @param {Number} width The width of the rectangle
 * @param {Number} height The height of the rectangle
 * @param {Number} [radius = 5] The corner radius; It can also be an object 
 *                 to specify different radii for corners
 * @param {Number} [radius.tl = 0] Top left
 * @param {Number} [radius.tr = 0] Top right
 * @param {Number} [radius.br = 0] Bottom right
 * @param {Number} [radius.bl = 0] Bottom left
 * @param {Boolean} [fill = false] Whether to fill the rectangle.
 * @param {Boolean} [stroke = true] Whether to stroke the rectangle.
 */
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
  if (typeof stroke === 'undefined') {
    stroke = true;
  }
  if (typeof radius === 'undefined') {
    radius = 5;
  }
  if (typeof radius === 'number') {
    radius = {tl: radius, tr: radius, br: radius, bl: radius};
  } else {
    var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0};
    for (var side in defaultRadius) {
      radius[side] = radius[side] || defaultRadius[side];
    }
  }
  ctx.beginPath();
  ctx.moveTo(x + radius.tl, y);
  ctx.lineTo(x + width - radius.tr, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
  ctx.lineTo(x + width, y + height - radius.br);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
  ctx.lineTo(x + radius.bl, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
  ctx.lineTo(x, y + radius.tl);
  ctx.quadraticCurveTo(x, y, x + radius.tl, y);
  ctx.closePath();
  if (fill) {
    ctx.fill();
  }
  if (stroke) {
    ctx.stroke();
  }

}
_x000D_
<canvas id="rounded-rect" width="500" height="200">
  <!-- Insert fallback content here -->
</canvas>
_x000D_
_x000D_
_x000D_

Git, fatal: The remote end hung up unexpectedly

You probably did clone the repository within an existing one, to solve the problem can simply clone of the repository in another directory and replicate the changes to this new directory and then run the push.

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Had this issue, but it wasn't related to the bitcode setting. I had somehow ended up with duplicate framework files in the Frameworks folder of my XCode project. I deleted all frameworks files that were red (and duplicates). This solved the "Apple Mach O, Linker Command failed with exit code 1" error.

Difference between try-catch and throw in java

All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

For more detail visit Java tutorial for beginners.

How to copy a row and insert in same table with a autoincrement field in MySQL?

This helped and it supports a BLOB/TEXT columns.

CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id=2;
UPDATE temp_table SET id=NULL WHERE id=2;
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
USE source_table;

How to set bootstrap navbar active class with Angular JS?

I use ng-class directive with $location to achieve it.

<ul class="nav">
<li data-ng-class="{active: ($location.path() == '/') }">
    <a href="#/">Carpeta Amarilla</a>
</li>
<li class="dropdown" data-ng-class="{active: ($location.path() == '/auditoria' || $location.path() == '/auditoria/todos') }">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
        Auditoria
        <b class="caret"></b>
    </a>
    <ul class="dropdown-menu pull-right">
        <li data-ng-class="{active: ($location.path() == '/auditoria') }">
            <a href="#/auditoria">Por Legajo</a>
        </li>
        <li data-ng-class="{active: ($location.path() == '/auditoria/todos') }">
            <a href="#/auditoria/todos">General</a>
        </li>
    </ul>
</li>
</ul>

It requires the navbar to be inside a main Controller with access to $location service like this:

bajasApp.controller('MenuCntl', ['$scope','$route', '$routeParams', '$location', 
   function MenuCntl($scope, $route, $routeParams, $location) {
   $scope.$route = $route;
   $scope.$location = $location;
   $scope.$routeParams = $routeParams;
}]);

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

How does one output bold text in Bash?

In order to apply a style on your string, you can use a command like:

echo -e '\033[1mYOUR_STRING\033[0m'

Explanation:

  • echo -e - The -e option means that escaped (backslashed) strings will be interpreted
  • \033 - escaped sequence represents beginning/ending of the style
  • lowercase m - indicates the end of the sequence
  • 1 - Bold attribute (see below for more)
  • [0m - resets all attributes, colors, formatting, etc.

The possible integers are:

  • 0 - Normal Style
  • 1 - Bold
  • 2 - Dim
  • 3 - Italic
  • 4 - Underlined
  • 5 - Blinking
  • 7 - Reverse
  • 8 - Invisible

What exactly is LLVM?

According to 'Getting Started With LLVM Core Libraries' book (c):

In fact, the name LLVM might refer to any of the following:

  • The LLVM project/infrastructure: This is an umbrella for several projects that, together, form a complete compiler: frontends, backends, optimizers, assemblers, linkers, libc++, compiler-rt, and a JIT engine. The word "LLVM" has this meaning, for example, in the following sentence: "LLVM is comprised of several projects".

  • An LLVM-based compiler: This is a compiler built partially or completely with the LLVM infrastructure. For example, a compiler might use LLVM for the frontend and backend but use GCC and GNU system libraries to perform the final link. LLVM has this meaning in the following sentence, for example: "I used LLVM to compile C programs to a MIPS platform".

  • LLVM libraries: This is the reusable code portion of the LLVM infrastructure. For example, LLVM has this meaning in the sentence: "My project uses LLVM to generate code through its Just-in-Time compilation framework".

  • LLVM core: The optimizations that happen at the intermediate language level and the backend algorithms form the LLVM core where the project started. LLVM has this meaning in the following sentence: "LLVM and Clang are two different projects".

  • The LLVM IR: This is the LLVM compiler intermediate representation. LLVM has this meaning when used in sentences such as "I built a frontend that translates my own language to LLVM".

Can gcc output C code after preprocessing?

cpp is the preprocessor.

Run cpp filename.c to output the preprocessed code, or better, redirect it to a file with cpp filename.c > filename.preprocessed.

What is Linux’s native GUI API?

Linux is a kernel, not a full operating system. There are different windowing systems and gui's that run on top of Linux to provide windowing. Typically X11 is the windowing system used by Linux distros.

PHP: Get key from array?


$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

MySQL query String contains

In addition to the answer from @WoLpH.

When using the LIKE keyword you also have the ability to limit which direction the string matches. For example:

If you were looking for a string that starts with your $needle:

... WHERE column LIKE '{$needle}%'

If you were looking for a string that ends with the $needle:

... WHERE column LIKE '%{$needle}'

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

How to get duplicate items from a list using LINQ?

  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

How to trigger an event after using event.preventDefault()

It is possible to use currentTarget of the event. Example shows how to proceed with form submit. Likewise you could get function from onclick attribute etc.

$('form').on('submit', function(event) {
  event.preventDefault();

  // code

  event.currentTarget.submit();
});

Android studio, gradle and NDK

If you're on unix the latest version (0.8) adds ndk-build. Here's how to add it:

android.ndk {
    moduleName "libraw"
}

It expects to find the JNI under 'src/main/jni', otherwise you can define it with:

sourceSets.main {
    jni.srcDirs = 'path'
}

As of 28 JAN 2014 with version 0.8 the build is broken on windows, you have to disable the build with:

sourceSets.main {
    jni.srcDirs = [] //disable automatic ndk-build call (currently broken for windows)
}

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

or

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

Center-align a HTML table

<table align="center"></table>

This works for me.

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Change language for bootstrap DateTimePicker

i think you have to set it in the options:

$(".form_datetime").datetimepicker({
    isRTL: false,
    format: 'dd.mm.yyyy hh:ii',
    autoclose:true,
    language: 'ru'
});

if its not working, be sure that:

$.fn.datetimepicker.dates['en'] = {
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    today: "Today"
};

is defined for 'ru'

Is null reference possible?

clang++ 3.5 even warns on it:

/tmp/a.C:3:7: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to
      always evaluate to false [-Wtautological-undefined-compare]
if( & nullReference == 0 ) // null reference
      ^~~~~~~~~~~~~    ~
1 warning generated.

Dump a mysql database to a plaintext (CSV) backup from the command line

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.

Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

How do I turn a C# object into a JSON string in .NET?

Serializer

 public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
        });
        using (var writer = new StreamWriter(filePath, append))
        {
            writer.Write(contentsToWriteToFile);
        }
}

Object

namespace MyConfig
{
    public class AppConfigurationSettings
    {
        public AppConfigurationSettings()
        {
            /* initialize the object if you want to output a new document
             * for use as a template or default settings possibly when 
             * an app is started.
             */
            if (AppSettings == null) { AppSettings=new AppSettings();}
        }

        public AppSettings AppSettings { get; set; }
    }

    public class AppSettings
    {
        public bool DebugMode { get; set; } = false;
    }
}

Implementation

var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);

Output

{
  "AppSettings": {
    "DebugMode": false
  }
}

How to wait for all threads to finish, using ExecutorService?

You could use this code:

public class MyTask implements Runnable {

    private CountDownLatch countDownLatch;

    public MyTask(CountDownLatch countDownLatch {
         this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
         try {
             //Do somethings
             //
             this.countDownLatch.countDown();//important
         } catch (InterruptedException ex) {
              Thread.currentThread().interrupt();
         }
     }
}

CountDownLatch countDownLatch = new CountDownLatch(NUMBER_OF_TASKS);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
for (int i = 0; i < NUMBER_OF_TASKS; i++){
     taskExecutor.execute(new MyTask(countDownLatch));
}
countDownLatch.await();
System.out.println("Finish tasks");

Sorting objects by property values

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [

    {
        name: "Honda",
        speed: 80
    },

    {
        name: "BMW",
        speed: 180
    },

    {
        name: "Trabi",
        speed: 40
    },

    {
        name: "Ferrari",
        speed: 200
    }
]


cars.sort(function(a, b) { 
    return a.speed - b.speed;
})

for(var i in cars)
    document.writeln(cars[i].name) // Trabi Honda BMW Ferrari 

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

How To Use DateTimePicker In WPF?

This just came in ;)

There is a new DatePicker class for WPF in the .NET 4.0 runtime: http://msdn.microsoft.com/en-us/library/system.windows.controls.datepicker.aspx

Also see the "Whats new in WPF" for more nice features: http://msdn.microsoft.com/en-us/library/bb613588.aspx