Programs & Examples On #Awt

The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit.

How to bring a window to the front?

I had the same problem with bringing a JFrame to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a WindowListener. Specifically, I had to set my JFrame to always stay on top whenever toFront() is invoked, and provide windowDeactivated event handler to setAlwaysOnTop(false).


So, here is the code that could be placed into a base JFrame, which is used to derive all application frames.

@Override
public void setVisible(final boolean visible) {
  // make sure that frame is marked as not disposed if it is asked to be visible
  if (visible) {
      setDisposed(false);
  }
  // let's handle visibility...
  if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
      super.setVisible(visible);
  }
  // ...and bring frame to the front.. in a strange and weird way
  if (visible) {
      toFront();
  }
}

@Override
public void toFront() {
  super.setVisible(true);
  int state = super.getExtendedState();
  state &= ~JFrame.ICONIFIED;
  super.setExtendedState(state);
  super.setAlwaysOnTop(true);
  super.toFront();
  super.requestFocus();
  super.setAlwaysOnTop(false);
}

Whenever your frame should be displayed or brought to front call frame.setVisible(true).

Since I moved to Ubuntu 9.04 there seems to be no need in having a WindowListener for invoking super.setAlwaysOnTop(false) -- as can be observed; this code was moved to the methods toFront() and setVisible().

Please note that method setVisible() should always be invoked on EDT.

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

What is the difference between Swing and AWT?

AWT 1 . AWT occupies more memory space 2 . AWT is platform dependent 3 . AWT require javax.awt package

swings 1 . Swing occupies less memory space 2 . Swing component is platform independent 3 . Swing requires javax.swing package

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

How to center a Window in Java?

The following code center the Window in the center of the current monitor (ie where the mouse pointer is located).

public static final void centerWindow(final Window window) {
    GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
    Rectangle r = screen.getDefaultConfiguration().getBounds();
    int x = (r.width - window.getWidth()) / 2 + r.x;
    int y = (r.height - window.getHeight()) / 2 + r.y;
    window.setLocation(x, y);
}

Getting a HeadlessException: No X11 DISPLAY variable was set

Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).

Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.

Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +

How to use KeyListener

http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial

If it's a UI based application , then " I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method" you can use GlassPane or Timer class to fulfill the requirement.

For key Event:

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/

Drawing in Java using Canvas

The following should work:

public static void main(String[] args)
{
    final String title = "Test Window";
    final int width = 1200;
    final int height = width / 16 * 9;

    //Creating the frame.
    JFrame frame = new JFrame(title);

    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    //Creating the canvas.
    Canvas canvas = new Canvas();

    canvas.setSize(width, height);
    canvas.setBackground(Color.BLACK);
    canvas.setVisible(true);
    canvas.setFocusable(false);


    //Putting it all together.
    frame.add(canvas);

    canvas.createBufferStrategy(3);

    boolean running = true;

    BufferStrategy bufferStrategy;
    Graphics graphics;

    while (running) {
        bufferStrategy = canvas.getBufferStrategy();
        graphics = bufferStrategy.getDrawGraphics();
        graphics.clearRect(0, 0, width, height);

        graphics.setColor(Color.GREEN);
        graphics.drawString("This is some text placed in the top left corner.", 5, 15);

        bufferStrategy.show();
        graphics.dispose();
    }
}

How to Change Font Size in drawString Java

Font myFont = new Font ("Courier New", 1, 17);

The 17 represents the font size. Once you have that, you can put:

g.setFont (myFont);
g.drawString ("Hello World", 10, 10);

Setting background color for a JFrame

Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.

Example:

myJFrame.getContentPane().setBackground( desiredColor );

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

Triangle Draw Method

You should try using the Shapes API.

Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas

You should also read up on GeneralPath & Drawing Arbitrary Shapes.

This method is much easy to apply AffineTransformations to

Mean per group in a data.frame

Or use group_by & summarise_at from the dplyr package:

library(dplyr)

d %>%
  group_by(Name) %>%
  summarise_at(vars(-Month), funs(mean(., na.rm=TRUE)))

# A tibble: 3 x 3
  Name  Rate1 Rate2
  <fct> <dbl> <dbl>
1 Aira   16.3  47.0
2 Ben    31.3  50.3
3 Cat    44.7  54.0

See ?summarise_at for the many ways to specify the variables to act on. Here, vars(-Month) says all variables except Month.

How to access pandas groupby dataframe by key

I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.

create groupby object based on some_key column

grouped = df.groupby('some_key')

pick N dataframes and grab their indices

sampled_df_i  = random.sample(grouped.indices, N)

grab the groups

df_list  = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)

optionally - turn it all back into a single dataframe object

sampled_df = pd.concat(df_list, axis=0, join='outer')

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

Convert java.time.LocalDate into java.util.Date type

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}

SQL Server - stop or break execution of a SQL script

In SQL 2012+, you can use THROW.

THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW

From MSDN:

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct ... If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.

Stop Visual Studio from mixing line endings in files

With VS2010+ there is a plugin solution: Line Endings Unifier.

With the plugin installed you can right click files and folders in the solution explorer and invoke the menu item Unify Line Endings in this file

Configuration for this is available via

Tools -> Options -> Line Endings Unifier.

The default file extension list that is included is pretty narrow:

 .cpp; .c; .h; .hpp; .cs; .js; .vb; .txt;

Might want to use something like:

 .cpp; .c; .h; .hpp; .cs; .js; .vb; .txt; .scss; .coffee; .ts; .jsx; .markdown; .config

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.

As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are

  1. define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
  2. use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
  3. define a function on the parent scope, and call it from the child (not always possible)

New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

<input type="text" ng-model="someObj.prop1">

<!--rather than
<input type="text" ng-model="prop1">`
-->


L-o-n-g answer:

JavaScript Prototypal Inheritance

Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes

It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.

Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:

prototypal inheritance

(Note that to save space, I show the anArray object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)

If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:

childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'

Suppose we then do this:

childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.

property hiding

Suppose we then do this:

childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)

follow the prototype chain

Suppose we then do this:

childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.

more property hiding

Takeaways:

  • If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
  • If we set childScope.propertyX, the prototype chain is not consulted.

One last scenario:

delete childScope.anArray
childScope.anArray[1] === 22  // true

We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.

after removing a child property


Angular Scope Inheritance

The contenders:

  • The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with scope: true, directive with transclude: true.
  • The following creates a new scope which does not inherit prototypically: directive with scope: { ... }. This creates an "isolate" scope instead.

Note, by default, directives do not create new scope -- i.e., the default is scope: false.

ng-include

Suppose we have in our controller:

$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

And in our HTML:

<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>

<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>

Each ng-include generates a new child scope, which prototypically inherits from the parent scope.

ng-include child scopes

Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.

ng-include with a primitive

Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.

ng-include with an object

We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:

<input ng-model="$parent.myPrimitive">

Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).

ng-include with $parent

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.

For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,

// in the parent scope
$scope.setMyPrimitive = function(value) {
     $scope.myPrimitive = value;
}

Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)

See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.

ng-switch

ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.

See also AngularJS, bind scope of a switch-case?

ng-repeat

Ng-repeat works a little differently. Suppose we have in our controller:

$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects    = [{num: 101}, {num: 202}]

And in our HTML:

<ul><li ng-repeat="num in myArrayOfPrimitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
       <input ng-model="obj.num">
    </li>
<ul>

For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:

childScope = scope.$new();  // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value;  // creates a new childScope property

If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num property that is independent of the myArrayOfPrimitives array:

ng-repeat with primitives

This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.

So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num) does change the object the parent scope references. So in the second ng-repeat above, we have:

ng-repeat with objects

(I colored one line gray just so that it is clear where it is going.)

This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.

See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945

ng-controller

Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

directives

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope. Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp in the isolated scope: <div my-directive> and scope: { localProp: '@parentProp' }. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp> and scope: { localProp: '@theParentProp' }.
    Isolate scope's __proto__ references Object. Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
    For the picture below we have
    <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> and
    scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
    Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
    isolated scope
    For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
    For the picture below, assume the same directive as above with this addition: transclude: true
    transcluded scope

This fiddle has a showScope() function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.


Summary

There are four types of scopes:

  1. normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
  2. normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
  3. isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
  4. transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

Diagrams were generated with "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.

Convert Enum to String

Simple: enum names into a List:

List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()

How to hide underbar in EditText

You can do it programmatically using setBackgroundResource:

editText.setBackgroundResource(android.R.color.transparent);

How do relative file paths work in Eclipse?

Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

Eclipse sets the working directory to the top-level project folder.

Android: how to refresh ListView contents?

Update ListView's contents by below code:

private ListView listViewBuddy;
private BuddyAdapter mBuddyAdapter;
private ArrayList<BuddyModel> buddyList = new ArrayList<BuddyModel>();

onCreate():

listViewBuddy = (ListView)findViewById(R.id.listViewBuddy);
mBuddyAdapter = new BuddyAdapter();
listViewBuddy.setAdapter(mBuddyAdapter);

onDataGet (After webservice call or from local database or otherelse):

mBuddyAdapter.setData(buddyList);
mBuddyAdapter.notifyDataSetChanged();

BaseAdapter:

private class BuddyAdapter extends BaseAdapter { 

    private ArrayList<BuddyModel> mArrayList = new ArrayList<BuddyModel>();
    private LayoutInflater mLayoutInflater= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    private ViewHolder holder;

    public void setData(ArrayList<BuddyModel> list){
        mArrayList = list;
    }

    @Override
    public int getCount() {
        return mArrayList.size();
    }

    @Override
    public BuddyModel getItem(int position) {
        return mArrayList.get(position);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    private class ViewHolder {
        private TextView txtBuddyName, txtBuddyBadge;

    }
    @SuppressLint("InflateParams")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.row_buddy, null);
            // bind views
            holder.txtBuddyName = (TextView) convertView.findViewById(R.id.txtBuddyName);
            holder.txtBuddyBadge = (TextView) convertView.findViewById(R.id.txtBuddyBadge);

            // set tag
            convertView.setTag(holder);
        } else {
            // get tag
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtBuddyName.setText(mArrayList.get(position).getFriendId());

        int badge = mArrayList.get(position).getCount();
        if(badge!=0){
            holder.txtBuddyBadge.setVisibility(View.VISIBLE);
            holder.txtBuddyBadge.setText(""+badge);
        }else{
            holder.txtBuddyBadge.setVisibility(View.GONE);
        }   

        return convertView;
    }
}

Whenever you want to Update Listview just call below two lines code:

 mBuddyAdapter.setData(Your_Updated_ArrayList);
 mBuddyAdapter.notifyDataSetChanged();

Done

Why is my CSS bundling not working with a bin deployed MVC4 app?

To add useful information to the conversation, I came across 404 errors for my bundles in the deployment (it was fine in the local dev environment).

For the bundle names, I including version numbers like such:

bundles.Add(new ScriptBundle("~/bundles/jquerymobile.1.4.3").Include(
...
);

On a whim, I removed all the dots and all was working magically again:

bundles.Add(new ScriptBundle("~/bundles/jquerymobile143").Include(
...
);

Hope that helps someone save some time and frustration.

Android Center text on canvas

I create a method to simplify this:

    public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
    Paint.Align align = paint.getTextAlign();
    float x;
    float y;
    //x
    if (align == Paint.Align.LEFT) {
        x = rectF.centerX() - paint.measureText(text) / 2;
    } else if (align == Paint.Align.CENTER) {
        x = rectF.centerX();
    } else {
        x = rectF.centerX() + paint.measureText(text) / 2;
    }
    //y
    metrics = paint.getFontMetrics();
    float acent = Math.abs(metrics.ascent);
    float descent = Math.abs(metrics.descent);
    y = rectF.centerY() + (acent - descent) / 2f;
    canvas.drawText(text, x, y, paint);

    Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
            + ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}

rectF is the area you want draw the text,That's it. Details

Good NumericUpDown equivalent in WPF?

If commercial solutions are ok, you may consider this control set: WPF Elements by Mindscape

It contains such a spin control and alternatively (my personal preference) a spin-decorator, that can decorate various numeric controls (like IntegerTextBox, NumericTextBox, also part of the control set) in XAML like this:

<WpfElements:SpinDecorator>
   <WpfElements:IntegerTextBox Text="{Binding Foo}" />
</WpfElements:SpinDecorator>

Read file-contents into a string in C++

maybe not the most efficient, but reads data in one line:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}

How to deal with SQL column names that look like SQL keywords?

If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.

select [select]
from [table]

How do you uninstall MySQL from Mac OS X?

You should also check /var/db/receipts and remove all entries that contain com.mysql.*

Using sudo rm -rf /var/db/receipts/com.mysql.* didn't work for me. I had to go into var/db/receipts and delete each one seperately.

How update the _id of one MongoDB Document?

You can also create a new document from MongoDB compass or using command and set the specific _id value that you want.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

What is so bad about singletons?

One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior. Also, if one day you want to have multiple ways of doing that one thing, it can be rather painful to change, depending on how you lay out your code.

One thing to note, if you DO use singletons, try to pass them in to whoever needs them rather than have them access it directly... Otherwise if you ever choose to have multiple ways of doing the thing that singleton does, it will be rather difficult to change as each class embeds a dependency if it accesses the singleton directly.

So basically:

public MyConstructor(Singleton singleton) {
    this.singleton = singleton;
}

rather than:

public MyConstructor() {
    this.singleton = Singleton.getInstance();
}

I believe this sort of pattern is called dependency injection and is generally considered a good thing.

Like any pattern though... Think about it and consider if its use in the given situation is inappropriate or not... Rules are made to be broken usually, and patterns should not be applied willy nilly without thought.

Visual Studio popup: "the operation could not be completed"

If you are using Visual studio 2015 and working on ASP.NET, create a new website, copy the previous files into the new site and build your site. Your old project is still referencing some old startup parameters.

openssl s_client using a proxy

You can use proxytunnel:

proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000

and then you can do this:

openssl s_client -connect localhost:7000 -showcerts

Hope this can help you!

How to upload files on server folder using jsp

I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB

What is the proper way to check if a string is empty in Perl?

The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.

Anyways those are numeric operators, you should use

if($foo eq "")

or

if(length($foo) == 0)

How do ACID and database transactions work?

To quote Wikipedia:

ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably.

A DBMS that supports transactions will strive to support all of these properties - any commercial DBMS (as well as several open-source DBMSs) provide full ACID 'support' - although it's often possible (for example, with varying isolation levels in MSSQL) to lessen the ACIDness - thus losing the guarantee of fully transactional behaviour.

How to stop default link click behavior with jQuery

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

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

Check Safari developer reference on Touch class.

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

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Well pandas use bitwise & | and each condition should be wrapped in a ()

For example following works

data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]

But the same query without proper brackets does not

data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]

Python strip() multiple characters?

strip only strips characters from the very front and back of the string.

To delete a list of characters, you could use the string's translate method:

import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

if your port is 3307 (based on your port)

Add this line in xampp\phpMyAdmin\config.inc: after i++

$cfg['Servers'][$i]['port'] = '3307';

Check if a string is not NULL or EMPTY

I would define $Version as a string to start with

[string]$Version

and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like

while (-not($version)){
    $version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

"unrecognized import path" with go get

I had the same problem on MacOS 10.10. And I found that the problem caused by OhMyZsh shell. Then I switched back to bash everything went ok.

Here is my go env

bash-3.2$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/bis/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1

Unable to run Java GUI programs with Ubuntu

Use JFrame instead of Frame. And do not extend from JFrame. Just write a class that has a JFrame property named gui, which configures this JFrame with the available methods, because it is better style doing it like this. Extending here is wrong the use of OOP.

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

Assign a synthesizable initial value to a reg in Verilog

You can combine the register declaration with initialization.

reg [7:0] data_reg = 8'b10101011;

Or you can use an initial block

reg [7:0] data_reg;
initial data_reg = 8'b10101011;

Shrink a YouTube video to responsive width

Refined Javascript only solution for YouTube and Vimeo using jQuery.

// -- After the document is ready
$(function() {
  // Find all YouTube and Vimeo videos
  var $allVideos = $("iframe[src*='www.youtube.com'], iframe[src*='player.vimeo.com']");

  // Figure out and save aspect ratio for each video
  $allVideos.each(function() {
    $(this)
      .data('aspectRatio', this.height / this.width)
      // and remove the hard coded width/height
      .removeAttr('height')
      .removeAttr('width');
  });

  // When the window is resized
  $(window).resize(function() {
    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {
      var $el = $(this);
      // Get parent width of this video
      var newWidth = $el.parent().width();
      $el
        .width(newWidth)
        .height(newWidth * $el.data('aspectRatio'));
    });

  // Kick off one resize to fix all videos on page load
  }).resize();
});

Simple to use with only embed:

<iframe width="16" height="9" src="https://www.youtube.com/embed/wH7k5CFp4hI" frameborder="0" allowfullscreen></iframe>

Or with responsive style framework like Bootstrap.

<div class="row">
  <div class="col-sm-6">
    Stroke Awareness
  <div class="col-sm-6>
    <iframe width="16" height="9" src="https://www.youtube.com/embed/wH7k5CFp4hI" frameborder="0" allowfullscreen></iframe>
  </div>
</div>
  • Relies on width and height of iframe to preserve aspect ratio
  • Can use aspect ratio for width and height (width="16" height="9")
  • Waits until document is ready before resizing
  • Uses jQuery substring *= selector instead of start of string ^=
  • Gets reference width from video iframe parent instead of predefined element
  • Javascript solution
  • No CSS
  • No wrapper needed

Thanks to @Dampas for starting point. https://stackoverflow.com/a/33354009/1011746

Recursive directory listing in DOS

I like to use the following to get a nicely sorted listing of the current dir:

> dir . /s /b sortorder:N

Multiple arguments to function called by pthread_create()?

main() has it's own thread and stack variables. either allocate memory for 'args' in the heap or make it global:

struct arg_struct {
    int arg1;
    int arg2;
}args;

//declares args as global out of main()

Then of course change the references from args->arg1 to args.arg1 etc..

ActiveModel::ForbiddenAttributesError when creating new user

Alternatively you can use the Protected Attributes gem, however this defeats the purpose of requiring strong params. However if you're upgrading an older app, Protected Attributes does provide an easy pathway to upgrade until such time that you can refactor the attr_accessible to strong params.

How does the "final" keyword in Java work? (I can still modify an object.)

"A final variable can only be assigned once"

*Reflection* - "wowo wait, hold my beer".


Freeze of final fields happen in two scenarios:

  • End of constructor.
  • When reflection sets the field's value. (as many times as it wants to)

Let's break the law

public class HoldMyBeer 
{
    final int notSoFinal;
    
    public HoldMyBeer()
    {
       notSoFinal = 1;
    }

    static void holdIt(HoldMyBeer beer, int yetAnotherFinalValue) throws Exception
    {
       Class<HoldMyBeer> cl = HoldMyBeer.class;
       Field field = cl.getDeclaredField("notSoFinal");
       field.setAccessible(true);
       field.set(beer, yetAnotherFinalValue);
    }

    public static void main(String[] args) throws Exception 
    {
       HoldMyBeer beer = new HoldMyBeer();
       System.out.println(beer.notSoFinal);
       holdIt(beer, 50);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 100);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 666);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 8888);
       System.out.println(beer.notSoFinal);
    }    
}

Output:

1
50
100
666
8888

The "final" field has been assigned 5 different "final" values (note the quotes). And it could keep being assigned different values over and over...

Why? Because reflection is like Chuck Norris, and if it wants to change the value of an initialized final field, it does. Some say he himself is the one that pushes the new values into the stack :

Code:
   7: astore_1
  11: aload_1
  12: getfield                
  18: aload_1
  19: bipush        50        //wait what
  27: aload_1
  28: getfield                
  34: aload_1
  35: bipush        100       //come on...
  43: aload_1
  44: getfield                
  50: aload_1
  51: sipush        666      //...you were supposed to be final...
  60: aload_1
  61: getfield                
  67: aload_1
  68: sipush        8888     //ok i'm out whatever dude
  77: aload_1
  78: getfield                

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

Vertical Align Center in Bootstrap 4

.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Decimal or numeric values in regular expression validation

/([0-9]+[.,]*)+/ matches any number with or without coma or dots

it can match

         122
         122,354
         122.88
         112,262,123.7678

bug: it also matches 262.4377,3883 ( but it doesn't matter parctically)

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

Calculate rolling / moving average in C++

Incrementing on @Nilesh's answer (credit goes to him), you can:

  • keep track of the sum, no need to divide and then multiply every time, generating error
  • avoid if conditions using % operator

This is UNTESTED sample code to show the idea, it could also be wrapped into a class:

const unsigned int size=10; // ten elements buffer

unsigned int counterPosition=0;
unsigned int counterNum=0;

int buffer[size];
long sum=0;

void reset() {
    for(int i=0;i<size;i++) {
        buffer[i]=0;
    }
}

float addValue(int value) {
    unsigned  int oldPos = ((counterPosition + 1) % size);

    buffer[counterPosition] = value;
    sum = (sum - buffer[oldPos] + value); 

    counterPosition=(counterPosition+1) % size;
    if(counterNum<size) counterNum++;

    return ((float)sum)/(float)counterNum;
}

float removeValue() {
    unsigned  int oldPos =((counterPosition + 1) % size);

    buffer[counterPosition] = 0;
    sum = (sum - buffer[oldPos]); 

    if(counterNum>1) { // leave one last item at the end, forever
        counterPosition=(counterPosition+1) % size;
        counterNum--; // here the two counters are different
    }
    return ((float)sum)/(float)counterNum;
}

It should be noted that, if the buffer is reset to all zeroes, this method works fine while receiving the first values in as - buffer[oldPos] is zero and counter grows. First output is the first number received. Second output is the average of only the first two, and so on, fading in the values while they arrive until size items are reached.

It is also worth considering that this method, like any other for rolling average, is asymmetrical, if you stop at the end of the input array, because the same fading does not happen at the end (it can happen after the end of data, with the right calculations).

That is correct. The rolling average of 100 elements with a buffer of 10 gives different results: 10 fading in, 90 perfectly rolling 10 elements, and finally 10 fading out, giving a total of 110 results for 100 numbers fed in! It's your choice to decide which ones to show (and if it's better going the straight way, old to recent, or backwards, recent to old).

To fade out correctly after the end, you can go on adding zeroes one by one and reducing the count of items by one every time until you have reached size elements (still keeping track of correct position of old values).

Usage is like this:

int avg=0;
reset();

avg=addValue(2); // Rpeat for 100 times
avg=addValue(3); // Use avg value

...

avg=addValue(-4);
avg=addValue(12); // last numer, 100th input 

// If you want to fade out repeat 10 times after the end of data:

avg=removeValue(); // Rpeat for last 10 times after data has finished
avg=removeValue(); // Use avg value
...
avg=removeValue();
avg=removeValue();

Regex to test if string begins with http:// or https://

^ for start of the string pattern,

? for allowing 0 or 1 time repeat. ie., s? s can exist 1 time or no need to exist at all.

/ is a special character in regex so it needs to be escaped by a backslash \/

/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false

What is external linkage and internal linkage?

Basically

  • extern linkage variable is visible in all files
  • internal linkage variable is visible in single file.

Explain: const variables internally link by default unless otherwise declared as extern

  1. by default, global variable is external linkage
  2. but, const global variable is internal linkage
  3. extra, extern const global variable is external linkage

A pretty good material about linkage in C++

http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/

Create a CSV File for a user in PHP

Put in the $output variable the CSV data and echo with the correct headers

header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;

JavaScript operator similar to SQL "like"

No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.

EDIT: This has been answered before:

Emulating SQL LIKE in JavaScript

How do I make a Git commit in the past?

To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE and GIT_COMMITTER_DATE:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'

where date -d'...' can be exact date like 2019-01-01 12:00:00 or relative like 5 months ago 24 days ago.

To see both dates in git log use:

git log --pretty=fuller

This also works for merge commits:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff

force browsers to get latest js and css files in asp.net application

<?php $rand_no = rand(10000000, 99999999)?> <script src="scripts/myjavascript.js?v=<?=$rand_no"></script>

This works for me in all browsers. Here I have used PHP to generate random no. You can use your own server side language.`

Eclipse: Frustration with Java 1.7 (unbound library)

Cause : This is common scenario when we import new project with different lib and JAR path.

I faced this issue and got resolved using exact following steps:

  • Project > Properties
  • Build Path > Configure Build Path
  • Select "Libraries" tab
  • Click "Add Library"
  • Select "JRE System Library" from displayed list
  • Click on "Next" followed by "Finish" button

This will point your system's proper & valid JRE path, which did thing for me. Cheers :)

Convert NaN to 0 in javascript

Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?

If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.

The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.

NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

Security of REST authentication schemes

Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).

Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:

XML encryption (W3C standard)

XML Security

html <input type="text" /> onchange event not working

A couple of comments that IMO are important:

  • input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.

  • The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input

  • The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)

  • Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...

  • jQuery has nothing to do with this. This is all in HTML standard.

  • If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.

My two cents.

How abstraction and encapsulation differ?

Abstraction & Encapsulation Example Image source

Abstraction: is outlined by the top left and top right images of the cat. The surgeon and the old lady designed (or visualized) the animal differently. In the same way, you would put different features in the Cat class, depending upon the need of the application. Every cat has a liver, bladder, heart and lung, but if you need your cat to 'purr' only, you will abstract your application's cat to the design on top-left rather than the top-right.

Encapsulation: is outlined by the cat standing on the table. That's what everyone outside the cat should see the cat as. They need not worry whether the actual implementation of the cat is the top-left one or the top-right one or even a combination of both.


PS: Go here on this same question to hear the complete story.

CURRENT_TIMESTAMP in milliseconds

Do as follows for milliseconds:

select round(date_format(CURTIME(3), "%f")/1000)

You can get microseconds by the following:

select date_format(CURTIME(6), "%f")

Initialization of an ArrayList in one line

The simple answer

In Java 9 or later, after List.of() was added:

List<String> strings = List.of("foo", "bar", "baz");

With Java 10 or later, this can be shortened with the var keyword.

var strings = List.of("foo", "bar", "baz");

This will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.


Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");

This will give you a List backed by an array, so it cannot change length.
But you can call List.set, so it's still mutable.


You can make Arrays.asList even shorter with a static import:

List<String> strings = asList("foo", "bar", "baz");

The static import:

import static java.util.Arrays.asList;  

Which any modern IDE will suggest and automatically do for you.
For example in IntelliJ IDEA you press Alt+Enter and select Static import method....


However, i don't recommend shortening the List.of method to of, because that becomes confusing.
List.of is already short enough and reads well.


Using Streams

Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:

Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:

import static java.util.stream.Collectors.toList;

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());

But preferably, just use the Stream without collecting it to a List.


If you really specifically need a java.util.ArrayList

(You probably don't.)
To quote JEP 269 (emphasis mine):

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.


If you want to both prepopulate an ArrayList and add to it afterwards (why?), use

ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");

or in Java 8 or earlier:

ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");

or using Stream:

import static java.util.stream.Collectors.toCollection;

ArrayList<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.


Program to interfaces, not to implementations

You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.

Which you are most likely not doing.

Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).

Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.

For example, if you're passing an ArrayList to a void method(...):

// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) { 
    for (String s : strings) { ... } 
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.

How do I convert a String object into a Hash object?

works in rails 4.1 and support symbols without quotes {:a => 'b'}

just add this to initializers folder:

class String
  def to_hash_object
    JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
  end
end

Google reCAPTCHA: How to get user response and validate in the server side?

Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:

 <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
 <span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) {

var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
 if(v.length != 0)
 {
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
 }
}

Java String remove all non numeric characters

A way to replace it with a java 8 stream:

public static void main(String[] args) throws IOException
{
    String test = "ab19198zxncvl1308j10923.";
    StringBuilder result = new StringBuilder();

    test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );

    System.out.println( result ); //returns 19198.130810923.
}

How to pass command-line arguments to a PowerShell ps1 file

if you want to invoke ps1 scripts from cmd and pass arguments without invoking the script like

powershell.exe script.ps1 -c test
script -c test ( wont work )

you can do the following

setx PATHEXT "%PATHEXT%;.PS1;" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1=powershell.exe "%1" %*

This is assuming powershell.exe is in your path

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ftype

Field 'browser' doesn't contain a valid alias configuration

Changed my entry to

entry: path.resolve(__dirname, './src/js/index.js'),

and it worked.

How to perform a real time search and filter on a HTML table

If you can separate html and data, you can use external libraries like datatables or the one i created. https://github.com/thehitechpanky/js-bootstrap-tables

This library uses keyup function to reload tabledata and hence it appears to work like search.

function _addTableDataRows(paramObjectTDR) {
    let { filterNode, limitNode, bodyNode, countNode, paramObject } = paramObjectTDR;
    let { dataRows, functionArray } = paramObject;
    _clearNode(bodyNode);
    if (typeof dataRows === `string`) {
        bodyNode.insertAdjacentHTML(`beforeend`, dataRows);
    } else {
        let filterTerm;
        if (filterNode) {
            filterTerm = filterNode.value.toLowerCase();
        }
        let serialNumber = 0;
        let limitNumber = 0;
        let rowNode;
        dataRows.forEach(currentRow => {
            if (!filterNode || _filterData(filterTerm, currentRow)) {
                serialNumber++;
                if (!limitNode || limitNode.value === `all` || limitNode.value >= serialNumber) {
                    limitNumber++;
                    rowNode = _getNode(`tr`);
                    bodyNode.appendChild(rowNode);
                    _addData(rowNode, serialNumber, currentRow, `td`);
                }
            }
        });
        _clearNode(countNode);
        countNode.insertAdjacentText(`beforeend`, `Showing 1 to ${limitNumber} of ${serialNumber} entries`);
    }
    if (functionArray) {
        functionArray.forEach(currentObject => {
            let { className, eventName, functionName } = currentObject;
            _attachFunctionToClassNodes(className, eventName, functionName);
        });
    }
}

How to check status of PostgreSQL server Mac OS X

You probably did not init postgres.

If you installed using HomeBrew, the init must be run before anything else becomes usable.

To see the instructions, run brew info postgres

# Create/Upgrade a Database
If this is your first install, create a database with:
     initdb /usr/local/var/postgres -E utf8

To have launchd start postgresql at login:
   ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents 
Then to load postgresql now:     
   launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist 
Or, if you don't want/need launchctl, you can just run:
    pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Once you have run that, it should say something like:

Success. You can now start the database server using:

postgres -D /usr/local/var/postgres or
pg_ctl -D /usr/local/var/postgres -l logfile start

If you are still having issues, check your firewall. If you use a good one like HandsOff! and it was configured to block traffic, then your page will not see the database.

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

Convert True/False value read from file to boolean

I'm not suggested this as the best answer, just an alternative but you can also do something like:

flag = reader[0] == "True"

flag will be True id reader[0] is "True", otherwise it will be False.

How to import/include a CSS file using PHP code and not HTML code?

I don't know why you would need this but to do this, you could edit your css file:-

<style type="text/css">
body{
...;
...;
}
</style>

You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit


Then edit your HTML file like this. NOTE: Make the include statement inside the tag

<html>
<head>
 <title>Sample</title>
 <?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>

How best to determine if an argument is not sent to the JavaScript function

It can be convenient to approach argument detection by evoking your function with an Object of optional properties:

function foo(options) {
    var config = { // defaults
        list: 'string value',
        of: [a, b, c],
        optional: {x: y},
        objects: function(param){
           // do stuff here
        }
    }; 
    if(options !== undefined){
        for (i in config) {
            if (config.hasOwnProperty(i)){
                if (options[i] !== undefined) { config[i] = options[i]; }
            }
        }
    }
}

How can I get color-int from color resource?

Define your color

values/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- color int as #AARRGGBB (alpha, red, green, blue) -->
    <color name="orange">#fff3632b</color>
    ...
    <color name="my_view_color">@color/orange</color>

</resources>

Get the color int and set it

int backgroundColor = ContextCompat.getColor(context, R.color.my_view_color);
// Color backgroundColor = ... (Don't do this. The color is just an int.)

myView.setBackgroundColor(backgroundColor);

See also

Difference between View and table in sql

A view is a virtual table. A view consists of rows and columns just like a table. The difference between a view and a table is that views are definitions built on top of other tables (or views), and do not hold data themselves. If data is changing in the underlying table, the same change is reflected in the view. A view can be built on top of a single table or multiple tables. It can also be built on top of another view. In the SQL Create View page, we will see how a view can be built.

Views offer the following advantages:

  1. Ease of use: A view hides the complexity of the database tables from end users. Essentially we can think of views as a layer of abstraction on top of the database tables.

  2. Space savings: Views takes very little space to store, since they do not store actual data.

  3. Additional data security: Views can include only certain columns in the table so that only the non-sensitive columns are included and exposed to the end user. In addition, some databases allow views to have different security settings, thus hiding sensitive data from prying eyes.

Answer from:http://www.1keydata.com/sql/sql-view.html

How do I sort a VARCHAR column in SQL server that contains numbers?

This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.

SELECT *,
       (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
FROM table_name 
ORDER BY IsNum, LEN(column_name), column_name;

Delete all rows in a table based on another table

I often do things like the following made-up example. (This example is from Informix SE running on Linux.)

The point of of this example is to delete all real estate exemption/abatement transaction records -- because the abatement application has a bug -- based on information in the real_estate table.

In this case last_update != nullmeans the account is not closed, and res_exempt != 'p' means the accounts are not personal property (commercial equipment/furnishings).

delete from trans 
where   yr = '16'
and     tran_date = '01/22/2016'
and     acct_type = 'r'
and     tran_type = 'a'
and     bill_no in
(select acct_no from real_estate where last_update is not null
 and res_exempt != 'p');

I like this method, because the filtering criteria -- at least for me -- is easier to read while creating the query, and to understand many months from now when I'm looking at it and wondering what I was thinking.

fatal error LNK1169: one or more multiply defined symbols found in game programming

I answered a similar question here.

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

That's what programmers call a "quick and dirty" solution, but sometimes you just want the build to be completed and get to the bottom of the problem later, so that's kind of a ad-hoc solution. To actually avoid this error, provided that you want

int WIDTH = 1024;
int HEIGHT = 800;

to be shared among several source files, just declare them only in a single .c / .cpp file, and refer to them in a header file:

extern int WIDTH;
extern int HEIGHT;

Then include the header in any other source file you wish these global variables to be available.

How to monitor the memory usage of Node.js?

The built-in process module has a method memoryUsage that offers insight in the memory usage of the current Node.js process. Here is an example from in Node v0.12.2 on a 64-bit system:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

In this simple example, you can see that allocating an array of 10M elements consumers approximately 80MB (take a look at heapUsed).
If you look at V8's source code (Array::New, Heap::AllocateRawFixedArray, FixedArray::SizeFor), then you'll see that the memory used by an array is a fixed value plus the length multiplied by the size of a pointer. The latter is 8 bytes on a 64-bit system, which confirms that observed memory difference of 8 x 10 = 80MB makes sense.

htaccess redirect to https://www

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

Find the nth occurrence of substring in a string

The replace one liner is great but only works because XX and bar have the same lentgh

A good and general def would be:

def findN(s,sub,N,replaceString="XXX"):
    return s.replace(sub,replaceString,N-1).find(sub) - (len(replaceString)-len(sub))*(N-1)

Combine two ActiveRecord::Relation objects

If you have an array of activerecord relations and want to merge them all, you can do

array.inject(:merge)

PDO closing connection

I created a derived class to have a more self-documented instruction instead of $conn=null;.

class CMyPDO extends PDO {
    public function __construct($dsn, $username = null, $password = null, array $options = null) {
        parent::__construct($dsn, $username, $password, $options);
    }

    static function getNewConnection() {
        $conn=null;
        try {
            $conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
        }
        catch (PDOException $exc) {
            echo $exc->getMessage();
        }
        return $conn;
    }

    static function closeConnection(&$conn) {
        $conn=null;
    }
}

So I can call my code between:

$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to change webservice url endpoint?

To change the end address property edit your wsdl file

<wsdl:definitions.......
  <wsdl:service name="serviceMethodName">
    <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
      <soap:address location="http://service_end_point_adress"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

private void btnSent_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        mail.From = new MailAddress(txtAcc.Text);
        mail.To.Add(txtToAdd.Text);
        mail.Subject = txtSub.Text;
        mail.Body = txtContent.Text;
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
        mail.Attachments.Add(attachment);

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);

        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
        MessageBox.Show("mail send");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MailMessage mail = new MailMessage();
    openFileDialog1.ShowDialog();
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
    mail.Attachments.Add(attachment);
    txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}

"unable to locate adb" using Android Studio

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

How to convert a string to utf-8 in Python

If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:

stringnamehere.decode('utf-8', 'ignore')

Address already in use: JVM_Bind

as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet

how to Call super constructor in Lombok

This is not possible in Lombok. Although it would be a really nice feature, it requires resolution to find the constructors of the super class. The super class is only known by name the moment Lombok gets invoked. Using the import statements and the classpath to find the actual class is not trivial. And during compilation you cannot just use reflection to get a list of constructors.

It is not entirely impossible but the results using resolution in val and @ExtensionMethod have taught us that is it hard and error-prone.

Disclosure: I am a Lombok developer.

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

process.waitFor() never returns

For the same reason you can also use inheritIO() to map Java console with external app console like:

ProcessBuilder pb = new ProcessBuilder(appPath, arguments);

pb.directory(new File(appFile.getParent()));
pb.inheritIO();

Process process = pb.start();
int success = process.waitFor();

CSS customized scroll bar in div

Firefox new version(64) support CSS Scrollbars Module Level 1

_x000D_
_x000D_
.scroller {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  overflow-y: scroll;_x000D_
  scrollbar-color: rebeccapurple green;_x000D_
  scrollbar-width: thin;_x000D_
}
_x000D_
<div class="scroller">_x000D_
Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi_x000D_
welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic._x000D_
Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette_x000D_
tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato._x000D_
Dandelion cucumber earthnut pea peanut soko zucchini._x000D_
</div>
_x000D_
_x000D_
_x000D_

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scrollbars

Firefox scrollbar

https://codepen.io/fatihhayri/pen/pqdrbd

Iterating over Numpy matrix rows to apply a function each?

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]

Form inside a form, is that alright?

Yes there is. It is wrong. It won't work because it is wrong. Most browsers will only see one form.

http://www.w3.org/MarkUp/html3/forms.html

NSDictionary to NSArray?

You just need to initialize your NSMutableArray

NSMutableArray  *myArray = [[NSMutableArray alloc] init];

When should I use semicolons in SQL Server?

Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)

Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.

[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]

tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.

PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';

Output:

Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional

How to start jenkins on different port rather than 8080 using command prompt in Windows?

Use the following command at command prompt:

java -jar jenkins.war --httpPort=9090

If you want to use https use the following command:

java -jar jenkins.war --httpsPort=9090

Details are here

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

Why can't I use switch statement on a String?

The following is a complete example based on JeeBee's post, using java enum's instead of using a custom method.

Note that in Java SE 7 and later you can use a String object in the switch statement's expression instead.

public class Main {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

      String current = args[0];
      Days currentDay = Days.valueOf(current.toUpperCase());

      switch (currentDay) {
          case MONDAY:
          case TUESDAY:
          case WEDNESDAY:
              System.out.println("boring");
              break;
          case THURSDAY:
              System.out.println("getting better");
          case FRIDAY:
          case SATURDAY:
          case SUNDAY:
              System.out.println("much better");
              break;

      }
  }

  public enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
  }
}

Can (domain name) subdomains have an underscore "_" in it?

A note on terminology, in furtherance to Bortzmeyer's answer

One should be clear about definitions. As used here:

  • domain name is the identifier of a resource in a DNS database
  • label is the part of a domain name in between dots
  • hostname is a special type of domain name which identifies Internet hosts

The hostname is subject to the restrictions of RFC 952 and the slight relaxation of RFC 1123

RFC 2181 makes clear that there is a difference between a domain name and a hostname:

...[the fact that] any binary label can have an MX record does not imply that any binary name can be used as the host part of an e-mail address...

So underscores in hostnames are a no-no, underscores in domain names are a-ok.

In practice, one may well see hostnames with underscores. As the Robustness Principle says: "Be conservative in what you send, liberal in what you accept".

A note on encoding

In the 21st century, it turns out that hostnames as well as domain names may be internationalized! This means resorting to encodings in case of labels that contain characters that are outside the allowed set.

In particular, it allows one to encode the _ in hostnames (Update 2017-07: This is doubtful, see comments. The _ still cannot be used in hostnames. Indeed, it cannot even be used in internationalized labels.)

The first RFC for internationalization was RFC 3490 of March 2003, "Internationalizing Domain Names in Applications (IDNA)". Today, we have:

  • RFC 5890 "IDNA: Definitions and Document Framework"
  • RFC 5891 "IDNA: Protocol"
  • RFC 5892 "The Unicode Code Points and IDNA"
  • RFC 5893 "Right-to-Left Scripts for IDNA"
  • RFC 5894 "IDNA: Background, Explanation, and Rationale"
  • RFC 5895 "Mapping Characters for IDNA 2008"

You may also want to check the Wikipedia Entry

RFC 5890 introduces the term LDH (Letter-Digit-Hypen) label for labels used in hostnames and says:

This is the classical label form used, albeit with some additional restrictions, in hostnames (RFC 952). Its syntax is identical to that described as the "preferred name syntax" in Section 3.5 of RFC 1034 as modified by RFC 1123. Briefly, it is a string consisting of ASCII letters, digits, and the hyphen with the further restriction that the hyphen cannot appear at the beginning or end of the string. Like all DNS labels, its total length must not exceed 63 octets.

Going back to simpler times, this Internet draft is an early proposal for hostname internationalization. Hostnames with international characters may be encoded using, for example, 'RACE' encoding.

The author of the 'RACE encoding' proposal notes:

According to RFC 1035, host parts must be case-insensitive, start and end with a letter or digit, and contain only letters, digits, and the hyphen character ("-"). This, of course, excludes any internationalized characters, as well as many other characters in the ASCII character repertoire. Further, domain name parts must be 63 octets or shorter in length.... All post-converted name parts that contain internationalized characters begin with the string "bq--". (...) The string "bq--" was chosen because it is extremely unlikely to exist in host parts before this specification was produced.

How can I easily view the contents of a datatable or dataview in the immediate window

To beautify adinas's debugger output I made some simple formattings:

    public void DebugTable(DataTable table)
    {
        Debug.WriteLine("--- DebugTable(" + table.TableName + ") ---");
        int zeilen = table.Rows.Count;
        int spalten = table.Columns.Count;

        // Header
        for (int i = 0; i < table.Columns.Count; i++)
        {
            string s = table.Columns[i].ToString();
            Debug.Write(String.Format("{0,-20} | ", s));
        }
        Debug.Write(Environment.NewLine);
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);

        // Data
        for (int i = 0; i < zeilen; i++)
        {
            DataRow row = table.Rows[i];
            //Debug.WriteLine("{0} {1} ", row[0], row[1]);
            for (int j = 0; j < spalten; j++)
            {
                string s = row[j].ToString();
                if (s.Length > 20) s = s.Substring(0, 17) + "...";
                Debug.Write(String.Format("{0,-20} | ", s));
            }
            Debug.Write(Environment.NewLine);
        }
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);
    }

Best of this solution: You don't need Visual Studio! Here my example output:

SELECT PackKurz, PackName, PackGewicht FROM verpackungen

PackKurz             | PackName             | PackGewicht          | 
---------------------|----------------------|----------------------|-
BB205                | BigBag 205 kg        | 205                  | 
BB300                | BigBag 300 kg        | 300                  | 
BB365                | BigBag 365 kg        | 365                  | 
CO                   | Container, Alteru... |                      | 
EP                   | Palette              |                      | 
IBC                  | Chemikaliengefäß ... |                      | 
lose                 | nicht verpackungs... | 0                    | 
---------------------|----------------------|----------------------|-

How to solve static declaration follows non-static declaration in GCC C code?

I had a similar issue , The function name i was using matched one of the inbuilt functions declared in one of the header files that i included in the program.Reading through the compiler error message will tell you the exact header file and function name.Changing the function name solved this issue for me

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Sometimes, such a question can be asked at an interview.

For example, when you write:

int a = 2;
long b = 3;
a = a + b;

there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.

So to avoid it, you must write your code like this:

int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

How to make program go back to the top of the code instead of closing

You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.

Email and phone Number Validation in android

try this:

extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));

private boolean validateMobile()    {   

    String mobile =extMobileNo.getText().toString().trim();
    if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )

    {
            inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
        requestFocus(extMobileNo);
        return false;
    }

    else {
        inputLayoutMobile.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidMobile(String mobile)
{
    return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

Detect when browser receives file download

When the user triggers the generation of the file, you could simply assign a unique ID to that "download", and send the user to a page which refreshes (or checks with AJAX) every few seconds. Once the file is finished, save it under that same unique ID and...

  • If the file is ready, do the download.
  • If the file is not ready, show the progress.

Then you can skip the whole iframe/waiting/browserwindow mess, yet have a really elegant solution.

How do you get the string length in a batch file?

Just found ULTIMATE solution:

set "MYSTRING=abcdef!%%^^()^!"
(echo "%MYSTRING%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%-5
echo string "%MYSTRING%" length = %STRLENGTH%

The output is:

string "abcdef!%^^()^!" length = 14

It handles escape characters, an order of magnitude simpler then most solutions above, and contains no loops, magic numbers, DelayedExpansion, temp files, etc.

In case usage outside batch script (mean putting commands to console manually), replace %%RESULT%% key with %RESULT%.

If needed, %ERRORLEVEL% variable could be set to FALSE using any NOP command, e.g. echo. >nul

Given an RGB value, how do I create a tint (or shade)?

Among several options for shading and tinting:

  • For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.

  • For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).

Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)

See also Violet Giraffe's comment about "gamma correction".

Correctly determine if date string is a valid date in that format

How about this one?

We simply use a try-catch block.

$dateTime = 'an invalid datetime';

try {
    $dateTimeObject = new DateTime($dateTime);
} catch (Exception $exc) {
    echo 'Do something with an invalid DateTime';
}

This approach is not limited to only one date/time format, and you don't need to define any function.

How can I access the MySQL command line with XAMPP for Windows?

  1. Open the XAMPP control panel.
  2. Click Shell.
  3. Type mysql --user=your_user_name --password=your_password.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

How to put space character into a string name in XML?

As already mentioned the correct way to have a space in an XML file is by using \u0020 which is the unicode character for a space.

Example:

<string name="spelatonertext3">-4,\u00205,\u0020-5,\u00206,\u0020-6</string>

Other suggestions have said to use &#160; or &#032; but there is two downsides to this. The first downside is that these are ASCII characters so you are relying on something like a TextView to parse them. The second downside is that &#160; can sometimes cause strange wrapping in TextViews.

Search for exact match of string in excel row using VBA Macro

Never mind, I found the answer.

This will do the trick.

Dim colIndex As Long    
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)

JavaScript unit test tools for TDD

Karma or Protractor

Karma is a JavaScript test-runner built with Node.js and meant for unit testing.

The Protractor is for end-to-end testing and uses Selenium Web Driver to drive tests.

Both have been made by the Angular team. You can use any assertion-library you want with either.

Screencast: Karma Getting started

related:

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from a browser or headless with PhantomJS
  • Run on multiple clients at once
  • Option to launch, capture, and automatically shut down browsers
  • Option to run server/clients on development computer or separately
  • Run tests from a command line (can be integrated into ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (Jasmine, Mocha, QUnit built-in)
    • Your own assertions/refutes
    • Reporters
    • Browser Launchers
  • Plugin for WebStorm
  • Supported by Netbeans IDE

Cons:

mocha.js

I'm totally unqualified to comment on mocha.js's features, strengths, and weaknesses, but it was just recommended to me by someone I trust in the JS community.

List of features, as reported by its website:

  • browser support
  • simple async support, including promises
  • test coverage reporting
  • string diff support
  • javascript # API for running tests
  • proper exit status for CI support etc
  • auto-detects and disables coloring for non-ttys
  • maps uncaught exceptions to the correct test case
  • async test timeout support
  • test-specific timeouts
  • growl notification support
  • reports test durations
  • highlights slow tests
  • file watcher support
  • global variable leak detection
  • optionally run tests that match a regexp
  • auto-exit to prevent "hanging" with an active loop
  • easily meta-generate suites & test-cases
  • mocha.opts file support
  • clickable suite titles to filter test execution
  • node debugger support
  • detects multiple calls to done()
  • use any assertion library you want
  • extensible reporting, bundled with 9+ reporters
  • extensible test DSLs or "interfaces"
  • before, after, before each, after each hook
  • arbitrary transpiler support (coffee-script etc)
  • TextMate bundle

yolpo

yolpo

This no longer exists, redirects to sequential.js instead

Yolpo is a tool to visualize the execution of javascript. Javascript API developers are encouraged to write their use cases to show and tell their API. Such use cases forms the basis of regression tests.

AVA

AVA logo

Futuristic test runner with built-in support for ES2015. Even though JavaScript is single-threaded, IO in Node.js can happen in parallel due to its async nature. AVA takes advantage of this and runs your tests concurrently, which is especially beneficial for IO heavy tests. In addition, test files are run in parallel as separate processes, giving you even better performance and an isolated environment for each test file.

  • Minimal and fast
  • Simple test syntax
  • Runs tests concurrently
  • Enforces writing atomic tests
  • No implicit globals
  • Isolated environment for each test file
  • Write your tests in ES2015
  • Promise support
  • Generator function support
  • Async function support
  • Observable support
  • Enhanced asserts
  • Optional TAP o utput
  • Clean stack traces

Buster.js

A JavaScript test-runner built with Node.js. Very modular and flexible. It comes with its own assertion library, but you can add your own if you like. The assertions library is decoupled, so you can also use it with other test-runners. Instead of using assert(!...) or expect(...).not..., it uses refute(...) which is a nice twist imho.

A browser JavaScript testing toolkit. It does browser testing with browser automation (think JsTestDriver), QUnit style static HTML page testing, testing in headless browsers (PhantomJS, jsdom, ...), and more. Take a look at the overview!

A Node.js testing toolkit. You get the same test case library, assertion library, etc. This is also great for hybrid browser and Node.js code. Write your test case with Buster.JS and run it both in Node.js and in a real browser.

Screencast: Buster.js Getting started (2:45)

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from a browser or headless with PhantomJS (soon)
  • Run on multiple clients at once
  • Supports NodeJS testing
  • Don't need to run server/clients on development computer (no need for IE)
  • Run tests from a command line (can be integrated into ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Defer tests instead of commenting them out
  • SinonJS built-in
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (JsTestDriver built in)
    • Your own assertions/refutes
    • Reporters (xUnit XML, traditional dots, specification, tap, TeamCity and more built-in)
    • Customize/replace the HTML that is used to run the browser-tests
  • TextMate and Emacs integration

Cons:

  • Stil in beta so can be buggy
  • No plugin for Eclipse/IntelliJ (yet)
  • Doesn't group results by os/browser/version like TestSwarm *. It does, however, print out the browser name and version in the test results.
  • No history of previous test results like TestSwarm *
  • Doesn't fully work on windows as of May 2014

* TestSwarm is also a Continuous Integration server, while you need a separate CI server for Buster.js. It does, however, output xUnit XML reports, so it should be easy to integrate with Hudson, Bamboo or other CI servers.

TestSwarm

https://github.com/jquery/testswarm

TestSwarm is officially no longer under active development as stated on their GitHub webpage. They recommend Karma, browserstack-runner, or Intern.

Jasmine

Jasmine

This is a behavior-driven framework (as stated in quote below) that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on RSpec that are used for testing in Rails projects.

Jasmine specs can be run from an html page (in qUnit fashion) or from a test runner (as Karma).

Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.

If you have experience with this testing framework, please contribute with more info :)

Project home: http://jasmine.github.io/

QUnit

QUnit focuses on testing JavaScript in the browser while providing as much convenience to the developer as possible. Blurb from the site:

QUnit is a powerful, easy-to-use JavaScript unit test suite. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code

QUnit shares some history with TestSwarm (above):

QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone. QUnit's assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.

Project home: http://qunitjs.com/

Sinon

Another great tool is sinon.js by Christian Johansen, the author of Test-Driven JavaScript Development. Best described by himself:

Standalone test spies, stubs and mocks for JavaScript. No dependencies works with any unit testing framework.

Intern

The Intern Web site provides a direct feature comparison to the other testing frameworks on this list. It offers more features out of the box than any other JavaScript-based testing system.

JEST

A new but yet very powerful testing framework. It allows snapshot based testing as well this increases the testing speed and creates a new dynamic in terms of testing

Check out one of their talks: https://www.youtube.com/watch?v=cAKYQpTC7MA

Better yet: Getting Started

How to exclude rows that don't join with another table?

SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL

capture div into image using html2canvas

I don't know if the answer will be late, but I have used this form.

JS:

function getPDF()  {
       html2canvas(document.getElementById("toPDF"),{
        onrendered:function(canvas){
 
        var img=canvas.toDataURL("image/png");
        var doc = new jsPDF('l', 'cm'); 
        doc.addImage(img,'PNG',2,2); 
        doc.save('reporte.pdf'); 
       }
    }); 
}

HTML:

<div id="toPDF"> 
    #your content...
</div>

<button  id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
    Download PDF
</button>

How to get first character of a string in SQL?

SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student

How should I remove all the leading spaces from a string? - swift

Try functional programming to remove white spaces:

extension String {
  func whiteSpacesRemoved() -> String {
    return self.filter { $0 != Character(" ") }
  }
}

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

How to call URL action in MVC with javascript function?

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

Recreate the default website in IIS

Other answers are basically right, thanks to them I was able to restore my default web site, they're just missing some more or less important details.

This was the complete process to restore the Default Web Site in my case (IIS 7 on Windows 7 64bit):

  1. open IIS Manager
  2. right click Sites node under your machine in the Connections tree on the left side and click Add Website
  3. enter "Default Web Site" as a Site name
  4. set Application pool back to DefaultAppPool!
  5. set Physical path to %SystemDrive%\inetpub\wwwroot
  6. leave Binding and everything else as is

Possible issues:

  1. If the newly created web site cannot be started with the following message:

    Internet Information Services (IIS) Manager - The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

    ...it's possible that port 80 is already assigned to another application (Skype in my case :). You can change the binding port to e.g. 8080 by right clicking Default Web Site and selecting Edit Bindings... and Edit.... See Error 0x80070020 when you try to start a Web site in IIS 7.0 for details. Or you can just close the application sitting on the port 80, of course.

  2. Some applications require Default Web Site to have the ID 1. In my case, it got ID 1 after recreation automatically. If it's not your case, see Re-create “default Website” in IIS after accidentally deleting. It's different for IIS 6 and 7.


Note: I had to recreate the Default Web Site, because I wasn't able to even open a project configured to run under IIS in Visual Studio. I had a solution with a couple of projects inside. One of the projects failed to load with the following error message:

The Web Application Project is configured to use IIS. The Web server 'http://localhost:8080/' could not be found.

After I have recreated the Default Web Site in IIS Manager, I was able to reload and open that specific project.

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

Cut Corners using CSS

You can use clip-path, as Stewartside and Sviatoslav Oleksiv mentioned. To make things easy, I created a sass mixin:

@mixin cut-corners ($left-top, $right-top: 0px, $right-bottom: 0px, $left-bottom: 0px) {
  clip-path: polygon($left-top 0%, calc(100% - #{$right-top}) 0%, 100% $right-top, 100% calc(100% - #{$right-bottom}), calc(100% - #{$right-bottom}) 100%, $left-bottom 100%, 0% calc(100% - #{$left-bottom}), 0% $left-top);
}

.cut-corners {
  @include cut-corners(10px, 0, 25px, 50px);
}

Using "&times" word in html changes to ×

I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

  • in Short, There are 3 parameters in AsyncTask

    1. parameters for Input use in DoInBackground(String... params)

    2. parameters for show status of progress use in OnProgressUpdate(String... status)

    3. parameters for result use in OnPostExcute(String... result)

    Note : - [Type of parameters can vary depending on your requirement]

How can I override inline styles with external CSS?

used !important in CSS property

<div style="color: red;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
        color: blue !important;
    }

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

How to get unique values in an array

Or for those looking for a one-liner (simple and functional), compatible with current browsers:

_x000D_
_x000D_
let a = ["1", "1", "2", "3", "3", "1"];_x000D_
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);_x000D_
console.log(unique);
_x000D_
_x000D_
_x000D_

Update 18-04-2017

It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)

Update 29-07-2015:

There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.

Usage:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser support, source from mozilla):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n = 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

How to prevent multiple definitions in C?

You shouldn't include other source files (*.c) in .c files. I think you want to have a header (.h) file with the DECLARATION of test function, and have it's DEFINITION in a separate .c file.

The error is caused by multiple definitions of the test function (one in test.c and other in main.c)

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

SELECT CASE WHEN myfield="" THEN 0 ELSE myfield::integer END FROM mytable

I haven't ever worked with PostgreSQL but I checked the manual for the correct syntax of IF statements in SELECT queries.

Android, How to create option Menu

public class MenuTest extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.more_tab_menu, menu);

        // return true so that the menu pop up is opened
        return true; 
    }
}

and don't forget to press the menu button or icon on Emulator or device

Alternative to Intersect in MySQL

There is a more effective way of generating an intersect, by using UNION ALL and GROUP BY. Performances are twice better according to my tests on large datasets.

Example:

SELECT t1.value from (
  (SELECT DISTINCT value FROM table_a)
  UNION ALL 
  (SELECT DISTINCT value FROM table_b)
) AS t1 GROUP BY value HAVING count(*) >= 2;

It is more effective, because with the INNER JOIN solution, MySQL will look up for the results of the first query, then for each row, look up for the result in the second query. With the UNION ALL-GROUP BY solution, it will query results of the first query, results of the second query, then group the results all together at once.

Using $window or $location to Redirect in AngularJS

I believe the way to do this is $location.url('/RouteTo/Login');

Edit for Clarity

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.com/login"

Eclipse error: "The import XXX cannot be resolved"

In my case it was a broken jar in the Maven repository. Delete jar files in repository and let Maven download them again.

When I ran mvn clean install from the command line, it ran fine, but Eclipse still could not compile the code. When I ran maven install in Eclipse then I saw that Maven complained about bad jar file. So I deleted it and ran maven install again. The problem was gone.

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

What is wrong with my SQL here? #1089 - Incorrect prefix key

In PHPMyAdmin, Ignore / leave the size value empty on the pop-up window.

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

ORA-30926: unable to get a stable set of rows in the source tables

A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

ReactJS - .JS vs .JSX

JSX tags (<Component/>) are clearly not standard javascript and have no special meaning if you put them inside a naked <script> tag for example. Hence all React files that contain them are JSX and not JS.

By convention, the entry point of a React application is usually .js instead of .jsx even though it contains React components. It could as well be .jsx. Any other JSX files usually have the .jsx extension.

In any case, the reason there is ambiguity is because ultimately the extension does not matter much since the transpiler happily munches any kinds of files as long as they are actually JSX.

My advice would be: don't worry about it.

logger configuration to log to file and print to stdout

Here is a complete, nicely wrapped solution based on Waterboy's answer and various other sources. It supports logging to both console and log file, allows for different log level settings, provides colorized output and is easily configurable (also available as Gist):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------------
#                                                                               -
#  Python dual-logging setup (console and log file),                            -
#  supporting different log levels and colorized output                         -
#                                                                               -
#  Created by Fonic <https://github.com/fonic>                                  -
#  Date: 04/05/20                                                               -
#                                                                               -
#  Based on:                                                                    -
#  https://stackoverflow.com/a/13733863/1976617                                 -
#  https://uran198.github.io/en/python/2016/07/12/colorful-python-logging.html  -
#  https://en.wikipedia.org/wiki/ANSI_escape_code#Colors                        -
#                                                                               -
# -------------------------------------------------------------------------------

# Imports
import os
import sys
import logging

# Logging formatter supporting colored output
class LogFormatter(logging.Formatter):

    COLOR_CODES = {
        logging.CRITICAL: "\033[1;35m", # bright/bold magenta
        logging.ERROR:    "\033[1;31m", # bright/bold red
        logging.WARNING:  "\033[1;33m", # bright/bold yellow
        logging.INFO:     "\033[0;37m", # white / light gray
        logging.DEBUG:    "\033[1;30m"  # bright/bold black / dark gray
    }

    RESET_CODE = "\033[0m"

    def __init__(self, color, *args, **kwargs):
        super(LogFormatter, self).__init__(*args, **kwargs)
        self.color = color

    def format(self, record, *args, **kwargs):
        if (self.color == True and record.levelno in self.COLOR_CODES):
            record.color_on  = self.COLOR_CODES[record.levelno]
            record.color_off = self.RESET_CODE
        else:
            record.color_on  = ""
            record.color_off = ""
        return super(LogFormatter, self).format(record, *args, **kwargs)

# Setup logging
def setup_logging(console_log_output, console_log_level, console_log_color, logfile_file, logfile_log_level, logfile_log_color, log_line_template):

    # Create logger
    # For simplicity, we use the root logger, i.e. call 'logging.getLogger()'
    # without name argument. This way we can simply use module methods for
    # for logging throughout the script. An alternative would be exporting
    # the logger, i.e. 'global logger; logger = logging.getLogger("<name>")'
    logger = logging.getLogger()

    # Set global log level to 'debug' (required for handler levels to work)
    logger.setLevel(logging.DEBUG)

    # Create console handler
    console_log_output = console_log_output.lower()
    if (console_log_output == "stdout"):
        console_log_output = sys.stdout
    elif (console_log_output == "stderr"):
        console_log_output = sys.stderr
    else:
        print("Failed to set console output: invalid output: '%s'" % console_log_output)
        return False
    console_handler = logging.StreamHandler(console_log_output)

    # Set console log level
    try:
        console_handler.setLevel(console_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set console log level: invalid level: '%s'" % console_log_level)
        return False

    # Create and set formatter, add console handler to logger
    console_formatter = LogFormatter(fmt=log_line_template, color=console_log_color)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # Create log file handler
    try:
        logfile_handler = logging.FileHandler(logfile_file)
    except Exception as exception:
        print("Failed to set up log file: %s" % str(exception))
        return False

    # Set log file log level
    try:
        logfile_handler.setLevel(logfile_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set log file log level: invalid level: '%s'" % logfile_log_level)
        return False

    # Create and set formatter, add log file handler to logger
    logfile_formatter = LogFormatter(fmt=log_line_template, color=logfile_log_color)
    logfile_handler.setFormatter(logfile_formatter)
    logger.addHandler(logfile_handler)

    # Success
    return True

# Main function
def main():

    # Setup logging
    script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    if (not setup_logging(console_log_output="stdout", console_log_level="warning", console_log_color=True,
                        logfile_file=script_name + ".log", logfile_log_level="debug", logfile_log_color=False,
                        log_line_template="%(color_on)s[%(created)d] [%(threadName)s] [%(levelname)-8s] %(message)s%(color_off)s")):
        print("Failed to setup logging, aborting.")
        return 1

    # Log some messages
    logging.debug("Debug message")
    logging.info("Info message")
    logging.warning("Warning message")
    logging.error("Error message")
    logging.critical("Critical message")

# Call main function
if (__name__ == "__main__"):
    sys.exit(main())

NOTE regarding Microsoft Windows 10:
For colors to actually appear on Microsoft Windows 10, ANSI terminal mode has to be enabled first. Here is a function to do just that:

# Enable ANSI terminal on Microsoft Windows 10
# https://stackoverflow.com/a/36760881/1976617
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
def windows_enable_ansi_terminal():
    if (sys.platform != "win32"):
        return None
    try:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        result = kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
        if (result == 0): raise Exception
        return True
    except:
        return False

Closing WebSocket correctly (HTML5, Javascript)

According to the protocol spec v76 (which is the version that browser with current support implement):

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

Fragments within Fragments

.. you can cleanup your nested fragment in the parent fragment's destroyview method:

@Override
    public void onDestroyView() {

      try{
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.remove(nestedFragment);

        transaction.commit();
      }catch(Exception e){
      }

        super.onDestroyView();
    }

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I wrote a quick simple app recent that handle the management of various version of node and npm. It allows you to choose different version of node and npm to download and select which version to use. Check it out and see if it's something that's useful.

https://github.com/nhatkthanh/wnm

How to set breakpoints in inline Javascript in Google Chrome?

Adding debugger; on top at my script worked for me.

How do you copy a record in a SQL table but swap out the unique id of the new row?

Try this:


insert into MyTable(field1, field2, id_backup)
    select field1, field2, uniqueId from MyTable where uniqueId = @Id;

Any fields not specified should receive their default value (which is usually NULL when not defined).

Mockito: Trying to spy on method is calling the original method

One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.

Example

@Autowired
private MonitoringDocumentsRepository repository

void test(){
    repository = Mockito.spy(repository)
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:

repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$

@SpyBean to the rescue

If instead @Autowired annotation we use @SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger

repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$

and here is the code:

@SpyBean
private MonitoringDocumentsRepository repository

void test(){
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

z-index not working with fixed positioning

z-index only works within a particular context i.e. relative, fixed or absolute position.

z-index for a relative div has nothing to do with the z-index of an absolutely or fixed div.

EDIT This is an incomplete answer. This answer provides false information. Please review @Dansingerman's comment and example below.

Can I use return value of INSERT...RETURNING in another INSERT?

You can do so starting with Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();

How do I join two lines in vi?

Vi or Vim?

Anyway, the following command works for Vim in 'nocompatible' mode. That is, I suppose, almost pure vi.

:join!

If you want to do it from normal command use

gJ

With 'gJ' you join lines as is -- without adding or removing whitespaces:

S<Switch_ID>_F<File type>
_ID<ID number>_T<date+time>_O<Original File name>.DAT

Result:

S<Switch_ID>_F<File type>_ID<ID number>_T<date+time>_O<Original File name>.DAT

With 'J' command you will have:

S<Switch_ID>_F<File type> _ID<ID number>_T<date+time>_O<Original File name>.DAT

Note space between type> and _ID.

Regex that matches integers in between whitespace or start/end of string only

^(-+)?[1-9][0-9]*$ starts with a - or + for 0 or 1 times, then you want a non zero number (because there is not such a thing -0 or +0) and then it continues with any number from 0 to 9

Difference between "git add -A" and "git add ."

From Charles' instructions, after testing my proposed understanding would be as follows:

# For the next commit
$ git add .   # Add only files created/modified to the index and not those deleted
$ git add -u  # Add only files deleted/modified to the index and not those created
$ git add -A  # Do both operations at once, add to all files to the index

This blog post might also be helpful to understand in what situation those commands may be applied: Removing Deleted Files from your Git Working Directory.

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

How can I check the size of a file in a Windows batch script?

After a few "try and test" iterations I've found a way (still not present here) to get size of file in cycle variable (not a command line parameter):

for %%i in (*.txt) do (
    echo %%~z%i
)

How to run a program in Atom Editor?

You can try to use the runner in atom Hit Ctrl+R (Alt+R on Win/Linux) to launch the runner for the active window. Hit Ctrl+Shift+R (Alt+Shift+R on Win/Linux) to run the currently selected text in the active window. Hit Ctrl+Shift+C to kill a currently running process. Hit Escape to close the runner window

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:

   os.path.basename(filename)

due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

How to set value in @Html.TextBoxFor in Razor syntax?

It is going to write the value of your property model.Destination

This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.

What are the differences in die() and exit() in PHP?

They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.

Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.

Then you can use exit() and catch that later on. Die() however doesn't support that.

Die() always exists with code 0. So essentially a die() command does the following:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>

How can I use an http proxy with node.js http.Client?

If you have the Basic http authentication scheme you have to make a base64 string of myuser:mypassword, and then add "Basic" in the beginning. That's the value of Proxy-Authorization header, here an example:

var Http = require('http');

var req = Http.request({
    host: 'myproxy.com.zx',
    port: 8080,
    headers:{"Proxy-Authorization": "Basic bXl1c2VyOm15cGFzc3dvcmQ="},
    method: 'GET',
    path: 'http://www.google.com/'
    }, function (res) {
        res.on('data', function (data) {
        console.log(data.toString());
    });
});

req.end();

In nodejs you could use Buffer to encode

var encodedData = Buffer.from('myuser:mypassword').toString('base64');

console.log(encodedData);

Just as example, in browsers you could encode in base64 using btoa(), useful in ajax requests in a browser without proxy settings performing a request using proxy.

_x000D_
_x000D_
var encodedData = btoa('myuser:mypassword')_x000D_
_x000D_
console.log(encodedData);
_x000D_
_x000D_
_x000D_

How to find wich scheme accepts the proxy server?

If we don't have a custom DNS configured (that would throw something like ERR_NAME_NOT_RESOLVED), when we perform a request, the response (code 407) should inform in the response headers which http authentication scheme the proxy is using.

Adding a directory to the PATH environment variable in Windows

  1. I have installed PHP that time. Extracted php-7***.zip into C:\php\
  2. Backup my current PATH environment variable: run cmd, and execute command: path >C:\path-backup.txt

  3. Get my current path value into C:\path.txt file (same way)

  4. Modify path.txt (sure, my path length is more than 1024 chars, windows is running few years)
    • I have removed duplicates paths in there, like 'C:\Windows; or C:\Windows\System32; or C:\Windows\System32\Wbem; - I've got twice.
    • Remove uninstalled programs paths as well. Example: C:\Program Files\NonExistSoftware;
    • This way, my path string length < 1024 :)))
    • at the end of path string add ;C:\php\
    • Copy path value only into buffer with framed double quotes! Example: "C:\Windows;****;C:\php\" No PATH= should be there!!!
  5. Open Windows PowerShell as Administrator.
  6. Run command:

setx path "Here you should insert string from buffer (new path value)"

  1. Re-run your terminal (I use "Far manager") and check: php -v

Print the contents of a DIV

Here is my jquery print plugin

(function ($) {

$.fn.printme = function () {
    return this.each(function () {
        var container = $(this);

        var hidden_IFrame = $('<iframe></iframe>').attr({
            width: '1px',
            height: '1px',
            display: 'none'
        }).appendTo(container);

        var myIframe = hidden_IFrame.get(0);

        var script_tag = myIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
        script_tag.appendChild(script);

        myIframe.contentWindow.document.body.innerHTML = container.html();
        myIframe.contentWindow.document.body.appendChild(script_tag);

        myIframe.contentWindow.Print();
        hidden_IFrame.remove();

    });
};
})(jQuery);

sweet-alert display HTML code in text

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

jquery: $(window).scrollTop() but no $(window).scrollBottom()

Here is the best option scroll to bottom for table grid, it will be scroll to the last row of the table grid :

 $('.add-row-btn').click(function () {
     var tempheight = $('#PtsGrid > table').height();
     $('#PtsGrid').animate({
         scrollTop: tempheight
         //scrollTop: $(".scroll-bottom").offset().top
     }, 'slow');
 });

App.settings - the Angular way?

It's not advisable to use the environment.*.ts files for your API URL configuration. It seems like you should because this mentions the word "environment".

Using this is actually compile-time configuration. If you want to change the API URL, you will need to re-build. That's something you don't want to have to do ... just ask your friendly QA department :)

What you need is runtime configuration, i.e. the app loads its configuration when it starts up.

Some other answers touch on this, but the difference is that the configuration needs to be loaded as soon as the app starts, so that it can be used by a normal service whenever it needs it.

To implement runtime configuration:

  1. Add a JSON config file to the /src/assets/ folder (so that is copied on build)
  2. Create an AppConfigService to load and distribute the config
  3. Load the configuration using an APP_INITIALIZER

1. Add Config file to /src/assets

You could add it to another folder, but you'd need to tell the CLI that it is an asset in the angular.json. Start off using the assets folder:

{
  "apiBaseUrl": "https://development.local/apiUrl"
}

2. Create AppConfigService

This is the service which will be injected whenever you need the config value:

@Injectable({
  providedIn: 'root'
})
export class AppConfigService {

  private appConfig: any;

  constructor(private http: HttpClient) { }

  loadAppConfig() {
    return this.http.get('/assets/config.json')
      .toPromise()
      .then(data => {
        this.appConfig = data;
      });
  }

  // This is an example property ... you can make it however you want.
  get apiBaseUrl() {

    if (!this.appConfig) {
      throw Error('Config file not loaded!');
    }

    return this.appConfig.apiBaseUrl;
  }
}

3. Load the configuration using an APP_INITIALIZER

To allow the AppConfigService to be injected safely, with config fully loaded, we need to load the config at app startup time. Importantly, the initialisation factory function needs to return a Promise so that Angular knows to wait until it finishes resolving before finishing startup:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [AppConfigService],
      useFactory: (appConfigService: AppConfigService) => {
        return () => {
          //Make sure to return a promise!
          return appConfigService.loadAppConfig();
        };
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now you can inject it wherever you need to and all the config will be ready to read:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  apiBaseUrl: string;

  constructor(private appConfigService: AppConfigService) {}

  ngOnInit(): void {
    this.apiBaseUrl = this.appConfigService.apiBaseUrl;
  }

}

I can't say it strongly enough, configuring your API urls as compile-time configuration is an anti-pattern. Use runtime configuration.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

Android/Java - Date Difference in days

Joda-Time

Best way is to use Joda-Time, the highly successful open-source library you would add to your project.

String date1 = "2015-11-11";
String date2 = "2013-11-11";
DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
long diffInMillis = d2.getMillis() - d1.getMillis();

Duration duration = new Duration(d1, d2);
int days = duration.getStandardDays();
int hours = duration.getStandardHours();
int minutes = duration.getStandardMinutes();

If you're using Android Studio, very easy to add joda-time. In your build.gradle (app):

dependencies {
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.2'
}

Differences between .NET 4.0 and .NET 4.5 in High level in .NET


.NET Framework 4


Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).
  • Introduce Common Language Runtime (CLR) 4.0.

After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.


.NET Framework 4.5


.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.

1. .NET for Metro style apps

Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.

2. Core Features

  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
  • Ability to define the culture for an application domain.
  • Console support for Unicode (UTF-16) encoding.
  • Support for versioning of cultural string ordering and comparison data.
  • Better performance when retrieving resources.
  • Zip compression improvements to reduce the size of a compressed file.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

3. Managed Extensibility Framework (MEF)

  • Support for generic types.
  • Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
  • Multiple scopes.

4. Asynchronous operations

In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.

5. ASP.NET

  • Support for new HTML5 form types.
  • Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
  • Support for unobtrusive JavaScript in client-side validation scripts.
  • Improved handling of client script through bundling and minification for improved page performance.
  • Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
  • Support for WebSocket protocol.
  • Support for reading and writing HTTP requests and responses asynchronously.
  • Support for asynchronous modules and handlers.
  • Support for content distribution network (CDN) fallback in the ScriptManager control.

6. Networking

  • Provides a new programming interface for HTTP applications: System.Net.Http namespace and System.Net.Http.Headers namespaces are added.
  • Other improvements: Improved internationalization and IPv6 support. RFC-compliant URI support. Support for Internationalized Domain Name (IDN) parsing. Support for Email Address Internationalization (EAI).

7. Windows Presentation Foundation (WPF)

  • The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
  • The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
  • New features for the VirtualizingPanel and Dispatcher classes.
  • Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
  • Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface and retrieval of data binding information from a binding expression.
  • Repositioning of data as the values change (live shaping).
  • Better integration between WPF and Win32 user interface components.
  • Ability to check whether the data context for an item container is disconnected.
  • Ability to set the amount of time that should elapse between property changes and data source updates.
  • Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

8. Windows Communication Foundation (WCF)

In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

  • Simplification of generated configuration files.
  • Support for contract-first development.
  • Ability to configure ASP.NET compatibility mode more easily.
  • Changes in default transport property values to reduce the likelihood that you will have to set them.
  • Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
  • Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
  • New asynchronous streaming support.
  • New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
  • Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
  • Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
  • Support for configuring services in code.
  • XML Editor tooltips.
  • ChannelFactory caching support.
  • Binary encoder compression support.
  • Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. A client sends a message to a service and expects no response from the service.
  • Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.
  • Support for WCF services that use internationalized domain names (IDNs).

9. Tools

  • Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows Store apps from a .resources file embedded in a .NET Framework assembly.
  • Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. The command-line tool generates profile data for native image application assemblies.

For more information and access to reference links, please visit:

===========.Net 4.5 Poster=========

enter image description here

How can I check if an argument is defined when starting/calling a batch file?

This is the same as the other answers, but uses only one label and puts the usage first, which additionally makes it serve as a kind of documentation commend of the script which is also usually placed at the top:

@echo off
:: add other test for the arguments here...
if not [%1]==[] goto main
:: --------------------------
echo This command does something.
echo.
echo %0 param%%1 param%%2
echo       param%%1 the file to operate on
echo       param%%1 another file

:: --------------------------
exit /B 1

:main
:: --------------------------
echo do something with all arguments (%%* == %*) here...

However, if you don't have to use cmd/batch, use bash on WSL or powershell, they have more sane syntax and less arcane features.

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

Tracing XML request/responses with JAX-WS

In runtime you could simply execute

com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump = true

as dump is a public var defined in the class as follows

public static boolean dump;

Python Requests library redirect new url

You are looking for the request history.

The response.history attribute is a list of responses that led to the final URL, which can be found in response.url.

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

Demo:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

How can I replace text with CSS?

This worked for me with inline text. It was tested in Firefox, Safari, Chrome, and Opera.

<p>Lorem ipsum dolor sit amet, consectetur <span>Some Text</span> adipiscing elit.</p>

span {
    visibility: hidden;
    word-spacing: -999px;
    letter-spacing: -999px;
}

span:after {
    content: "goodbye";
    visibility: visible;
    word-spacing: normal;
    letter-spacing: normal;
}

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

Import numpy on pycharm

I added Anaconda3/Library/Bin to the environment path and PyCharm no longer complained with the error.

Stated by https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001194720/comments/360000341500

Set select option 'selected', by value

The easiest way to do that is:

HTML

<select name="dept">
   <option value="">Which department does this doctor belong to?</option>
   <option value="1">Orthopaedics</option>
   <option value="2">Pathology</option>
   <option value="3">ENT</option>
</select>

jQuery

$('select[name="dept"]').val('3');

Output: This will activate ENT.

Alternative to google finance api

If you are still looking to use Google Finance for your data you can check this out.

I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)

Adding Lombok plugin to IntelliJ project

There is a lot of really helpful info posted here, but there is one thing that all the posts seem to have wrong. I could not find any 'Settings' option under 'Files', and I hunted around for 10 minutes looking through all the menus until I found the settings under 'IntelliJ IDE' -> 'Preferences'.

I don't know if I am using a differing OS version or IntelliJ version from other posters, or if it is because I am a stupid Windows user that doesn't know that settings == preferences on a mac (Did I miss the memo?), but I hope this helps you if you aren't finding the paths that other posts are suggesting.

div with dynamic min-height based on browser window height

If #top and #bottom have fixed heights, you can use:

#top {
    position: absolute;
    top: 0;
    height: 200px;
}
#bottom {
    position: absolute;
    bottom: 0;
    height: 100px;
}
#central {
    margin-top: 200px;
    margin-bot: 100px;
}

update

If you want #central to stretch down, you could:

  • Fake it with a background on parent;
  • Use CSS3's (not widely supported, most likely) calc();
  • Or maybe use javascript to dynamically add min-height.

With calc():

#central {
    min-height: calc(100% - 300px);
}

With jQuery it could be something like:

$(document).ready(function() {
  var desiredHeight = $("body").height() - $("top").height() - $("bot").height();
  $("#central").css("min-height", desiredHeight );
});

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

How can I set a dynamic model name in AngularJS?

You can use something like this scopeValue[field], but if your field is in another object you will need another solution.

To solve all kind of situations, you can use this directive:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);

Html example:

<input dynamic-model="'scopeValue.' + field" type="text">

How to convert answer into two decimal point

Try using the Format function:

Private Sub btncalc_Click(ByVal sender As System.Object,
                          ByVal e As System.EventArgs) Handles btncalc.Click
  txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                     Val(txtF.Text) / Val(txtE.Text), "0.00")
  txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

Encrypt and Decrypt text with RSA in PHP

I have difficulty in decrypting a long string that is encrypted in python. Here is the python encryption function:

def RSA_encrypt(public_key, msg, chunk_size=214):
    """
    Encrypt the message by the provided RSA public key.

    :param public_key: RSA public key in PEM format.
    :type public_key: binary
    :param msg: message that to be encrypted
    :type msg: string
    :param chunk_size: the chunk size used for PKCS1_OAEP decryption, it is determined by \
    the private key length used in bytes - 42 bytes.
    :type chunk_size: int
    :return: Base 64 encryption of the encrypted message
    :rtype: binray
    """
    rsa_key = RSA.importKey(public_key)
    rsa_key = PKCS1_OAEP.new(rsa_key)

    encrypted = b''
    offset = 0
    end_loop = False

    while not end_loop:
        chunk = msg[offset:offset + chunk_size]

        if len(chunk) % chunk_size != 0:
            chunk += " " * (chunk_size - len(chunk))
            end_loop = True

        encrypted += rsa_key.encrypt(chunk.encode())
        offset += chunk_size

    return base64.b64encode(encrypted)

The decryption in PHP:

/**
 * @param  base64_encoded string holds the encrypted message.
 * @param  Resource your private key loaded using openssl_pkey_get_private
 * @param  integer Chunking by bytes to feed to the decryptor algorithm.
 * @return String decrypted message.
 */
public function RSADecyrpt($encrypted_msg, $ppk, $chunk_size=256){
    if(is_null($ppk))
        throw new Exception("Returned message is encrypted while you did not provide private key!");
    $encrypted_msg = base64_decode($encrypted_msg);

    $offset = 0;
    $chunk_size = 256;

    $decrypted = "";
    while($offset < strlen($encrypted_msg)){
        $decrypted_chunk = "";
        $chunk = substr($encrypted_msg, $offset, $chunk_size);

        if(openssl_private_decrypt($chunk, $decrypted_chunk, $ppk, OPENSSL_PKCS1_OAEP_PADDING))
            $decrypted .= $decrypted_chunk;
        else 
            throw new exception("Problem decrypting the message");
        $offset += $chunk_size;
    }
    return $decrypted;
}

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

how to run mysql in ubuntu through terminal

You seem to just have begun using mysql.

Simple answer: for now use

mysql -u root -p password

Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.

Input and output numpy arrays to h5py

h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:

http://docs.h5py.org/en/latest/quick.html

A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:

In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()

You can then load that data back in using: '

In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True

Definitely check out the docs:

http://docs.h5py.org

Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save, np.savez etc:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

Consider using needle - tool for automated visual comparison https://github.com/bfirsh/needle , which has built-in functionality that allows to take screenshots of specific elements (selected by CSS selector). The tool works on Selenium's WebDriver and it's written in Python.

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Setting top and left CSS attributes

Your problem is that the top and left properties require a unit of measure, not just a bare number:

div.style.top = "200px";
div.style.left = "200px";

Where does flask look for image files?

From the documentation:

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css')

The file has to be stored on the filesystem as static/style.css.

How can I change the color of my prompt in zsh (different from normal text)?

Put this in ~/.zshrc:

autoload -U colors && colors
PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%~ %{$reset_color%}%% "

Supported Colors:
red, blue, green, cyan, yellow, magenta, black, & white (from this answer) although different computers may have different valid options.

Surround color codes (and any other non-printable chars) with %{....%}. This is for the text wrapping to work correctly.

Additionally, here is how you can get this to work with the directory-trimming from here.

PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%(5~|%-1~/.../%3~|%4~) %{$reset_color%}%% "