Programs & Examples On #Unions

The plural of a keyword in the C family of languages for declaring a union data type.

Purpose of Unions in C and C++

In C++, Boost Variant implement a safe version of the union, designed to prevent undefined behavior as much as possible.

Its performances are identical to the enum + union construct (stack allocated too etc) but it uses a template list of types instead of the enum :)

Why do we need C Unions?

Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:

set a to b times 7.

consists of the following language elements:

  • symbol[set]
  • variable[a]
  • symbol[to]
  • variable[b]
  • symbol[times]
  • constant[7]
  • symbol[.]

Language elements were defines as '#define' values thus:

#define ELEM_SYM_SET        0
#define ELEM_SYM_TO         1
#define ELEM_SYM_TIMES      2
#define ELEM_SYM_FULLSTOP   3
#define ELEM_VARIABLE     100
#define ELEM_CONSTANT     101

and the following structure was used to store each element:

typedef struct {
    int typ;
    union {
        char *str;
        int   val;
    }
} tElem;

then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).

In order to create a "set" element, you would use:

tElem e;
e.typ = ELEM_SYM_SET;

In order to create a "variable[b]" element, you would use:

tElem e;
e.typ = ELEM_VARIABLE;
e.str = strdup ("b");   // make sure you free this later

In order to create a "constant[7]" element, you would use:

tElem e;
e.typ = ELEM_CONSTANT;
e.val = 7;

and you could easily expand it to include floats (float flt) or rationals (struct ratnl {int num; int denom;}) and other types.

The basic premise is that the str and val are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010 and integers and pointers are both 4 bytes:

       +-----------+
0x1010 |           |
0x1011 |    typ    |
0x1012 |           |
0x1013 |           |
       +-----+-----+
0x1014 |     |     |
0x1015 | str | val |
0x1016 |     |     |
0x1017 |     |     |
       +-----+-----+

If it were just in a structure, it would look like this:

       +-------+
0x1010 |       |
0x1011 |  typ  |
0x1012 |       |
0x1013 |       |
       +-------+
0x1014 |       |
0x1015 |  str  |
0x1016 |       |
0x1017 |       |
       +-------+
0x1018 |       |
0x1019 |  val  |
0x101A |       |
0x101B |       |
       +-------+

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

Difference between a Structure and a Union

what is the difference between structure and union?

Short cut answer is: The deference is in memory allocation. Explanation: In structure, memory space will be created for all members inside structure. In union memory space will be created only for a member which needs largest memory space. Consider the following code:

struct s_tag
{
   int a; 
   long int b;
} x;

union u_tag
{
   int a; 
   long int b;
} y;

Here there are two members inside struct and union: int and long int. Memory space for int is: 4 byte and Memory space for long int is: 8 in 32 bit operating system.

So for struct 4+8=12 bytes will be created while 8 bytes will be created for union

Code example:

#include<stdio.h>
struct s_tag
{
  int a;
  long int b;
} x;
union u_tag
{
     int a;
     long int b;
} y;
int main()
{
    printf("Memory allocation for structure = %d", sizeof(x));
    printf("\nMemory allocation for union = %d", sizeof(y));
    return 0;
}

Ref:http://www.codingpractise.com/home/c-programming/structure-and-union/

Django Rest Framework -- no module named rest_framework

if you used pipenv:

if you installed rest_framework thru the new pipenv, you need to run it thru the virtual environment:

1.pipenv shell

2.(env) now, run your command(for example python manage.py runserver)

Print empty line?

Python 2.x: Prints a newline

print      

Python 3.x: You must call the function

print() 

Source: https://docs.python.org/3.0/whatsnew/3.0.html

Virtual Memory Usage from Java under Linux, too much memory used

The amount of memory allocated for the Java process is pretty much on-par with what I would expect. I've had similar problems running Java on embedded/memory limited systems. Running any application with arbitrary VM limits or on systems that don't have adequate amounts of swap tend to break. It seems to be the nature of many modern apps that aren't design for use on resource-limited systems.

You have a few more options you can try and limit your JVM's memory footprint. This might reduce the virtual memory footprint:

-XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]

-XX:MaxPermSize=64m Size of the Permanent Generation. [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]

Also, you also should set your -Xmx (max heap size) to a value as close as possible to the actual peak memory usage of your application. I believe the default behavior of the JVM is still to double the heap size each time it expands it up to the max. If you start with 32M heap and your app peaked to 65M, then the heap would end up growing 32M -> 64M -> 128M.

You might also try this to make the VM less aggressive about growing the heap:

-XX:MinHeapFreeRatio=40 Minimum percentage of heap free after GC to avoid expansion.

Also, from what I recall from experimenting with this a few years ago, the number of native libraries loaded had a huge impact on the minimum footprint. Loading java.net.Socket added more than 15M if I recall correctly (and I probably don't).

angular ng-repeat in reverse

You can reverse by the $index parameter

<tr ng-repeat="friend in friends | orderBy:'$index':true">

SQL Server : SUM() of multiple rows including where clauses

The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

How to make CSS width to fill parent?

almost there, just change outerWidth: 100%; to width: auto; (outerWidth is not a CSS property)

alternatively, apply the following styles to bar:

width: auto;
display: block;

Evaluating string "3*(4+2)" yield int 18

I recently needed to do this for a project and I ended up using IronPython to do it. You can declare an instance of the engine, and then pass any valid python expression and get the result. If you're just doing simple math expressions, then it would suffice. My code ended up looking similar to:

IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();
string expression = "3*(2+4)";
double result = pythonEngine.EvaluateAs<double>(expression);

You'd probably not want to create the engine for each expression. You also need a reference to IronPython.dll

"FATAL: Module not found error" using modprobe

Ensure that your network is brought down before loading module:

sudo stop networking

It helped me - https://help.ubuntu.com/community/UbuntuBonding

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

How to use Chrome's network debugger with redirects

This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.


Current (= v32)

At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.

Chrome v33 DevTools Network Tab: Preserve Log

The little red dot on the left now has the purpose to switch network logging on and off completely.


Older versions

In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.

Chrome v22 DevTools Network Tab: Preserve Log Upon Navigation

If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.

Why does one use dependency injection?

As the other answers stated, dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. This is also why dependency injection is a realization of the Inversion of control (IoC) principle.

IoC is the principle, where DI is the pattern. The reason that you might "need more than one logger" is never actually met, as far as my experience goes, but the actualy reason is, that you really need it, whenever you test something. An example:

My Feature:

When I look at an offer, I want to mark that I looked at it automatically, so that I don't forget to do so.

You might test this like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var formdata = { . . . }

    // System under Test
    var weasel = new OfferWeasel();

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(new DateTime(2013,01,13,13,01,0,0));
}

So somewhere in the OfferWeasel, it builds you an offer Object like this:

public class OfferWeasel
{
    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = DateTime.Now;
        return offer;
    }
}

The problem here is, that this test will most likely always fail, since the date that is being set will differ from the date being asserted, even if you just put DateTime.Now in the test code it might be off by a couple of milliseconds and will therefore always fail. A better solution now would be to create an interface for this, that allows you to control what time will be set:

public interface IGotTheTime
{
    DateTime Now {get;}
}

public class CannedTime : IGotTheTime
{
    public DateTime Now {get; set;}
}

public class ActualTime : IGotTheTime
{
    public DateTime Now {get { return DateTime.Now; }}
}

public class OfferWeasel
{
    private readonly IGotTheTime _time;

    public OfferWeasel(IGotTheTime time)
    {
        _time = time;
    }

    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = _time.Now;
        return offer;
    }
}

The Interface is the abstraction. One is the REAL thing, and the other one allows you to fake some time where it is needed. The test can then be changed like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var date = new DateTime(2013, 01, 13, 13, 01, 0, 0);
    var formdata = { . . . }

    var time = new CannedTime { Now = date };

    // System under test
    var weasel= new OfferWeasel(time);

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(date);
}

Like this, you applied the "inversion of control" principle, by injecting a dependency (getting the current time). The main reason to do this is for easier isolated unit testing, there are other ways of doing it. For example, an interface and a class here is unnecessary since in C# functions can be passed around as variables, so instead of an interface you could use a Func<DateTime> to achieve the same. Or, if you take a dynamic approach, you just pass any object that has the equivalent method (duck typing), and you don't need an interface at all.

You will hardly ever need more than one logger. Nonetheless, dependency injection is essential for statically typed code such as Java or C#.

And... It should also be noted that an object can only properly fulfill its purpose at runtime, if all its dependencies are available, so there is not much use in setting up property injection. In my opinion, all dependencies should be satisfied when the constructor is being called, so constructor-injection is the thing to go with.

I hope that helped.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

GitLab git user password

I had this same problem when using a key of 4096 bits:

$ ssh-keygen -t rsa -C "GitLab" -b 4096
$ ssh -vT git@gitlabhost
...
debug1: Offering public key: /home/user/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/user/.ssh/id_dsa
debug1: Trying private key: /home/user/.ssh/id_ecdsa
debug1: Next authentication method: password
git@gitlabhost's password:
Connection closed by host

But with the 2048 bit key (the default size), ssh connects to gitlab without prompting for a password (after adding the new pub key to the user's gitlab ssh keys)

$ ssh-keygen -t rsa -C "GitLab"
$ ssh -vT git@gitlabhost
Welcome to GitLab, Joe User!

How to sort List of objects by some property

public class ActiveAlarm implements Comparable<ActiveAlarm> {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public int compareTo(ActiveAlarm a) {
        if ( this.timeStarted > a.timeStarted )
            return 1;
        else if ( this.timeStarted < a.timeStarted )
            return -1;
        else {
             if ( this.timeEnded > a.timeEnded )
                 return 1;
             else
                 return -1;
        }
 }

That should give you a rough idea. Once that's done, you can call Collections.sort() on the list.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

RegEx for validating an integer with a maximum length of 10 characters

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

How does "cat << EOF" work in bash?

The cat <<EOF syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.

Examples of cat <<EOF syntax usage in Bash:

1. Assign multi-line string to a shell variable

$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql".

2. Pass multi-line string to a file in Bash

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user

3. Pass multi-line string to a pipe in Bash

$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

The b.txt file contains bar and baz lines. The same output is printed to stdout.

How do I trim() a string in angularjs?

If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead.

app.filter('trim', function () {
    return function(value) {
        if(!angular.isString(value)) {
            return value;
        }  
        return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
    };
});

And then

<span>{{ foo | trim }}</span>

contenteditable change events

This thread was very helpful while I was investigating the subject.

I've modified some of the code available here into a jQuery plugin so it is in a re-usable form, primarily to satisfy my needs but others may appreciate a simpler interface to jumpstart using contenteditable tags.

https://gist.github.com/3410122

Update:

Due to its increasing popularity the plugin has been adopted by Makesites.org

Development will continue from here:

https://github.com/makesites/jquery-contenteditable

How to determine when a Git branch was created?

very simple

In the address bar of your web browser, type the following URL and press the Enter key to retrieve information of a GitHub repository.

https://api.github.com/repos/{:owner}/{:repository}

Note! In the URL above, replace the {:owner} and {:repository} parts with the values that can be found in the URL of the GitHub repository for which you want to know the creation date. For example, if the URL of the repository is https://github.com/ArthurGareginyan/batch-rename/, then the URL of it’s information will be https://api.github.com/repos/ArthurGareginyan/batch-rename.

output:

image

Get list from pandas DataFrame column headers

A DataFrame follows the dict-like convention of iterating over the “keys” of the objects.

my_dataframe.keys()

Create a list of keys/columns - object method to_list() and pythonic way

my_dataframe.keys().to_list()
list(my_dataframe.keys())

Basic iteration on a DataFrame returns column labels

[column for column in my_dataframe]

Do not convert a DataFrame into a list, just to get the column labels. Do not stop thinking while looking for convenient code samples.

xlarge = pd.DataFrame(np.arange(100000000).reshape(10000,10000))
list(xlarge) #compute time and memory consumption depend on dataframe size - O(N)
list(xlarge.keys()) #constant time operation - O(1)

How do I drop a MongoDB database from the command line?

Open another terminal window and execute the following commands,

mongodb
use mydb
db.dropDatabase()

Output of that operation shall look like the following

MAC:FOLDER USER$ mongodb
> show databases
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
> use mydb
switched to db mydb
>db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
>

Please note that mydb is still in use, hence inserting any input at that time will initialize the database again.

What should a JSON service return on failure / error

Yes, you should use HTTP status codes. And also preferably return error descriptions in a somewhat standardized JSON format, like Nottingham’s proposal, see apigility Error Reporting:

The payload of an API Problem has the following structure:

  • type: a URL to a document describing the error condition (optional, and "about:blank" is assumed if none is provided; should resolve to a human-readable document; Apigility always provides this).
  • title: a brief title for the error condition (required; and should be the same for every problem of the same type; Apigility always provides this).
  • status: the HTTP status code for the current request (optional; Apigility always provides this).
  • detail: error details specific to this request (optional; Apigility requires it for each problem).
  • instance: URI identifying the specific instance of this problem (optional; Apigility currently does not provide this).

HTML/CSS--Creating a banner/header

Remove the z-index value.

I would also recommend this approach.

HTML:

<header class="main-header" role="banner">
  <img src="mybannerimage.gif" alt="Banner Image"/>
</header>

CSS:

.main-header {
  text-align: center;
}

This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.

Using $window or $location to Redirect in AngularJS

Not sure from what version, but I use 1.3.14 and you can just use:

window.location.href = '/employee/1';

No need to inject $location or $window in the controller and no need to get the current host address.

Message 'src refspec master does not match any' when pushing commits in Git

First you need to git init to create your own .git file, otherwise if you clone someones git folder it will not recognize your git credential. After you started git, then continue with git add. and git commit ...

How do I crop an image in Java?

This is a method which will work:

import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;

public BufferedImage crop(BufferedImage src, Rectangle rect)
{
    BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_ARGB_PRE);
    Graphics g = dest.getGraphics();
    g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null);
    g.dispose();
    return dest;
}

Of course you have to make your own JComponent:

import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Graphics;
import javax.swing.JComponent;

public class JImageCropComponent extends JComponent implements MouseListener, MouseMotionListener
{
   private BufferedImage img;
   private int x1, y1, x2, y2;

   public JImageCropComponent(BufferedImage img)
   {
       this.img = img;
       this.addMouseListener(this);
       this.addMouseMotionListener(this);
   }

   public void setImage(BufferedImage img)
   {
       this.img = img;
   }

   public BufferedImage getImage()
   {
       return this;
   }

   @Override
   public void paintComponent(Graphics g)
   {
      g.drawImage(img, 0, 0, this);
      if (cropping)
      {
          // Paint the area we are going to crop.
          g.setColor(Color.RED);
          g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
      }
   }

   @Override
   public void mousePressed(MouseEvent evt)
   {
       this.x1 = evt.getX();
       this.y1 = evt.getY();
   }

   @Override
   public void mouseReleased(MouseEvent evt)
   {
       this.cropping = false;
       // Now we crop the image;
       // This is the method a wrote in the other snipped
       BufferedImage cropped = crop(new Rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
       // Now you have the cropped image;
       // You have to choose what you want to do with it
       this.img = cropped;
   }

   @Override
   public void mouseDragged(MouseEvent evt)
   {
       cropping = true;
       this.x2 = evt.getX();
       this.y2 = evt.getY();
   }

   //TODO: Implement the other unused methods from Mouse(Motion)Listener

}

I didn't test it. Maybe there are some mistakes (I'm not sure about all the imports).

You can put the crop(img, rect) method in this class. Hope this helps.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Changing the default icon in a Windows Forms application

Add your icon as a Resource (Project > yourprojectname Properties > Resources > Pick "Icons from dropdown > Add Resource (or choose Add Existing File from dropdown if you already have the .ico)

Then:

this.Icon = Properties.Resources.youriconname;

ViewPager PagerAdapter not updating the View

The best solution from my experience : https://stackoverflow.com/a/44177688/3118950, which is override the long getItemId() and return unique ID instead of the default position. In addition to that answer is imported to notice that old fragment will be kept in the fragment manager in case the total amount is less than the page limit and onDetach()/onDestory() will not be called when the fragment is replaced.

Grouping into interval of 5 minutes within a time range

This works with every interval.

PostgreSQL

SELECT
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * round(extract('epoch' from timestamp) / 300) * 300 as timestamp,
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
round(extract('epoch' from timestamp) / 300), name


MySQL

SELECT
    timestamp,  -- not sure about that
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
UNIX_TIMESTAMP(timestamp) DIV 300, name

java - iterating a linked list

Linked list is guaranteed to act in sequential order.

From the documentation

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

iterator() Returns an iterator over the elements in this list in proper sequence.

Python datetime strptime() and strftime(): how to preserve the timezone information

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")

It will print something like

2017-08-10 20:46:24 +0800

Delete all the queues from RabbitMQ?

For whose have a problem with installing rabbitmqadmin, You should firstly install python.

UNIX-like operating system users need to copy rabbitmqadmin to a directory in PATH, e.g. /usr/local/bin.

Windows users will need to ensure Python is on their PATH, and invoke rabbitmqadmin as python.exe rabbitmqadmin.

Then

  1. Browse to http://{hostname}:15672/cli/rabbitmqadmin to download.
  2. Go to the containing folder then run cmd with administrator privilege

To list Queues python rabbitmqadmin list queues.

To delete Queue python rabbitmqadmin delete queue name=Name_of_queue

To Delete all Queues

1- Declare Policy

python rabbitmqadmin declare policy name='expire_all_policies' pattern=.* definition={\"expires\":1} apply-to=queues

2- Remove the policy

python rabbitmqadmin  delete policy name='expire_all_policies'

Formatting a Date String in React Native

Easily accomplished using a package.

Others have mentioned Moment. Moment is great but very large for a simple use like this, and unfortunately not modular so you have to import the whole package to use any of it.

I recommend using date-fns (https://date-fns.org/) (https://github.com/date-fns/date-fns). It is light-weight and modular, so you can import only the functions that you need.

In your case:

Install it: npm install date-fns --save

In your component:

import { format } from "date-fns";

var date = new Date("2016-01-04 10:34:23");

var formattedDate = format(date, "MMMM do, yyyy H:mma");

console.log(formattedDate);

Substitute the format string above "MMMM do, yyyy H:mma" with whatever format you require.

Update: v1 vs v2 format differences

v1 used Y for year and D for day, while v2 uses y and d. Format strings above have been updated for v2; the equivalent for v1 would be "MMMM Do, YYYY H:mma" (source: https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg/). Thanks @Red

How to define a relative path in java

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The answer by Leos Literak is correct but now outdated, using one of the troublesome old date-time classes, java.sql.Timestamp.

tl;dr

it is really a DATETIME in the DB

Nope, it is not. No such data type as DATETIME in Oracle database.

I was looking for a getDateTime method.

Use java.time classes in JDBC 4.2 and later rather than troublesome legacy classes seen in your Question. In particular, rather than java.sql.TIMESTAMP, use Instant class for a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE.

Contrived code snippet:

if( 
    JDBCType.valueOf( 
        myResultSetMetaData.getColumnType( … )
    )
    .equals( JDBCType.TIMESTAMP_WITH_TIMEZONE ) 
) {
    Instant instant = myResultSet.getObject( … , Instant.class ) ;
}

Oddly enough, the JDBC 4.2 specification does not require support for the two most commonly used java.time classes, Instant and ZonedDateTime. So if your JDBC does not support the code seen above, use OffsetDateTime instead.

OffsetDateTime offsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;

Details

I would like to get the DATETIME column from an Oracle DB Table with JDBC.

According to this doc, there is no column data type DATETIME in the Oracle database. That terminology seems to be Oracle’s word to refer to all their date-time types as a group.

I do not see the point of your code that detects the type and branches on which data-type. Generally, I think you should be crafting your code explicitly in the context of your particular table and particular business problem. Perhaps this would be useful in some kind of generic framework. If you insist, read on to learn about various types, and to learn about the extremely useful new java.time classes built into Java 8 and later that supplant the classes used in your Question.

Smart objects, not dumb strings

valueToInsert = aDate.toString();

You appear to trying to exchange date-time values with your database as text, as String objects. Don’t.

To exchange date-time values with your database, use date-time objects. Now in Java 8 and later, that means java.time objects, as discussed below.

Various type systems

You may be confusing three sets of date-time related data types:

  • Standard SQL types
  • Proprietary types
  • JDBC types

SQL standard types

The SQL standard defines five types:

  • DATE
  • TIME WITHOUT TIME ZONE
  • TIME WITH TIME ZONE
  • TIMESTAMP WITHOUT TIME ZONE
  • TIMESTAMP WITH TIME ZONE

Date-only

  • DATE
    Date only, no time, no time zone.

Time-Of-Day-only

  • TIME or TIME WITHOUT TIME ZONE
    Time only, no date. Silently ignores any time zone specified as part of input.
  • TIME WITH TIME ZONE (or TIMETZ)
    Time only, no date. Applies time zone and Daylight Saving Time rules if sufficient data is included with input. Of questionable usefulness given the other data types, as discussed in Postgres doc.

Date And Time-Of-Day

  • TIMESTAMP or TIMESTAMP WITHOUT TIME ZONE
    Date and time, but ignores time zone. Any time zone information passed to the database is ignores with no adjustment to UTC. So this does not represent a specific moment on the timeline, but rather a range of possible moments over about 26-27 hours. Use this if the time zone or offset are (a) unknown or (b) irrelevant such as "All our factories around the world close at noon for lunch". If you have any doubts, not likely the right type.
  • TIMESTAMP WITH TIME ZONE (or TIMESTAMPTZ)
    Date and time with respect for time zone. Note that this name is something of a misnomer depending on the implementation. Some systems may store the given time zone info. In other systems such as Postgres the time zone information is not stored, instead the time zone information passed to the database is used to adjust the date-time to UTC.

Proprietary

Many database offer their own date-time related types. The proprietary types vary widely. Some are old, legacy types that should be avoided. Some are believed by the vendor to offer certain benefits; you decide whether to stick with the standard types only or not. Beware: Some proprietary types have a name conflicting with a standard type; I’m looking at you Oracle DATE.

JDBC

The Java platform's handles the internal details of date-time differently than does the SQL standard or specific databases. The job of a JDBC driver is to mediate between these differences, to act as a bridge, translating the types and their actual implemented data values as needed. The java.sql.* package is that bridge.

JDBC legacy classes

Prior to Java 8, the JDBC spec defined 3 types for date-time work. The first two are hacks as before Version 8, Java lacked any classes to represent a date-only or time-only value.

  • java.sql.Date
    Simulates a date-only, pretends to have no time, no time zone. Can be confusing as this class is a wrapper around java.util.Date which tracks both date and time. Internally, the time portion is set to zero (midnight UTC).
  • java.sql.Time
    Time only, pretends to have no date, and no time zone. Can also be confusing as this class too is a thin wrapper around java.util.Date which tracks both date and time. Internally, the date is set to zero (January 1, 1970).
  • java.sql.TimeStamp
    Date and time, but no time zone. This too is a thin wrapper around java.util.Date.

So that answers your question regarding no "getDateTime" method in the ResultSet interface. That interface offers getter methods for the three bridging data types defined in JDBC:

Note that the first lack any concept of time zone or offset-from-UTC. The last one, java.sql.Timestamp is always in UTC despite what its toString method tells you.

JDBC modern classes

You should avoid those poorly-designed JDBC classes listed above. They are supplanted by the java.time types.

  • Instead of java.sql.Date, use LocalDate. Suits SQL-standard DATE type.
  • Instead of java.sql.Time, use LocalTime. Suits SQL-standard TIME WITHOUT TIME ZONE type.
  • Instead of java.sql.Timestamp, use Instant. Suits SQL-standard TIMESTAMP WITH TIME ZONE type.

As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. Use setObject/getObject methods.

Insert/update.

myPreparedStatement.setObject( … , instant ) ;

Retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Adjusting time zone

If you want to see the moment of an Instant as viewed through the wall-clock time used by the people of a particular region (a time zone) rather than as UTC, adjust by applying a ZoneId to get a ZonedDateTime object.

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;

The resulting ZonedDateTime object is the same moment, the same simultaneous point on the timeline. A new day dawns earlier to the east, so the date and time-of-day will differ. For example, a few minutes after midnight in New Zealand is still “yesterday” in UTC.

You can apply yet another time zone to either the Instant or ZonedDateTime to see the same simultaneous moment through yet another wall-clock time used by people in some other region.

ZoneId zMontréal = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = zdtAuckland.withZoneSameInstant( zMontréal ) ;  // Or, for the same effect: instant.atZone( zMontréal ) 

So now we have three objects (instant, zdtAuckland, zMontréal) all representing the same moment, same point on the timeline.

Detecting type

To get back to the code in Question about detecting the data-type of the databases: (a) not my field of expertise, (b) I would avoid this as mentioned up top, and (c) if you insist on this, beware that as of Java 8 and later, the java.sql.Types class is outmoded. That class is now replaced by a proper Java Enum of JDBCType that implements the new interface SQLType. See this Answer to a related Question.

This change is listed in JDBC Maintenance Release 4.2, sections 3 & 4. To quote:

Addition of the java.sql.JDBCType Enum

An Enum used to identify generic SQL Types, called JDBC Types. The intent is to use JDBCType in place of the constants defined in Types.java.

The enum has the same values as the old class, but now provides type-safety.

A note about syntax: In modern Java, you can use a switch on an Enum object. So no need to use cascading if-then statements as seen in your Question. The one catch is that the enum object’s name must be used unqualified when switching for some obscure technical reason, so you must do your switch on TIMESTAMP_WITH_TIMEZONE rather than the qualified JDBCType.TIMESTAMP_WITH_TIMEZONE. Use a static import statement.

So, all that is to say that I guess (I’ve not tried yet) you can do something like the following code example.

final int columnType = myResultSetMetaData.getColumnType( … ) ;
final JDBCType jdbcType = JDBCType.valueOf( columnType ) ;

switch( jdbcType ) {  

    case DATE :  // FYI: Qualified type name `JDBCType.DATE` not allowed in a switch, because of an obscure technical issue. Use a `static import` statement.
        …
        break ;

    case TIMESTAMP_WITH_TIMEZONE :
        …
        break ;

    default :
        … 
        break ;

}

enter image description here


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. This section left intact as history.

Joda-Time

Prior to Java 8 (java.time.* package), the date-time classes bundled with java (java.util.Date & Calendar, java.text.SimpleDateFormat) are notoriously troublesome, confusing, and flawed.

A better practice is to take what your JDBC driver gives you and from that create Joda-Time objects, or in Java 8, java.time.* package. Eventually, you should see new JDBC drivers that automatically use the new java.time.* classes. Until then some methods have been added to classes such as java.sql.Timestamp to interject with java.time such as toInstant and fromInstant.

String

As for the latter part of the question, rendering a String… A formatter object should be used to generate a string value.

The old-fashioned way is with java.text.SimpleDateFormat. Not recommended.

Joda-Time provide various built-in formatters, and you may also define your own. But for writing logs or reports as you mentioned, the best choice may be ISO 8601 format. That format happens to be the default used by Joda-Time and java.time.

Example Code

//java.sql.Timestamp timestamp = resultSet.getTimestamp(i);
// Or, fake it 
// long m = DateTime.now().getMillis();
// java.sql.Timestamp timestamp = new java.sql.Timestamp( m );

//DateTime dateTimeUtc = new DateTime( timestamp.getTime(), DateTimeZone.UTC );
DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC ); // Defaults to now, this moment.

// Convert as needed for presentation to user in local time zone.
DateTimeZone timeZone = DateTimeZone.forID("Europe/Paris");
DateTime dateTimeZoned = dateTimeUtc.toDateTime( timeZone );

Dump to console…

System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeZoned: " + dateTimeZoned );

When run…

dateTimeUtc: 2014-01-16T22:48:46.840Z
dateTimeZoned: 2014-01-16T23:48:46.840+01:00

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:

Add-PSSnapin Microsoft.Sharepoint.Powershell

in the Powershell console.

How to pass command line argument to gnuplot?

Yet another way is this:

You have a gnuplot script named scriptname.gp:

#!/usr/bin/gnuplot -p
# This code is in the file 'scriptname.gp'
EPATH = $0
FILENAME = $1 

plot FILENAME

Now you can call the gnuplot script scriptname.gp by this convoluted peace of syntax:

echo "call \"scriptname.gp\" \"'.'\" \"'data.dat'\"" | gnuplot 

Laravel 5.1 - Checking a Database Connection

Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

// Test database connection
try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

What is the C++ function to raise a number to a power?

It's pow or powf in <math.h>

There is no special infix operator like in Visual Basic or Python

How to read attribute value from XmlNode in C#?

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

Best radio-button implementation for IOS

Try DLRadioButton, works for both Swift and ObjC. You can also use images to indicate selection status or customize your own style.

Check it out at GitHub.

radio button for iOS

**Update: added the option for putting selection indicator on the right side.

**Update: added square button, IBDesignable, improved performance.

**Update: added multiple selection support.

How do I get the current date and current time only respectively in Django?

 import datetime

Current Date and time

     print(datetime.datetime.now())
     #2019-09-08 09:12:12.473393

Current date only

     print(datetime.date.today())
     #2019-09-08

Current year only

     print(datetime.date.today().year)
     #2019

Current month only

     print(datetime.date.today().month)
     #9

Current day only

     print(datetime.date.today().day)
     #8

Deserialize JSON to ArrayList<POJO> using Jackson

Another way is to use an array as a type, e.g.:

ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyPojo> pojoList = Arrays.asList(pojos);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

How to remove "href" with Jquery?

Your title question and your example are completely different. I'll start by answering the title question:

$("a").removeAttr("href");

And as far as not requiring an href, the generally accepted way of doing this is:

<a href"#" onclick="doWork(); return false;">link</a>

The return false is necessary so that the href doesn't actually go anywhere.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

Getting multiple selected checkbox values in a string in javascript and PHP

This is a variation to get all checked checkboxes in all_location_id without using an "if" statement

var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');

var aIds = [];

for(var x = 0, l = all_location_id.length; x < l;  x++)
{
    aIds.push(all_location_id[x].value);
}

var str = aIds.join(', ');

console.log(str);

How to explicitly obtain post data in Spring MVC?

You can simply just pass the attribute you want without any annotations in your controller:

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

Works with GET and POST

Detect application heap size in Android

Here's how you do it:

Getting the max heap size that the app can use:

Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory();

Getting how much of the heap your app currently uses:

long usedMemory=runtime.totalMemory() - runtime.freeMemory();

Getting how much of the heap your app can now use (available memory) :

long availableMemory=maxMemory-usedMemory;

And, to format each of them nicely, you can use:

String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize); 

Custom method names in ASP.NET Web API

Just modify your WebAPIConfig.cs as bellow

Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{action}/{id}",
  defaults: new { action = "get", id = RouteParameter.Optional });

Then implement your API as bellow

    // GET: api/Controller_Name/Show/1
    [ActionName("Show")]
    [HttpGet]
    public EventPlanner Id(int id){}

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

I faced the same issue and as majority of the answers indicated, you have to apply position: sticky; and top: 0; ( mostly but can vary if there is a navbar which is fixed as well) to 'th' element. These properties do not apply to thead or tr.

One more thing, if it still doesn't work, you have to look for 'overflow' properties of the parent. If any parent component has an overflow set, i.e. overflow: hidden, then position: sticky just doesn't work. Make sure to remove all such parent properties. Chao!

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

jQuery Ajax requests are getting cancelled without being sent

In my case, it was the missing trailing slash in the url. Adding the trailing slash solved my problem.

add onclick function to a submit button

I have this code:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() {     _x000D_
    document.getElementById("boton").style.display = 'none';_x000D_
    document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando...";     _x000D_
    return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio"  /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
   <input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Adding double quote delimiters into csv file

open powershell and run below command:

import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv  -NoTypeInformation -Encoding UTF8

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Use jQuery to change an HTML tag?

This the quick way to change HTML tags inside your DOM using jQuery. I find this replaceWith() function is very useful.

   var text= $('p').text();
   $('#change').on('click', function() {
     target.replaceWith( "<h5>"+text+"</h5>" );
   });

How to install Python MySQLdb module using pip?

I had problems installing the 64-bit version of MySQLdb on Windows via Pip (problem compiling sources) [32bit version installed ok]. Managed to install the compiled MySQLdb from the .whl file available from http://www.lfd.uci.edu/~gohlke/pythonlibs/

The .whl file can then be installed via pip as document in https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels

For example if you save in C:/ the you can install via

pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl

Follow-up: if you have a 64bit version of Python installed, then you want to install the 64-bit AMD version of MySQLdb from the link above [i.e. even if you have a Intel processor]. If you instead try and install the 32-bit version, I think you get the unsupported wheel error in comments below.

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Why should I use a container div in HTML?

THis method allows you to have more flexibility of styling your entire content. Effectivly creating two containers that you can style. THe HTML Body tag which serves as your background, and the div with an id of container which contains your content.

This then allows you to position your content within the page, while styling a background or other effects without issue. THink of it as a "Frame" for the content.

ASP.net using a form to insert data into an sql server table

There are tons of sample code online as to how to do this.

Here is just one example of how to do this: http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

you define the text boxes between the following tag:

<form id="form1" runat="server"> 

you create your textboxes and define them to runat="server" like so:

<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>

define a button to process your logic like so (notice the onclick):

<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />

in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named

protected void Button1_Click(object sender, EventArgs e)

or you could just double click the button in the design view.

Here is a very quick sample of code to insert into a table in the button click event (codebehind)

protected void Button1_Click(object sender, EventArgs e)
{
   string name = TxtName.Text; // Scrub user data

   string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
   SqlConnection conn = null;
   try
   {
          conn = new SqlConnection(connString);
          conn.Open();

          using(SqlCommand cmd = new SqlCommand())
          {
                 cmd.Conn = conn;
                 cmd.CommandType = CommandType.Text;
                 cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
                 cmd.Parameters.AddWithValue("@var", name);
                 int rowsAffected = cmd.ExecuteNonQuery();
                 if(rowsAffected ==1)
                 {
                        //Success notification
                 }
                 else
                 {
                        //Error notification
                 }
          }
   }
   catch(Exception ex)
   {
          //log error 
          //display friendly error to user
   }
   finally
   {
          if(conn!=null)
          {
                 //cleanup connection i.e close 
          }
   }
}

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

docker entrypoint running bash script gets "permission denied"

Dot [.]

This problem take with me more than 3 hours finally , I just tried the problem was in removing dot from the end just .

problem was

docker run  -p 3000:80 --rm --name test-con test-app .

/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied

just remove dot from the end of your command line :

docker run  -p 3000:80 --rm --name test-con test-app 

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

Maintaining href "open in new tab" with an onClick handler in React

Above answers are correct. But simply this worked for me

target={"_blank"}

Printing one character at a time from a string, using the while loop

Other answers have already given you the code you need to iterate though a string using a while loop (or a for loop) but I thought it might be useful to explain the difference between the two types of loops.

while loops repeat some code until a certain condition is met. For example:

import random

sum = 0
while sum < 100:
    sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
    print sum

This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.

for loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for loops usually use some sort of a counter variable (below I use i), and generally makes the similarity between while and for loops much more explicit.

for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
    System.out.println(i);
}

This loop will run exactly 10 times. This is just a nicer way to write this:

int i = 0;
while (i < 10) { //until i is 10
   System.out.println(i);
   i++; //add one to i 
}

The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:

for item in myList:
    print item

or

for character in myString:
    print character

However, you didn't want to use a for loop. In that case, you'll need to look at each character using its index. Like this:

print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.

Knowing that you can make a for loop using only a while loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while loop.

HOWEVER in general you'd use a for loop in this situation because it's easier to read.

Difference between multitasking, multithreading and multiprocessing?

In a multiprogramming system, there are more than one programs loaded in main memory which are ready to execute. Only one program at a time is able to get the CPU for executing its instructions while all others are waiting their turn. The main idea of multiprogramming is to maximize the use of CPU time. Suppose currently running process is performing an I/O task, then OS may interrupt that process and give the control to one of the other in - main memory programs that are ready to execute (i.e. process context switching). In this way, no CPU time is wasted by system waiting for the I/O task to be completed.

MultiProcessing - Multiprocessing is the ability of an operating system to execute more than one process simultaneously on a multi processor machine. In multiprocessing system, a computer uses more than one CPU at a tme.

Multitasking - Multitasking is the ability of an operating system to execute more than one task simultaneously on single processor machine, these multiple tasks share common resources such as CPU and memory. In multitasking system, CPU switches from one task to next task so quickly that appears as all tasks are executing at the same time.

There are differences between multitasking and multi programming. A task in a multitasking system is not whole application program but it can refers to a "thread of execution" when one process is divided into sub-tasks. Each smaller task does not hijack the CPU until it finishes, they share a small amount of the CPU time called Quantum. Multi programming and multitasking operating systems are time sharing systems.

Multi threading - Multi threading is the extension of multitasking. Multi threading is the ability of an operating system to subdivide the specific operation within a single application into individual threads. Each of these threads can run in parallel. The OS divides processing time not only among different applications but also among each thread within an application.

Remove "Using default security password" on Spring Boot

Adding following in application.properties worked for me,

security.basic.enabled=false

Remember to restart the application and check in the console.

How to control the line spacing in UILabel

As a quick-dirty-smart-simple workaround:

For UILabels that don't have much lines you can instead use stackViews.

  1. For each line write a new label.
  2. Embed them into a StackView.(select both labels-->Editor-->Embed In -->StackView
  3. Adjust the Spacing of the StackView to your desired amount

Be sure to stack them vertically. This solution also works for custom fonts.

enter image description here

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

"No such file or directory" error when executing a binary

Well another possible cause of this can be simple line break at end of each line and shebang line If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

Encoding conversion in java

You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

Align text in JLabel to the right

JLabel label = new JLabel("fax", SwingConstants.RIGHT);

IIS: Idle Timeout vs Recycle

I have inherited a desktop app that makes calls to a series of Web Services on IIS. The web services (also) have to be able to run timed processes, independently (without having the client on). Hence they all have timers. The web service timers were shutting down (memory leak?) so we set the Idle time out to 0 and timers stay on.

How to count lines of Java code using IntelliJ IDEA?

In the past I have used the excellently named MetricsReloaded plugin to get this information.

You can install it from the JetBrains repository.

Once installed, access via: Analyze -> Calculate Metrics...

How to capitalize the first character of each word in a string

Use:

    String text = "jon skeet, miles o'brien, old mcdonald";

    Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
    Matcher matcher = pattern.matcher(text);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
    }
    String capitalized = matcher.appendTail(buffer).toString();
    System.out.println(capitalized);

How can we stop a running java process through Windows cmd?

In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.

wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate

Else taskkill /im java.exe will work to kill all java processes

Difference between spring @Controller and @RestController annotation

  • @Controller: This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
  • @RestController: This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically so we do not have to add @ResponseBody to our mapping methods.

Rails - Could not find a JavaScript runtime?

sudo apt-get install nodejs does not work for me. In order to get it to work, I have to do the following:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

Hope this will help someone having the same problem as me.

How to capitalize the first letter of word in a string using Java?

String sentence = "ToDAY   WeAthEr   GREat";    
public static String upperCaseWords(String sentence) {
        String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
        String newSentence = "";
        for (String word : words) {
            for (int i = 0; i < word.length(); i++)
                newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase(): 
                    (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
        }

        return newSentence;
    }
//Today Weather Great

jQuery selector for inputs with square brackets in the name attribute

If the selector is contained within a variable, the code below may be helpful:

selector_name = $this.attr('name');
//selector_name = users[0][first:name]

escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]

In this case we prefix all special characters with double backslash.

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

Have a look at iconv() or mb_convert_encoding(). Just by the way: why don't utf8_encode() and utf8_decode() work for you?

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

So essentially

$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');

$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');

all should do the same - with utf8_en/decode() requiring no special extension, mb_convert_encoding() requiring ext/mbstring and iconv() requiring ext/iconv.

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

Pandas Split Dataframe into two Dataframes at a specific row

use np.split(..., axis=1):

Demo:

In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))

In [256]: df
Out[256]:
          a         b         c         d         e         f
0  0.823638  0.767999  0.460358  0.034578  0.592420  0.776803
1  0.344320  0.754412  0.274944  0.545039  0.031752  0.784564
2  0.238826  0.610893  0.861127  0.189441  0.294646  0.557034
3  0.478562  0.571750  0.116209  0.534039  0.869545  0.855520
4  0.130601  0.678583  0.157052  0.899672  0.093976  0.268974

In [257]: dfs = np.split(df, [4], axis=1)

In [258]: dfs[0]
Out[258]:
          a         b         c         d
0  0.823638  0.767999  0.460358  0.034578
1  0.344320  0.754412  0.274944  0.545039
2  0.238826  0.610893  0.861127  0.189441
3  0.478562  0.571750  0.116209  0.534039
4  0.130601  0.678583  0.157052  0.899672

In [259]: dfs[1]
Out[259]:
          e         f
0  0.592420  0.776803
1  0.031752  0.784564
2  0.294646  0.557034
3  0.869545  0.855520
4  0.093976  0.268974

np.split() is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]:

In [260]: dfs = np.split(df, [2,3], axis=1)

In [261]: dfs[0]
Out[261]:
          a         b
0  0.823638  0.767999
1  0.344320  0.754412
2  0.238826  0.610893
3  0.478562  0.571750
4  0.130601  0.678583

In [262]: dfs[1]
Out[262]:
          c
0  0.460358
1  0.274944
2  0.861127
3  0.116209
4  0.157052

In [263]: dfs[2]
Out[263]:
          d         e         f
0  0.034578  0.592420  0.776803
1  0.545039  0.031752  0.784564
2  0.189441  0.294646  0.557034
3  0.534039  0.869545  0.855520
4  0.899672  0.093976  0.268974

What is the best open-source java charting library? (other than jfreechart)

There is charts4j which is a charts and graphs API. It enables developers to programmatically create the charts available in the Google Chart API through a straightforward and intuitive Java API.

Disclaimer: I wrote charts4j. We will be doing another major release in the next few weeks.

Can I apply multiple background colors with CSS3?

You can only use one color but as many images as you want, here is the format:

background: [ <bg-layer> , ]* <final-bg-layer>

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}

<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>

or background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;

If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.

The format is from http://www.css3.info/preview/multiple-backgrounds/

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

For people who are looking to insert a row between two rows in an existing excel with XSSF (Apache POI), there is already a method "copyRows" implemented in the XSSFSheet.

import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class App2 throws Exception{
    public static void main(String[] args){
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("input.xlsx"));
        XSSFSheet sheet = workbook.getSheet("Sheet1");
        sheet.copyRows(0, 2, 3, new CellCopyPolicy());
        FileOutputStream out = new FileOutputStream("output.xlsx");
        workbook.write(out);
        out.close();
    }
}

C# How to change font of a label

You can't change a Font once it's created - so you need to create a new one:

  mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

Check existence of input argument in a Bash shell script

It is:

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi

The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi

The -z switch will test if the expansion of "$1" is a null string or not. If it is a null string then the body is executed.

How can I give eclipse more memory than 512M?

I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).

Open eclipse.ini in the Eclipse installation directory. You should be able to change the memory sizes after -vmargs up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:

-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m

And here's that section on my Windows box:

-vmargs
-Xms256m
-Xmx1024m

But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.

EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.

EDIT: Nick's post contains some great links that explain two different things:

  • The problem is largely dependent on your system and the amount of contiguous free memory available, and
  • By using javaw.exe (on Windows), you may be able to get a larger allocated block of memory.

I have 8 gigs of Ram and can't set -Xmx to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Do checkbox inputs only post data if they're checked?

Having the same problem with unchecked checkboxes that will not be send on forms submit, I came out with a another solution than mirror the checkbox items.

Getting all unchecked checkboxes with

var checkboxQueryString;

$form.find ("input[type=\"checkbox\"]:not( \":checked\")" ).each(function( i, e ) {
  checkboxQueryString += "&" + $( e ).attr( "name" ) + "=N"
});

Hide Twitter Bootstrap nav collapse on click

Bootstrap3 users try the given below code. It worked for me.

function close_toggle() {
   if ($(window).width() <= 768) {
      $('.nav a').on('click', function(){
          $(".navbar-toggle").click();
      });
   }
   else {
     $('.nav a').off('click');
   }
}
close_toggle();

$(window).resize(close_toggle);

adb command not found

you have to move the adb command to /bin/ folder

in my case:

sudo su
mv /root/Android/Sdk/platform-tools/adb /bin/

Convert .cer certificate to .jks

Export a certificate from a keystore:

keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks

Add onclick event to newly added element in JavaScript

I don't think you can do that this way. You should use :

void addEventListener( 
  in DOMString type, 
  in EventListener listener, 
  in boolean useCapture 
); 

Documentation right here.

MINGW64 "make build" error: "bash: make: command not found"

You can also use Chocolatey.

Having it installed, just run:

choco install make

When it finishes, it is installed and available in Git for Bash / MinGW.

Convert an image (selected by path) to base64 string

Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:

byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);

To convert a base64 image back to a System.Drawing.Image:

var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Which browser has the best support for HTML 5 currently?

http://wiki.whatwg.org/wiki/Implementations_in_Web_browsers has information maintained by the WHATWG community (and everyone who drops by and edits it).

Disclaimer: I'm a member of that community.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I am late, hope it will help someone ....This is a known issue with IIS 8.0

The solution is to delete the 3.x module and handler from IIS manager. You could delete them at the application or site level if you want to keep them in applicationHost.config. But I wanted to delete them from applicationHost.config. do the following steps:

In IIS manager, click the machine name node. In “Features View”, double-click “Modules”. Find “ServiceModel” and remove it. Image 1 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Go back to the machine name node’s “Features View”, double-click “Handler Mappings”. Find “svc-Integrated” and remove it. Image 2 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Reading my own Jar's Manifest

The easiest way is to use JarURLConnection class :

String className = getClass().getSimpleName() + ".class";
String classPath = getClass().getResource(className).toString();
if (!classPath.startsWith("jar")) {
    return DEFAULT_PROPERTY_VALUE;
}

URL url = new URL(classPath);
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue(PROPERTY_NAME);

Because in some cases ...class.getProtectionDomain().getCodeSource().getLocation(); gives path with vfs:/, so this should be handled additionally.

Get original URL referer with PHP?

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

session_start();

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

How to indent HTML tags in Notepad++

Use the XML Tools plugin for Notepad++ and then you can Auto-Indent the code with Ctrl+Alt+Shift+B .For the more point-and-click inclined, you could also go to Plugins --> XML Tools --> Pretty Print.

Concat all strings inside a List<string> using LINQ

Put String.Join into an extension method. Here is the version I use, which is less verbose than Jordaos version.

  • returns empty string "" when list is empty. Aggregate would throw exception instead.
  • probably better performance than Aggregate
  • is easier to read when combined with other LINQ methods than a pure String.Join()

Usage

var myStrings = new List<string>() { "a", "b", "c" };
var joinedStrings = myStrings.Join(",");  // "a,b,c"

Extensionmethods class

public static class ExtensionMethods
{
    public static string Join(this IEnumerable<string> texts, string separator)
    {
        return String.Join(separator, texts);
    }
}

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

How to set up default schema name in JPA configuration?

For those who uses last versions of spring boot will help this:

.properties:

spring.jpa.properties.hibernate.default_schema=<name of your schema>

.yml:

spring:
    jpa:
        properties:
            hibernate:
                default_schema: <name of your schema>

HTML5 tag for horizontal line break

Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.

Here is a sample code:

The HTML:

<div class="title_block">
    <h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>

The CSS:

.title_block {
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
    margin-bottom: 5px;
}

Cannot construct instance of - Jackson

For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.

public class TeamCode {

    @Expose
    private String value;

    public String getValue() {
        return value;
    }

    **public TeamCode() {
    }**

    public TeamCode(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "TeamCode{" +
                "value='" + value + '\'' +
                '}';
    }

    public void setValue(String value) {
        this.value = value;
    }

}

Tool to Unminify / Decompress JavaScript

If you have a Mac and TextMate - An easy alternative for formatting Javascript is:

  1. Open the file with Textmate.
  2. Click on > Bundles > JavaScript > Reformat Document
  3. Crack open a beer.

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

How add unique key to existing table (with non uniques rows)

For MySQL:

ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;

Get escaped URL parameter

function getURLParameters(paramName) 
{
        var sURL = window.document.URL.toString();  
    if (sURL.indexOf("?") > 0)
    {
       var arrParams = sURL.split("?");         
       var arrURLParams = arrParams[1].split("&");      
       var arrParamNames = new Array(arrURLParams.length);
       var arrParamValues = new Array(arrURLParams.length);     
       var i = 0;
       for (i=0;i<arrURLParams.length;i++)
       {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
       }

       for (i=0;i<arrURLParams.length;i++)
       {
                if(arrParamNames[i] == paramName){
            //alert("Param:"+arrParamValues[i]);
                return arrParamValues[i];
             }
       }
       return "No Parameters Found";
    }

}

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

How to auto adjust the <div> height according to content in it?

<div> should expand automatically. I guess that the problem is that you're using fixed height:100px;, try replacing it with min-height:100px;

Add new line in text file with Windows batch file

I believe you are using the

echo Text >> Example.txt 

function?

If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.

Example:

echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Delete all rows in a table based on another table

To Delete table records based on another table

     Delete From Table1 a,Table2 b where a.id=b.id

    Or

      DELETE FROM Table1
    WHERE Table1.id IN (SELECT Table2.id FROM Table2)

  Or

        DELETE Table1
     FROM Table1 t1 INNER JOIN Table2 t2 ON t1.ID = t2.ID;

How do I check/uncheck all checkboxes with a button using jQuery?

Check All with uncheck/check controller if all items is/isnt checked

JS:

e = checkbox id t= checkbox (item) class n= checkbox check all class

function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}

HTML:

Check ALL controle class : chkall_ctrl

<input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
<br/>
1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
<br/>
<input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>

<script>
jQuery(document).ready(function($)
{
  checkAll('chkall_up','chkall','chkall_ctrl');
  checkAll('chkall_down','chkall','chkall_ctrl');
});
 </script>

How do you migrate an IIS 7 site to another server?

I'd say export your server config in IIS manager:

  1. In IIS manager, click the Server node
  2. Go to Shared Configuration under "Management"
  3. Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
  4. Move these files to your new server

    administration.config
    applicationHost.config
    configEncKey.key 
    
  5. On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.

  6. It should prompt for the encryption password(if you set it) and reset IIS.

BAM! Go have a beer!

proper name for python * operator?

I call *args "star args" or "varargs" and **kwargs "keyword args".

Display text on MouseOver for image in html

You can do like this also:

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>

In javascript:

function somefunction()
{
  //Do somethisg.
}

?

Mockito - difference between doReturn() and when()

The latter alternative is used for methods on mocks that return void.

Please have a look, for example, here: How to make mock to void methods with mockito

How to efficiently remove duplicates from an array without using Set

You need to sort your array then then loop and remove duplicates. As you cannot use other tools you need to write be code yourself.

You can easily find examples of quicksort in Java on the internet (on which this example is based).

public static void main(String[] args) throws Exception {
    final int[] original = new int[]{1, 1, 2, 8, 9, 8, 4, 7, 4, 9, 1};
    System.out.println(Arrays.toString(original));
    quicksort(original);
    System.out.println(Arrays.toString(original));
    final int[] unqiue = new int[original.length];
    int prev = original[0];
    unqiue[0] = prev;
    int count = 1;
    for (int i = 1; i < original.length; ++i) {
        if (original[i] != prev) {
            unqiue[count++] = original[i];
        }
        prev = original[i];
    }
    System.out.println(Arrays.toString(unqiue));
    final int[] compressed = new int[count];
    System.arraycopy(unqiue, 0, compressed, 0, count);
    System.out.println(Arrays.toString(compressed));
}

private static void quicksort(final int[] values) {
    if (values.length == 0) {
        return;
    }
    quicksort(values, 0, values.length - 1);
}

private static void quicksort(final int[] values, final int low, final int high) {
    int i = low, j = high;
    int pivot = values[low + (high - low) / 2];
    while (i <= j) {
        while (values[i] < pivot) {
            i++;
        }
        while (values[j] > pivot) {
            j--;
        }
        if (i <= j) {
            swap(values, i, j);
            i++;
            j--;
        }
    }
    if (low < j) {
        quicksort(values, low, j);
    }
    if (i < high) {
        quicksort(values, i, high);
    }
}

private static void swap(final int[] values, final int i, final int j) {
    final int temp = values[i];
    values[i] = values[j];
    values[j] = temp;
}

So the process runs in 3 steps.

  1. Sort the array - O(nlgn)
  2. Remove duplicates - O(n)
  3. Compact the array - O(n)

So this improves significantly on your O(n^3) approach.

Output:

[1, 1, 2, 8, 9, 8, 4, 7, 4, 9, 1]
[1, 1, 1, 2, 4, 4, 7, 8, 8, 9, 9]
[1, 2, 4, 7, 8, 9, 0, 0, 0, 0, 0]
[1, 2, 4, 7, 8, 9]

EDIT

OP states values inside array doesn't matter really. But I can assume that range is between 0-1000. This is a classic case where an O(n) sort can be used.

We create an array of size range +1, in this case 1001. We then loop over the data and increment the values on each index corresponding to the datapoint.

We can then compact the resulting array, dropping values the have not been incremented. This makes the values unique as we ignore the count.

public static void main(String[] args) throws Exception {
    final int[] original = new int[]{1, 1, 2, 8, 9, 8, 4, 7, 4, 9, 1, 1000, 1000};
    System.out.println(Arrays.toString(original));
    final int[] buckets = new int[1001];
    for (final int i : original) {
        buckets[i]++;
    }
    final int[] unique = new int[original.length];
    int count = 0;
    for (int i = 0; i < buckets.length; ++i) {
        if (buckets[i] > 0) {
            unique[count++] = i;
        }
    }
    final int[] compressed = new int[count];
    System.arraycopy(unique, 0, compressed, 0, count);
    System.out.println(Arrays.toString(compressed));
}

Output:

[1, 1, 2, 8, 9, 8, 4, 7, 4, 9, 1, 1000, 1000]
[1, 2, 4, 7, 8, 9, 1000]

ES6 exporting/importing in index file

Too late but I want to share the way that I resolve it.

Having model file which has two named export:

export { Schema, Model };

and having controller file which has the default export:

export default Controller;

I exposed in the index file in this way:

import { Schema, Model } from './model';
import Controller from './controller';

export { Schema, Model, Controller };

and assuming that I want import all of them:

import { Schema, Model, Controller } from '../../path/';

Difference between text and varchar (character varying)

There is no difference, under the hood it's all varlena (variable length array).

Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/

A couple of highlights:

To sum it all up:

  • char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit
  • varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
  • varchar – just like text
  • text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

How to sort a List<Object> alphabetically using Object name field

I found another way to do the type.

if(listAxu.size() > 0){
    Collections.sort(listAxu, Comparator.comparing(IdentityNamed::getDescricao));
}

How to dynamically set bootstrap-datepicker's date value?

This works for me,

$('#datepicker').datepicker("setValue", '01/10/2014' );
$('#datepicker').datepicker("setValue", new Date(2008,9,03));

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__)) or #pragma pack(1), what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.

Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align option, it isn't enabled by default nor with -Wall or -Wextra. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.

Consider the following:

struct  __attribute__((__packed__)) my_struct {
    char c;
    int i;
};

struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;

Here, the type of a is a packed struct (as defined above). Similarly, b is a pointer to a packed struct. The type of of the expression a.i is (basically) an int l-value with 1 byte alignment. c and d are both normal ints. When reading a.i, the compiler generates code for unaligned access. When you read b->i, b's type still knows it's packed, so no problem their either. e is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall or -Wextra).

How can I make my match non greedy in vim?

Plugin eregex.vim handles Perl-style non-greedy operators *? and +?

What is tempuri.org?

http://en.wikipedia.org/wiki/Tempuri

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For RVM & OSX users

Make sure you use latest rvm:

rvm get stable

Then you can do two things:

  1. Update certificates:

    rvm osx-ssl-certs update all
    
  2. Update rubygems:

    rvm rubygems latest
    

For non RVM users

Find path for certificate:

cert_file=$(ruby -ropenssl -e 'puts OpenSSL::X509::DEFAULT_CERT_FILE')

Generate certificate:

security find-certificate -a -p /Library/Keychains/System.keychain > "$cert_file"
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> "$cert_file"

The whole code: https://github.com/wayneeseguin/rvm/blob/master/scripts/functions/osx-ssl-certs


For non OSX users

Make sure to update package ca-certificates. (on old systems it might not be available - do not use an old system which does not receive security updates any more)

Windows note

The Ruby Installer builds for windows are prepared by Luis Lavena and the path to certificates will be showing something like C:/Users/Luis/... check https://github.com/oneclick/rubyinstaller/issues/249 for more details and this answer https://stackoverflow.com/a/27298259/497756 for fix.

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

How to get a dependency tree for an artifact?

If your artifact is not a dependency of a given project, your best bet is to use a repository search engine. Many of them describes the dependencies of a given artifact.

How to upgrade PowerShell version from 2.0 to 3.0

  1. Install Chocolatey
  2. Run the following commands in CMD

    • choco install powershell

    • choco upgrade powershell

Call PHP function from Twig template

There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.

And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.

pandas three-way joining multiple dataframes on columns

There is another solution from the pandas documentation (that I don't see here),

using the .append

>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
   A  B
0  1  2
1  3  4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
   A  B
0  5  6
1  7  8
>>> df.append(df2, ignore_index=True)
   A  B
0  1  2
1  3  4
2  5  6
3  7  8

The ignore_index=True is used to ignore the index of the appended dataframe, replacing it with the next index available in the source one.

If there are different column names, Nan will be introduced.

How to simulate browsing from various locations?

Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...

I usually use online DNS lookup tools for that, e.g. http://network-tools.com/

It can check your HTTP header as well. Only a proxy located in Europe would be better.

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

Can I create links with 'target="_blank"' in Markdown?

For ghost markdown use:

[Google](https://google.com" target="_blank)

Found it here: https://cmatskas.com/open-external-links-in-a-new-window-ghost/

PHP array printing using a loop

Another advanced method is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects.

$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];

$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();

while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}

How to get the azure account tenant Id?

In PowerShell:

Add-AzureRmAccount #if not already logged in 
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId

Can I serve multiple clients using just Flask app.run() as standalone?

Using the simple app.run() from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.

Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.

That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).

Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

How to compare datetime with only date in SQL Server

You can use LIKE statement instead of =. But to do this with DateStamp you need to CONVERT it first to VARCHAR:

SELECT * 
FROM [User] U
WHERE CONVERT(VARCHAR, U.DateCreated, 120) LIKE '2014-02-07%'

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is the latest correct way that I know of how to check for IE and Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/\d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Note that you don't need the extra var isIE10 in your code because it does very specific checks now.

Also check out this page for the latest IE and Edge user agent strings because this answer may become outdated at some point: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

How to change progress bar's progress color in Android

Since method public void setColorFilter(@ColorInt int color, @NonNull PorterDuff.Mode mode) is deprecated, I use such form:

progressBar.indeterminateDrawable.colorFilter =
            PorterDuffColorFilter(ContextCompat.getColor(this, R.color.black), PorterDuff.Mode.SRC_IN)

Print: Entry, ":CFBundleIdentifier", Does Not Exist

Delete the node modules and run 'npm install' in your project directory. Now you can able to run the project.

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

Chart creating dynamically. in .net, c#

Yep.

// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart).  Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;


namespace Dino.Tools.WebMonitor
{
    public class FakeChartForm1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;

        public FakeChartForm1 ()
        {
            InitializeComponent();
        }

        private double f(int i)
        {
            var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
            return f1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Series.Clear();
            var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name = "Series1",
                Color = System.Drawing.Color.Green,
                IsVisibleInLegend = false,
                IsXValueIndexed = true,
                ChartType = SeriesChartType.Line
            };

            this.chart1.Series.Add(series1);

            for (int i=0; i < 100; i++)
            {
                series1.Points.AddXY(i, f(i));
            }
            chart1.Invalidate();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            //
            // chart1
            //
            chartArea1.Name = "ChartArea1";
            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(0, 50);
            this.chart1.Name = "chart1";
            // this.chart1.Size = new System.Drawing.Size(284, 212);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.chart1);
            this.Name = "Form1";
            this.Text = "FakeChart";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FakeChartForm1());
        }
    }
}

UI:

enter image description here

filename and line number of Python script

Thanks to mcandre, the answer is:

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

How can I resolve the error: "The command [...] exited with code 1"?

For me, in VS 2013, I had to get rid of missing references under References in the UI project (MVC). Turns out, the ones missing were not referenced.

HTML5 Canvas: Zooming

Canvas zoom and pan

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<canvas id="myCanvas" width="" height=""_x000D_
style="border:1px solid #d3d3d3;">_x000D_
Your browser does not support the canvas element._x000D_
</canvas>_x000D_
_x000D_
<script>_x000D_
console.log("canvas")_x000D_
var ox=0,oy=0,px=0,py=0,scx=1,scy=1;_x000D_
var canvas = document.getElementById("myCanvas");_x000D_
canvas.onmousedown=(e)=>{px=e.x;py=e.y;canvas.onmousemove=(e)=>{ox-=(e.x-px);oy-=(e.y-py);px=e.x;py=e.y;} } _x000D_
_x000D_
canvas.onmouseup=()=>{canvas.onmousemove=null;}_x000D_
canvas.onwheel =(e)=>{let bfzx,bfzy,afzx,afzy;[bfzx,bfzy]=StoW(e.x,e.y);scx-=10*scx/e.deltaY;scy-=10*scy/e.deltaY;_x000D_
[afzx,afzy]=StoW(e.x,e.y);_x000D_
ox+=(bfzx-afzx);_x000D_
oy+=(bfzy-afzy);_x000D_
}_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
function draw(){_x000D_
window.requestAnimationFrame(draw);_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height);_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=0,sy=i;_x000D_
let ex=100,ey=i;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=i,sy=0;_x000D_
let ex=i,ey=100;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
}_x000D_
draw()_x000D_
function WtoS(wx,wy){_x000D_
let sx=(wx-ox)*scx;_x000D_
let sy=(wy-oy)*scy;_x000D_
return[sx,sy];_x000D_
}_x000D_
function StoW(sx,sy){_x000D_
let wx=sx/scx+ox;_x000D_
let wy=sy/scy+oy;_x000D_
return[wx,wy];_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

How to enter special characters like "&" in oracle database?

you can simply escape & by following a dot. try this:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');

UICollectionView Set number of columns

First add UICollectionViewDelegateFlowLayout as protocol.

Then:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
        var columnCount = 3
        let width  = (view.frame.width - 20) / columnCount
        return CGSize(width: width, height: width)
}

SignalR Console app example

Example for SignalR 2.2.1 (May 2017)

Server

Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1

[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
    class Program
    {
        static IDisposable SignalR;

        static void Main(string[] args)
        {
            string url = "http://127.0.0.1:8088";
            SignalR = WebApp.Start(url);

            Console.ReadKey();
        }

        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);

                /*  CAMEL CASE & JSON DATE FORMATTING
                 use SignalRContractResolver from
                https://stackoverflow.com/questions/30005575/signalr-use-camel-case

                var settings = new JsonSerializerSettings()
                {
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc
                };

                settings.ContractResolver = new SignalRContractResolver();
                var serializer = JsonSerializer.Create(settings);
                  
               GlobalHost.DependencyResolver.Register(typeof(JsonSerializer),  () => serializer);                
            
                 */

                app.MapSignalR();
            }
        }

        [HubName("MyHub")]
        public class MyHub : Hub
        {
            public void Send(string name, string message)
            {
                Clients.All.addMessage(name, message);
            }
        }
    }
}

Client

(almost the same as Mehrdad Bahrainy reply)

Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1

namespace ConsoleApplication116_SignalRClient
{
    class Program
    {
        private static void Main(string[] args)
        {
            var connection = new HubConnection("http://127.0.0.1:8088/");
            var myHub = connection.CreateHubProxy("MyHub");

            Console.WriteLine("Enter your name");    
            string name = Console.ReadLine();

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");

                    myHub.On<string, string>("addMessage", (s1, s2) => {
                        Console.WriteLine(s1 + ": " + s2);
                    });

                    while (true)
                    {
                        Console.WriteLine("Please Enter Message");
                        string message = Console.ReadLine();

                        if (string.IsNullOrEmpty(message))
                        {
                            break;
                        }

                        myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
                            if (task1.IsFaulted)
                            {
                                Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                            }
                            else
                            {
                                Console.WriteLine(task1.Result);
                            }
                        });
                    }
                }

            }).Wait();

            Console.Read();
            connection.Stop();
        }
    }
}

Angular directives - when and how to use compile, controller, pre-link and post-link

What else happens between these function calls?

The various directive functions are executed from within two other angular functions called $compile (where the directive's compile is executed) and an internal function called nodeLinkFn (where the directive's controller, preLink and postLink are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:

An illustration showing Angular compile and link phases

To demonstrate the these steps, let's use the following HTML markup:

<div ng-repeat="i in [0,1,2]">
    <my-element>
        <div>Inner content</div>
    </my-element>
</div>

With the following directive:

myApp.directive( 'myElement', function() {
    return {
        restrict:   'EA',
        transclude: true,
        template:   '<div>{{label}}<div ng-transclude></div></div>'
    }
});

Compile

The compile API looks like so:

compile: function compile( tElement, tAttributes ) { ... }

Often the parameters are prefixed with t to signify the elements and attributes provided are those of the source template, rather than that of the instance.

Prior to the call to compile transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile function will look like so:

<my-element>
    <div>
        "{{label}}"
        <div ng-transclude></div>
    </div>
</my-element>

Notice that the transcluded content is not re-inserted at this point.

Following the call to the directive's .compile, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).

Instance creation

In our case, three instances of the source template above will be created (by ng-repeat). Thus, the following sequence will execute three times, once per instance.

Controller

The controller API involves:

controller: function( $scope, $element, $attrs, $transclude ) { ... }

Entering the link phase, the link function returned via $compile is now provided with a scope.

First, the link function create a child scope (scope: true) or an isolated scope (scope: {...}) if requested.

The controller is then executed, provided with the scope of the instance element.

Pre-link

The pre-link API looks like so:

function preLink( scope, element, attributes, controller ) { ... }

Virtually nothing happens between the call to the directive's .controller and the .preLink function. Angular still provide recommendation as to how each should be used.

Following the .preLink call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).

Post-link

The post-link API is similar to that of the pre-link function:

function postLink( scope, element, attributes, controller ) { ... }

Perhaps worth noticing that once a directive's .postLink function is called, the link process of all its children elements has completed, including all the children's .postLink functions.

This means that by the time .postLink is called, the children are 'live' are ready. This includes:

  • data binding
  • transclusion applied
  • scope attached

The template at this stage will thus look like so:

<my-element>
    <div class="ng-binding">
        "{{label}}"
        <div ng-transclude>                
            <div class="ng-scope">Inner content</div>
        </div>
    </div>
</my-element>

How to disable and then enable onclick event on <div> with javascript

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

$("#id").attr('disabled','disabled');

Hope this helps.

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

Return date as ddmmyyyy in SQL Server

CONVERT style 103 is dd/mm/yyyy. Then use the REPLACE function to eliminate the slashes.

SELECT REPLACE(CONVERT(CHAR(10), [MyDateTime], 103), '/', '')

How do I check if a directory exists? "is_dir", "file_exists" or both?

Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

While many people here say there is no best way for object creation, there is a rationale as to why there are so many ways to create objects in JavaScript, as of 2019, and this has to do with the progress of JavaScript over the different iterations of EcmaScript releases dating back to 1997.

Prior to ECMAScript 5, there were only two ways of creating objects: the constructor function or the literal notation ( a better alternative to new Object()). With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.

// constructor function
function Person() {};

// literal notation
var Person = {};

Regardless of the method you use, JavaScript objects are simply properties of key value pairs:

// Method 1: dot notation
obj.firstName = 'Bob';

// Method 2: bracket notation. With bracket notation, you can use invalid characters for a javascript identifier.
obj['lastName'] = 'Smith';

// Method 3: Object.defineProperty
Object.defineProperty(obj, 'firstName', {
    value: 'Bob',
    writable: true,
    configurable: true,
    enumerable: false
})

// Method 4: Object.defineProperties
Object.defineProperties(obj, {
  firstName: {
    value: 'Bob',
    writable: true
  },
  lastName: {
    value: 'Smith',
    writable: false
  }
});

In early versions of JavaScript, the only real way to mimic class-based inheritance was to use constructor functions. the constructor function is a special function that is invoked with the 'new' keyword. By convention, the function identifier is capitalized, albiet it is not required. Inside of the constructor, we refer to the 'this' keyword to add properties to the object that the constructor function is implicitly creating. The constructor function implicitly returns the new object with the populated properties back to the calling function implicitly, unless you explicitly use the return keyword and return something else.

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

    this.sayName = function(){
        return "My name is " + this.firstName + " " + this.lastName;
    }
} 

var bob = new Person("Bob", "Smith");
bob instanceOf Person // true

There is a problem with the sayName method. Typically, in Object-Oriented Class-based programming languages, you use classes as factories to create objects. Each object will have its own instance variables, but it will have a pointer to the methods defined in the class blueprint. Unfortunately, when using JavaScript's constructor function, every time it is called, it will define a new sayName property on the newly created object. So each object will have its own unique sayName property. This will consume more memory resources.

In addition to increased memory resources, defining methods inside of the constructor function eliminates the possibility of inheritance. Again, the method will be defined as a property on the newly created object and no other object, so inheritance cannot work like. Hence, JavaScript provides the prototype chain as a form of inheritance, making JavaScript a prototypal language.

If you have a parent and a parent shares many properties of a child, then the child should inherit those properties. Prior to ES5, it was accomplished as follows:

function Parent(eyeColor, hairColor) {
    this.eyeColor = eyeColor;
    this.hairColor = hairColor;
}

Parent.prototype.getEyeColor = function() {
  console.log('has ' + this.eyeColor);
}

Parent.prototype.getHairColor = function() {
  console.log('has ' + this.hairColor);
}

function Child(firstName, lastName) {
  Parent.call(this, arguments[2], arguments[3]);
  this.firstName = firstName;
  this.lastName = lastName;
}

Child.prototype = Parent.prototype;

var child = new Child('Bob', 'Smith', 'blue', 'blonde');
child.getEyeColor(); // has blue eyes
child.getHairColor(); // has blonde hair

The way we utilized the prototype chain above has a quirk. Since the prototype is a live link, by changing the property of one object in the prototype chain, you'd be changing same property of another object as well. Obviously, changing a child's inherited method should not change the parent's method. Object.create resolved this issue by using a polyfill. Thus, with Object.create, you can safely modify a child's property in the prototype chain without affecting the parent's same property in the prototype chain.

ECMAScript 5 introduced Object.create to solve the aforementioned bug in the constructor function for object creation. The Object.create() method CREATES a new object, using an existing object as the prototype of the newly created object. Since a new object is created, you no longer have the issue where modifying the child property in the prototype chain will modify the parent's reference to that property in the chain.

var bobSmith = {
    firstName: "Bob",
    lastName: "Smith",
    sayName: function(){
      return "My name is " + this.firstName + " " + this.lastName;
    }
}

var janeSmith = Object.create(bobSmith, {
    firstName : {  value: "Jane" }
})

console.log(bobSmith.sayName()); // My name is Bob Smith
console.log(janeSmith.sayName()); // My name is Jane Smith
janeSmith.__proto__ == bobSmith; // true
janeSmith instanceof bobSmith; // Uncaught TypeError: Right-hand side of 'instanceof' is not callable. Error occurs because bobSmith is not a constructor function.

Prior to ES6, here was a common creational pattern to utilize function constructors and Object.create:

const View = function(element){
  this.element = element;
}

View.prototype = {
  getElement: function(){
    this.element
  }
}

const SubView = function(element){
  View.call(this, element);
}

SubView.prototype = Object.create(View.prototype);

Now Object.create coupled with constructor functions have been widely used for object creation and inheritance in JavaScript. However, ES6 introduced the concept of classes, which are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript. Thus, JavaScript remains a prototypal language.

ES6 classes make inheritance much easier. We no longer have to manually copy the parent class's prototype functions and reset the child class's constructor.

// create parent class
class Person {
  constructor (name) {
    this.name = name;
  }
}

// create child class and extend our parent class
class Boy extends Person {
  constructor (name, color) {
    // invoke our parent constructor function passing in any required parameters
    super(name);

    this.favoriteColor = color;
  }
}

const boy = new Boy('bob', 'blue')
boy.favoriteColor; // blue

All in all, these 5 different strategies of Object Creation in JavaScript coincided the evolution of the EcmaScript standard.

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

Call method in directive controller from other controller

I got much better solution .

here is my directive , I have injected on object reference in directive and has extend that by adding invoke function in directive code .

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
        /*The object that passed from the cntroller*/
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',

        link: function ($scope, element, attrs) {
            /*This method will be called whet the 'objectToInject' value is changes*/
            $scope.$watch('objectToInject', function (value) {
                /*Checking if the given value is not undefined*/
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                }    
            });
        }
    };
});

Declaring the directive in the HTML with a parameter:

<my-directive object-to-inject="injectedObject"></ my-directive>

my Controller:

app.controller("myController", ['$scope', function ($scope) {
   // object must be empty initialize,so it can be appended
    $scope.injectedObject = {};

    // now i can directly calling invoke function from here 
     $scope.injectedObject.invoke();
}];

Reading from text file until EOF repeats last line

Without to much modifications of the original code, it could become :

while (!iFile.eof())
{  
    int x;
    iFile >> x;
    if (!iFile.eof()) break;
    cerr << x << endl;
}

but I prefer the two other solutions above in general.

Mocking Logger and LoggerFactory with PowerMock and Mockito

The following is a test class that mocks private static final Logger named log in class LogUtil.

In addition to mocking the getLogger factory call, it is necessary to explicitly set the field using reflection, in @BeforeClass

public class LogUtilTest {

    private static Logger logger;

    private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;

    /**
     * Since {@link LogUtil#log} being a static final variable it is only initialized once at the class load time
     * So assertions are also performed against the same mock {@link LogUtilTest#logger}
     */
    @BeforeClass
    public static void beforeClass() {
        logger = mock(Logger.class);
        loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
        loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
        Whitebox.setInternalState(LogUtil.class, "log", logger);
    }

    @AfterClass
    public static void after() {
        loggerFactoryMockedStatic.close();
    }
} 

IN Clause with NULL or IS NULL

I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

SELECT *
FROM (SELECT CASE WHEN id_field IS NULL 
                THEN 0 
                ELSE id_field 
            END AS id_field
      FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

How do I rename a column in a SQLite database table?

CASE 1 : SQLite 3.25.0+

Only the Version 3.25.0 of SQLite supports renaming columns. If your device is meeting this requirement, things are quite simple. The below query would solve your problem:

ALTER TABLE "MyTable" RENAME COLUMN "OldColumn" TO "NewColumn";

CASE 2 : SQLite Older Versions

You have to follow a different Approach to get the result which might be a little tricky

For example, if you have a table like this:

CREATE TABLE student(Name TEXT, Department TEXT, Location TEXT)

And if you wish to change the name of the column Location

Step 1: Rename the original table:

ALTER TABLE student RENAME TO student_temp;

Step 2: Now create a new table student with correct column name:

CREATE TABLE student(Name TEXT, Department TEXT, Address TEXT)

Step 3: Copy the data from the original table to the new table:

INSERT INTO student(Name, Department, Address) SELECT Name, Department, Location FROM student_temp;

Note: The above command should be all one line.

Step 4: Drop the original table:

DROP TABLE student_temp;

With these four steps you can manually change any SQLite table. Keep in mind that you will also need to recreate any indexes, viewers or triggers on the new table as well.

Read all worksheets in an Excel workbook into an R list with data.frames

To read multiple sheets from a workbook, use readxl package as follows:

library(readxl)
library(dplyr)

final_dataFrame <- bind_rows(path_to_workbook %>%
                              excel_sheets() %>%
                              set_names() %>%
                              map(read_excel, path = path_to_workbook))

Here, bind_rows (dplyr) will put all data rows from all sheets into one data frame, and path_to_workbook is the location of your data: "dir/of/the/data/workbook".

How to query values from xml nodes?

Try this:

SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
       RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

Lombok is not generating getter and setter

  • If you use STS. You must have Lombok installed in your Eclipse by running lombok-xyz.jar

  • Please Try the Following the Steps:

    1. Include pom in Maven .
    2. Exit/Shutdown STS
    3. Find lombok Jar in ~/.m2/repository/org/projectlombok/lombok/version.x
    4. From Command Prompt/Shell java -jar lombok-1.x.y.jar Project Lombok Installer

    5. Start STS

Thats all.

EDIT: I did this and was still showing errors, as mentioned in the comments. So I updated the project: right-click on project -> Maven -> Update Project and the errors disappeared.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Even if you've configured Apache to listen on another port, you will still get this error if another program is using the default SSL port 443.

What you also need to edit is the http-ssl.conf file and alter the line Listen 443 and change the port number there.

To show error message without alert box in Java Script

Try like this:

function validate(el, status){
     var targetVal = document.getElementById(el).value;
     var statusEl = document.getElementById(status);
     if(targetVal.length > 0){
        statusEl.innerHTML = '';
  }
     else{
        statusEL.innerHTML = "Invalid Name";
   }
}

Now HTML:

<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
  First_Name
  <input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
  <br />
  <span id="fnameStatus"></span>
  <br />
  Last_Name
  <input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')"> 
  <br />
  <span id="lnameStatus"></span>
  <br />
  <input type=button value=check> 
</form>
</body>
</html>

How do I force make/GCC to show me the commands?

Library makefiles, which are generated by autotools (the ./configure you have to issue) often have a verbose option, so basically, using make VERBOSE=1 or make V=1 should give you the full commands.

But this depends on how the makefile was generated.

The -d option might help, but it will give you an extremely long output.

bash assign default value

Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

${parameter-default}, ${parameter:-default}

If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

unset EGGS
echo 1 ${EGGS-spam}   # 1 spam
echo 2 ${EGGS:-spam}  # 2 spam

EGGS=
echo 3 ${EGGS-spam}   # 3
echo 4 ${EGGS:-spam}  # 4 spam

EGGS=cheese
echo 5 ${EGGS-spam}   # 5 cheese
echo 6 ${EGGS:-spam}  # 6 cheese

${parameter=default}, ${parameter:=default}

If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS     # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS     # 2 spam

EGGS=
: ${EGGS=spam}
echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS     # 4 spam

EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS     # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS     # 6 cheese

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

unset EGGS
echo 1 ${EGGS+spam}  # 1
echo 2 ${EGGS:+spam} # 2

EGGS=
echo 3 ${EGGS+spam}  # 3 spam
echo 4 ${EGGS:+spam} # 4

EGGS=cheese
echo 5 ${EGGS+spam}  # 5 spam
echo 6 ${EGGS:+spam} # 6 spam

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

Convert an image to grayscale in HTML/CSS

Doesn't look like it's possible (yet), even with CSS3 or proprietary -webkit- or -moz- CSS properties.

However, I did find this post from last June that used SVG filters on HTML. Not available in any current browser (the demo hinted at a custom WebKit build), but very impressive as a proof of concept.

incompatible character encodings: ASCII-8BIT and UTF-8

Try to find the exact line which causing this problem and then enforce UTF8 coding, this solution worked for me.

title.to_s.force_encoding("UTF-8")

How to zip a whole folder using PHP

This is a function that zips a whole folder and its contents in to a zip file and you can use it simple like this :

addzip ("path/folder/" , "/path2/folder.zip" );

function :

// compress all files in the source directory to destination directory 
    function create_zip($files = array(), $dest = '', $overwrite = false) {
    if (file_exists($dest) && !$overwrite) {
        return false;
    }
    if (($files)) {
        $zip = new ZipArchive();
        if ($zip->open($dest, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        foreach ($files as $file) {
            $zip->addFile($file, $file);
        }
        $zip->close();
        return file_exists($dest);
    } else {
        return false;
    }
}

function addzip($source, $destination) {
    $files_to_zip = glob($source . '/*');
    create_zip($files_to_zip, $destination);
    echo "done";
}