Programs & Examples On #Pgm

PGM is a grayscale image format used by the Netpbm library and other graphics software.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Even without looking at assembly, the most obvious reason is that /= 2 is probably optimized as >>=1 and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.

Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2 as >>=1 would be the best 1st place to look.


On an unrelated note, if n is odd, the expression n*3+1 will always be even. So there is no need to check. You can change that branch to

{
   n = (n*3+1) >> 1;
   count += 2;
}

So the whole statement would then be

if (n & 1)
{
    n = (n*3 + 1) >> 1;
    count += 2;
}
else
{
    n >>= 1;
    ++count;
}

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

Command /usr/bin/codesign failed with exit code 1

All I had to do is to disable automatic signing, then re-nable it, and choose my team identity. And it worked!

Circle line-segment collision detection algorithm?

Here is my solution in TypeScript, following the idea that @Mizipzor suggested (using projection):

/**
 * Determines whether a line segment defined by a start and end point intersects with a sphere defined by a center point and a radius
 * @param a the start point of the line segment
 * @param b the end point of the line segment
 * @param c the center point of the sphere
 * @param r the radius of the sphere
 */
export function lineSphereIntersects(
  a: IPoint,
  b: IPoint,
  c: IPoint,
  r: number
): boolean {
  // find the three sides of the triangle formed by the three points
  const ab: number = distance(a, b);
  const ac: number = distance(a, c);
  const bc: number = distance(b, c);

  // check to see if either ends of the line segment are inside of the sphere
  if (ac < r || bc < r) {
    return true;
  }

  // find the angle between the line segment and the center of the sphere
  const numerator: number = Math.pow(ac, 2) + Math.pow(ab, 2) - Math.pow(bc, 2);
  const denominator: number = 2 * ac * ab;
  const cab: number = Math.acos(numerator / denominator);

  // find the distance from the center of the sphere and the line segment
  const cd: number = Math.sin(cab) * ac;

  // if the radius is at least as long as the distance between the center and the line
  if (r >= cd) {
    // find the distance between the line start and the point on the line closest to
    // the center of the sphere
    const ad: number = Math.cos(cab) * ac;
    // intersection occurs when the point on the line closest to the sphere center is
    // no further away than the end of the line
    return ad <= ab;
  }
  return false;
}

export function distance(a: IPoint, b: IPoint): number {
  return Math.sqrt(
    Math.pow(b.z - a.z, 2) + Math.pow(b.y - a.y, 2) + Math.pow(b.x - a.x, 2)
  );
}

export interface IPoint {
  x: number;
  y: number;
  z: number;
}

Environment variable substitution in sed

I had similar problem, I had a list and I have to build a SQL script based on template (that contained @INPUT@ as element to replace):

for i in LIST 
do
    awk "sub(/\@INPUT\@/,\"${i}\");" template.sql >> output
done

How to count duplicate value in an array in javascript

public class CalculateCount {
public static void main(String[] args) {
    int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
    Arrays.sort(a);
    int count=1;
    int i;
    for(i=0;i<a.length-1;i++){
        if(a[i]!=a[i+1]){
            System.out.println("The Number "+a[i]+" appears "+count+" times");
            count=1;                
        }
        else{
            count++;
        }
    }
    System.out.println("The Number "+a[i]+" appears "+count+" times");

}   

}

Passing data to a jQuery UI Dialog

i hope this helps

$("#dialog-yesno").dialog({
    autoOpen: false,
    resizable: false,
    closeOnEscape: false,
    height:180,
    width:350,
    modal: true,
    show: "blind",
    open: function() {
        $(document).unbind('keydown.dialog-overlay');
        },
    buttons: {
        "Delete": function() {
            $(this).dialog("close");
            var dir = $(this).data('link').href;
            var arr=dir.split("-");
            delete(arr[1]);
        },
    "Cancel": function() {
        $(this).dialog("close");
        }
    }
});



<a href="product-002371" onclick="$( '#dialog-yesno' ).data('link', this).dialog( 'open' ); return false;">Delete</a>

jQuery date/time picker

By far the nicest and simplest DateTime picker option is http://trentrichardson.com/examples/timepicker/.

It is an extension of the jQuery UI Datepicker so it will support the same themes as well it works very much the same way, similar syntax, etc. This should be packaged with the jQuery UI imo.

How are parameters sent in an HTTP POST request?

The default media type in a POST request is application/x-www-form-urlencoded. This is a format for encoding key-value pairs. The keys can be duplicate. Each key-value pair is separated by an & character, and each key is separated from its value by an = character.

For example:

Name: John Smith
Grade: 19

Is encoded as:

Name=John+Smith&Grade=19

This is placed in the request body after the HTTP headers.

vue.js 2 how to watch store values from vuex

It's as simple as:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

How do you list volumes in docker containers?

Here is my version to find mount points of a docker compose. In use this to backup the volumes.

 # for Id in $(docker-compose -f ~/ida/ida.yml ps -q); do docker inspect -f '{{ (index .Mounts 0).Source }}' $Id; done
/data/volumes/ida_odoo-db-data/_data
/data/volumes/ida_odoo-web-data/_data

This is a combination of previous solutions.

How to check whether a int is not null or empty?

public class Demo {
    private static int i;
    private static Integer j;
    private static int k = -1;

    public static void main(String[] args) {
        System.out.println(i+" "+j+" "+k);
    }
}

OutPut: 0 null -1

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

In my case, that problem is about permissions. if you open android studio as administrator (or using sudo) then if you open the project again as normal user, android studio may not delete some files because when you open the project as administrator, some project files permissions are changed. If you lived those steps, I think you should clone the project from your VCS (git, tfs, svn etc.) again. Otherwise you have to configure project file - folder permissions.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

How to iterate over the keys and values with ng-repeat in AngularJS?

How about:

<table>
  <tr ng-repeat="(key, value) in data">
    <td> {{key}} </td> <td> {{ value }} </td>
  </tr>
</table>

This method is listed in the docs: https://docs.angularjs.org/api/ng/directive/ngRepeat

Error:Unable to locate adb within SDK in Android Studio

I know this is silly, but in my case while I was getting the same error message, just changing the USB cable used to connect the device fixed the problem :O

Perhaps this might benefit someone else as well?!

Remove tracking branches no longer on remote

This is gonna delete all the remote branches that are not present locally (in ruby):

bs = `git branch`.split; bs2 = `git branch -r | grep origin`.split.reject { |b| bs.include?(b.split('/')[1..-1].join('/')) }; bs2.each { |b| puts `git  push origin --delete #{b.split('/')[1..-1].join('/')}` }

Explained:

# local branches
bs = `git branch`.split
# remote branches
bs2 = `git branch -r | grep origin`.split
# reject the branches that are present locally (removes origin/ in front)
bs2.reject! { |b| bs.include?(b.split('/')[1..-1].join('/')) }
# deletes the branches (removes origin/ in front)
bs2.each { |b| puts `git  push origin --delete #{b.split('/')[1..-1].join('/')}` }

Make A List Item Clickable (HTML/CSS)

I'm sure it is a late response, but maybe is useful for somebody else. You can put all your <li> element content into <a> tag and add the following css:

li a { 
    display: block; 
    /* and you can use padding for additional space if needs, as a clickable area / or other styling */ 
    padding: 5px 20px; 
}

Moving up one directory in Python

In Python 3.4 pathlib was introduced:

>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')

It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.

how to fix Cannot call sendRedirect() after the response has been committed?

you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

Remove '\' char from string c#

line = line.Replace("\\", "");

Javascript Array.sort implementation?

The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not stable (in the sorting sense of the word) when sorting a map. IE's sort() is stable.

How to embed new Youtube's live video permanent URL?

The issue is two-fold:

  1. WordPress reformats the YouTube link
  2. You need a custom embed link to support a live stream embed

As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.

You will need to use the following URL format for the embed:

<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>

The &autoplay=1 is not necessary, but I like to include it. Change CHANNEL to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:

<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>

Let me know if that worked for you!

How to search for an element in a golang slice

With a simple for loop:

for _, v := range myconfig {
    if v.Key == "key1" {
        // Found!
    }
}

Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

It would be faster to use a range loop just on the index, this avoids copying the elements:

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
    }
}

Notes:

It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
        break
    }
}

Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
    confMap[v.Key] = v.Value
}

// And then to find values by key:
if v, ok := confMap["key1"]; ok {
    // Found
}

MVC Razor @foreach

When people say don't put logic in views, they're usually referring to business logic, not rendering logic. In my humble opinion, I think using @foreach in views is perfectly fine.

How to use Collections.sort() in Java?

Sort the unsorted hashmap in ascending order.

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

How to make rpm auto install dependencies

Matthew's answer awoke many emotions, because of the fact that it still lacks a minor detail. The general command would be:

# yum --nogpgcheck localinstall <package1_file_name> ... <packageN_file_name>

The package_file_name above can include local absolute or relative path, or be a URL (possibly even an URI).

Yum would search for dependencies among all package files given on the command line AND IF IT FAILS to find the dependencies there, it will also use any configured and enabled yum repositories.

Neither the current working directory, nor the paths of any of package_file_name will be searched, except when any of these directories has been previously configured as an enabled yum repository.

So in the OP's case the yum command:

# cd <path with pkg files>; yum --nogpgcheck localinstall ./proj1-1.0-1.x86_64.rpm ./libtest1-1.0-1.x86_64.rpm

would do, as would do the rpm:

# cd <path with pkg files>; rpm -i proj1-1.0-1.x86_64.rpm libtest1-1.0-1.x86_64.rpm

The differencve between these yum and rpm invocations would only be visible if one of the packages listed to be installed had further dependencies on packages NOT listed on the command line.

In such a case rpm will just refuse to continue, while yum would use any configured and enabled yum repositories to search for dependencies, and may possibly succeed.

The current working directory will NOT be searched in any case, except when it has been previously configured as an enabled yum repository.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.

http://en.wikipedia.org/wiki/File:IP_stack_connections.svg

that's the long way of saying, "Yes!"

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

Fixed size div?

<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>

css:

.smallDiv { height: 150px; width: 150px; }

Get Selected Item Using Checkbox in Listview

make the checkbox non-focusable, and on list-item click do this, here codevalue is the position.

    Arraylist<Integer> selectedschools=new Arraylist<Integer>();

    lvPickSchool.setOnItemClickListener(new AdapterView.OnItemClickListener() 
  {

   @Override
        public void onItemClick(AdapterView<?> parent, View view, int codevalue, long id)
   {
                      CheckBox cb = (CheckBox) view.findViewById(R.id.cbVisitingStatus);

            cb.setChecked(!cb.isChecked());
            if(cb.isChecked())
            {

                if(!selectedschool.contains(codevaule))
                {
                    selectedschool.add(codevaule);
                }
            }
            else
            {
                if(selectedschool.contains(codevaule))
                {
                    selectedschool.remove(codevaule);
                }
            }
        }
    });

Should I test private methods or only public ones?

The answer to "Should I test private methods?" is ".......sometimes". Typically you should be testing against the interface of your classes.

  • One of the reasons is because you do not need double coverage for a feature.
  • Another reason is that if you change private methods, you will have to update each test for them, even if the interface of your object hasn't changed at all.

Here is an example:

class Thing
  def some_string
    one + two
  end

  private 

  def one
    'aaaa'
  end

  def two
    'bbbb'
  end

end


class RefactoredThing
def some_string
    one + one_a + two + two_b
  end

  private 

  def one
    'aa'
  end

  def one_a
    'aa'
  end

  def two
    'bb'
  end

  def two_b
    'bb'
  end
end

In RefactoredThing you now have 5 tests, 2 of which you had to update for refactoring, but your object's functionality really hasn't changed. So let's say that things are more complex than that and you have some method that defines the order of the output such as:

def some_string_positioner
  if some case
  elsif other case
  elsif other case
  elsif other case
  else one more case
  end
end

This shouldn't be run by an outside user, but your encapsulating class may be to heavy to run that much logic through it over and over again. In this case maybe you would rather extract this into a seperate class, give that class an interface and test against it.

And finally, let's say that your main object is super heavy, and the method is quite small and you really need to ensure that the output is correct. You are thinking, "I have to test this private method!". Have you that maybe you can make your object lighter by passing in some of the heavy work as an initialization parameter? Then you can pass something lighter in and test against that.

UnsatisfiedDependencyException: Error creating bean with name

I just added the @Repository annotation to Repository interface and @EnableJpaRepositories ("domain.repositroy-package") to the main class. It worked just fine.

Checking for an empty file in C++

How about (not elegant way though )

int main( int argc, char* argv[] )
{
    std::ifstream file;
    file.open("example.txt");

    bool isEmpty(true);
    std::string line;

    while( file >> line ) 
        isEmpty = false;

        std::cout << isEmpty << std::endl;
}

OpenCV Python rotate image by X degrees around specific point

I had issues with some of the above solutions, with getting the correct "bounding_box" or new size of the image. Therefore here is my version

def rotation(image, angleInDegrees):
    h, w = image.shape[:2]
    img_c = (w / 2, h / 2)

    rot = cv2.getRotationMatrix2D(img_c, angleInDegrees, 1)

    rad = math.radians(angleInDegrees)
    sin = math.sin(rad)
    cos = math.cos(rad)
    b_w = int((h * abs(sin)) + (w * abs(cos)))
    b_h = int((h * abs(cos)) + (w * abs(sin)))

    rot[0, 2] += ((b_w / 2) - img_c[0])
    rot[1, 2] += ((b_h / 2) - img_c[1])

    outImg = cv2.warpAffine(image, rot, (b_w, b_h), flags=cv2.INTER_LINEAR)
    return outImg

How to know which version of Symfony I have?

if you are in app_dev, you can find symfony version at the bottom left corner of the page

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

How to "grep" out specific line ranges of a file

Try using sed as mentioned on http://linuxcommando.blogspot.com/2008/03/using-sed-to-extract-lines-in-text-file.html. For example use

sed '2,4!d' somefile.txt

to print from the second line to the fourth line of somefile.txt. (And don't forget to check http://www.grymoire.com/Unix/Sed.html, sed is a wonderful tool.)

How to change the name of a Django app?

In many cases, I believe @allcaps's answer works well.

However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.

Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.

As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:

  1. Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.

  2. makemigrations and migrate

  3. Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and migrate again.

At this point, everything still works, because the original app and its data are still in place.

  1. Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.

  2. Once you are certain that everything works, you can remove the original app.

This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.

How to convert image to byte array

This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array

   public static byte[] imageConversion(string imageName){            


        //Initialize a file stream to read the image file
        FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);

        //Initialize a byte array with size of stream
        byte[] imgByteArr = new byte[fs.Length];

        //Read data from the file stream and put into the byte array
        fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));

        //Close a file stream
        fs.Close();

        return imageByteArr
    }

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

The separate XML solution never worked for me and other's recently ...

I usually follow this process and something helps:

  1. Stop the server (Make sure its stopped via Task Manager, I killed javaw.exe as many times Eclipse doesn't really shut down properly)
  2. Right click the Server->'Add and Remove'. Remove the project. Finish.
  3. Right click the Server->'Add and Remove'. Add the project. Finish.
  4. Restart see if works, if not continue
  5. Double click the Server... See where its getting published (Server Path: which I think goes to a tmp# directory for me since I use an already-installed Tomcat instance I re-use, not sure if would be different if use Eclipse's internal/bundled tomcat server)
  6. Right click on Server and 'Clean' ... Last one worked for me last time (so may want to try this first), Adding/Removing project worked for me other times. If doesn't work, continue ...
  7. Delete all files from the Server Path and see if all files actually get built and published there (/WEB-INF/classes and other regular files in / webroot).
  8. Restart Eclipse and/or machine (not sure I ever needed to get to this point)

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

One particular case : Before learning bootstrap grid system, make sure browser zoom is set to 100% (a hundred percent). For example : If screen resolution is (1600px x 900px) and browser zoom is 175%, then "bootstrap-ped" elements will be stacked.

HTML

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-4">class="col-lg-4"</div>
        <div class="col-lg-4">class="col-lg-4"</div>
    </div>
</div>

Chrome zoom 100%

Browser 100 percent - elements placed horizontally

Chrome zoom 175%

Browser 175 percent - stacked elements

CSS3 selector to find the 2nd div of the same class

.parent_class div:first-child + div

I just used the above to find the second div by chaining first-child with the + selector.

ActiveRecord OR query

Use ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

The resulting SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))

How to split a string into an array in Bash?

UPDATE: Don't do this, due to problems with eval.

With slightly less ceremony:

IFS=', ' eval 'array=($string)'

e.g.

string="foo, bar,baz"
IFS=', ' eval 'array=($string)'
echo ${array[1]} # -> bar

Preserve line breaks in angularjs

Try:

<div ng-repeat="item in items">
  <pre>{{item.description}}</pre>
</div>

The <pre> wrapper will print text with \n as text

also if you print the json, for better look use json filter, like:

<div ng-repeat="item in items">
  <pre>{{item.description|json}}</pre>
</div>

Demo

I agree with @Paul Weber that white-space: pre-wrap; is better approach, anyways using <pre> - the quick way mostly for debug some stuff (if you don't want to waste time on styling)

Detect whether current Windows version is 32 bit or 64 bit

In C#:

public bool Is64bit() {
    return Marshal.SizeOf(typeof(IntPtr)) == 8;
}

In VB.NET:

Public Function Is64bit() As Boolean
   If Marshal.SizeOf(GetType(IntPtr)) = 8 Then Return True
   Return False
End Function

How to sum the values of one column of a dataframe in spark/scala

If you want to sum all values of one column, it's more efficient to use DataFrame's internal RDD and reduce.

import sqlContext.implicits._
import org.apache.spark.sql.functions._

val df = sc.parallelize(Array(10,2,3,4)).toDF("steps")
df.select(col("steps")).rdd.map(_(0).asInstanceOf[Int]).reduce(_+_)

//res1 Int = 19

Create XML file using java

Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
        // root element


Element rootElement = doc.createElement("words");
            doc.appendChild(rootElement);
while (ptbt.hasNext()) {
                CoreLabel label = ptbt.next();
                System.out.println(label);

                m = r1.matcher(label.toString());
                //System.out.println(m.find());
                if (m.find() == true) {
                    Element w = doc.createElement("word");                  
                    w.appendChild(doc.createTextNode(label.toString()));
                    rootElement.appendChild(w);
                }

TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
        transformer.transform(source, result);
        // Output to console for testing
        StreamResult consoleResult = new StreamResult(System.out);
        transformer.transform(source, consoleResult);

This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I've read the sentence from a file)

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

How do you determine what technology a website is built on?

http://guess.scritch.org/ does this for CMSs.

Just pop in the URL and it'll try to guess the CMS. In this case it tells me my blog is running wordpress 3.4.2 (which is correct, I just checked!)

enter image description here

Programmatically get the version number of a DLL

This works if the dll is .net or Win32. Reflection methods only work if the dll is .net. Also, if you use reflection, you have the overhead of loading the whole dll into memory. The below method does not load the assembly into memory.

// Get the file version.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll");

// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' +
                  "Version number: " + myFileVersionInfo.FileVersion);

From: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

original source

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

String Concatenation in EL

1.The +(operator) has not effect to that in using EL. 2.so this is the way,to use that

<c:set var="enabled" value="${value} enabled" />


<c:out value="${empty value ? 'none' : enabled}" />

is this helpful to You ?

Are email addresses case sensitive?

From RFC 5321, section 2.3.11:

The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

"Name servers and resolvers must compare [domains] in a case-insensitive manner"

In short, you are safe to treat email addresses as case-insensitive.

Removing object from array in Swift 3

Try this in Swift 3

array.remove(at: Index)

Instead of

array.removeAtIndex(index)

Update

"Declaration is only valid at file scope".

Make sure the object is in scope. You can give scope "internal", which is default.

index(of:<Object>) to work, class should conform to Equatable

How to have comments in IntelliSense for function in Visual Studio?

To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:

  • C#: ///

  • VB: '''

See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.

Get time in milliseconds using C#

long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

This is actually how the various Unix conversion methods are implemented in the DateTimeOffset class (.NET Framework 4.6+, .NET Standard 1.3+):

long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

How to git reset --hard a subdirectory?

Ajedi32's answer is what I was looking for but for some commits I ran into this error:

error: cannot apply binary patch to 'path/to/directory' without full index line

May be because some files of the directory are binary files. Adding '--binary' option to the git diff command fixed it:

git diff --binary --cached commit -- path/to/directory | git apply -R --index

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

error: function returns address of local variable

The local variables have a lifetime which extends only inside the block in which it is defined. The moment the control goes outside the block in which the local variable is defined, the storage for the variable is no more allocated (not guaranteed). Therefore, using the memory address of the variable outside the lifetime area of the variable will be undefined behaviour.

On the other hand you can do the following.

 char *str_to_ret = malloc (sizeof (char) * required_size);
  .
  .
  .
 return str_to_ret;

And use the str_to_ret instead. And when returning str_to_ret, the address allocated by malloc will be returned. The memory allocated by malloc is allocated from the heap, which has a lifetime which spans the entire execution of the program. Therefore, you can access the memory location from any block and any time while the program is running.

Also note that it is a good practice that after you have done with the allocated memory block, free it to save from memory leaks. Once you free the memory, you can't access that block again.

What's the difference between "git reset" and "git checkout"?

The key difference in a nutshell is that reset moves the current branch reference, while checkout does not (it moves HEAD).

As the Pro Git book explains under Reset Demystified,

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does); reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch (i.e. you’re currently on the master branch), running git reset 9e5e6a4 will start by making master point to 9e5e6a4. [emphasis added]

See also VonC's answer for a very helpful text and diagram excerpt from the same article, which I won't duplicate here.

Of course there are a lot more details about what effects checkout and reset can have on the index and the working tree, depending on what parameters are used. There can be lots of similarities and differences between the two commands. But as I see it, the most crucial difference is whether they move the tip of the current branch.

What is the best way to implement a "timer"?

Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

PHP multidimensional array search by value

Just share, maybe can like this.

if( ! function_exists('arraySearchMulti')){
function arraySearchMulti($search,$key,$array,$returnKey=false)
{
    foreach ($array as $k => $val) {
        if (isset($val[$key])) {
            if ((string)$val[$key] == (string)$search) {
                return ($returnKey ? $k : $val);
            }
        }else{
            return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);
        }
    }
    return null;
}}

Convert JSONArray to String Array

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");

Cannot open backup device. Operating System error 5

I had this issue recently as well, however I was running the backup job from server A but the database being backed up was on server B to a file share on server C. When the agent on server A tells server B to run a backup t-sql command, its actually the service account that sql is running under on SERVER B that attempts to write the backup to server C.

Just remember, its the service account of the sql server performing the actual BACKUP DATABASE command is what needs privileges on the file system, not the agent.

angular.service vs angular.factory

  angular.service('myService', myServiceFunction);
  angular.factory('myFactory', myFactoryFunction);

I had trouble wrapping my head around this concept until I put it to myself this way:

Service: the function that you write will be new-ed:

  myInjectedService  <----  new myServiceFunction()

Factory: the function (constructor) that you write will be invoked:

  myInjectedFactory  <---  myFactoryFunction()

What you do with that is up to you, but there are some useful patterns...

Such as writing a service function to expose a public API:

function myServiceFunction() {
  this.awesomeApi = function(optional) {
    // calculate some stuff
    return awesomeListOfValues;
  }
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.awesome = myInjectedService.awesomeApi();

Or using a factory function to expose a public API:

function myFactoryFunction() {
  var aPrivateVariable = "yay";

  function hello() {
    return "hello mars " + aPrivateVariable;
  }
  
  // expose a public API
  return {
    hello: hello
  };
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.hello = myInjectedFactory.hello();

Or using a factory function to return a constructor:

function myFactoryFunction() {
    return function() {
        var a = 2;
        this.a2 = function() {
            return a*2;
        };
    };
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();

Which one to use?...

You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:

var myShinyNewObject = new myInjectedService.myFunction()

which is arguably less desirable than this:

var myShinyNewObject = new myInjectedFactory();

(But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.)


One more thing, they are all Singletons...

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

mysql said: Cannot connect: invalid settings. xampp

In xampp\phpMyAdmin\config.inc.php : changing:

'config';$cfg['Servers'][$i]['user'] = 'root'

to

'config';$cfg['Servers'][$i]['user'] = 'user'

and

$cfg['Servers'][$i]['controluser'] = 'root'

to

$cfg['Servers'][$i]['controluser'] = 'user'

Solved my Problem.

How do you find the current user in a Windows environment?

In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find "explorer"] returns a line that contains the explorer.exe process owner's, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.

In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find ">"].

How do I determine the dependencies of a .NET application?

Try compiling your .NET assembly with the option --staticlink:"Namespace.Assembly" . This forces the compiler to pull in all the dependencies at compile time. If it comes across a dependency that's not referenced it will give a warning or error message usually with the name of that assembly.

Namespace.Assembly is the assembly you suspect as having the dependency problem. Typically just statically linking this assembly will reference all dependencies transitively.

css h1 - only as wide as the text

You can use display:inline-block to force this behavior

What is the difference between iterator and iterable and how to use them?

Iterable were introduced to use in for each loop in java

public interface Collection<E> extends Iterable<E>  

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

goto command prompt

netstat -aon

for linux

netstat -tulpn | grep 'your_port_number'

it will show you something like

 TCP    192.1.200.48:2053      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2055      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2126      213.146.189.201:12350  ESTABLISHED     1308
 TCP    192.1.200.48:3918      192.1.200.2:8073       ESTABLISHED     1504
 TCP    192.1.200.48:3975      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:3976      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:4039      209.85.153.100:80      ESTABLISHED     248
 TCP    192.1.200.48:8080      209.85.153.100:80      ESTABLISHED     248

check which process has binded your port. here in above example its 248 now if you are sure that you need to kill that process fire

Linux:

kill -9 248

Windows:

taskkill /f /pid 248

it will kill that process

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

Please find below codes for ios 10 request permission sample for info.plist.
You can modify for your custom message.

    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} Camera Usage</string>

    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>${PRODUCT_NAME} BluetoothPeripheral</string>

    <key>NSCalendarsUsageDescription</key>
    <string>${PRODUCT_NAME} Calendar Usage</string>

    <key>NSContactsUsageDescription</key>
    <string>${PRODUCT_NAME} Contact fetch</string>

    <key>NSHealthShareUsageDescription</key>
    <string>${PRODUCT_NAME} Health Description</string>

    <key>NSHealthUpdateUsageDescription</key>
    <string>${PRODUCT_NAME} Health Updates</string>

    <key>NSHomeKitUsageDescription</key>
    <string>${PRODUCT_NAME} HomeKit Usage</string>

    <key>NSLocationAlwaysUsageDescription</key>
    <string>${PRODUCT_NAME} Use location always</string>

    <key>NSLocationUsageDescription</key>
    <string>${PRODUCT_NAME} Location Updates</string>

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>${PRODUCT_NAME} WhenInUse Location</string>

    <key>NSAppleMusicUsageDescription</key>
    <string>${PRODUCT_NAME} Music Usage</string>

    <key>NSMicrophoneUsageDescription</key>
    <string>${PRODUCT_NAME} Microphone Usage</string>

    <key>NSMotionUsageDescription</key>
    <string>${PRODUCT_NAME} Motion Usage</string>

    <key>kTCCServiceMediaLibrary</key>
    <string>${PRODUCT_NAME} MediaLibrary Usage</string>

    <key>NSPhotoLibraryUsageDescription</key>
    <string>${PRODUCT_NAME} PhotoLibrary Usage</string>

    <key>NSRemindersUsageDescription</key>
    <string>${PRODUCT_NAME} Reminder Usage</string>

    <key>NSSiriUsageDescription</key>
    <string>${PRODUCT_NAME} Siri Usage</string>

    <key>NSSpeechRecognitionUsageDescription</key>
    <string>${PRODUCT_NAME} Speech Recognition Usage</string>

    <key>NSVideoSubscriberAccountUsageDescription</key>
    <string>${PRODUCT_NAME} Video Subscribe Usage</string>

iOS 11 and plus, If you want to add photo/image to your library then you must add this key

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>${PRODUCT_NAME} library Usage</string>

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

How to set environment variables in Jenkins?

For some reason sudo su - jenkins does not log me to jenkins user, I ended up using different approach.

I was successful setting the global env variables using using jenkins config.xml at /var/lib/jenkins/config.xml (installed in Linux/ RHEL) - without using external plugins.

I simply had to stop jenkins add then add globalNodeProperties, and then restart.

Example, I'm defining variables APPLICATION_ENVIRONMENT and SPRING_PROFILES_ACTIVE to continious_integration below,

<?xml version='1.0' encoding='UTF-8'?>
<hudson>

  <globalNodeProperties>
    <hudson.slaves.EnvironmentVariablesNodeProperty>
      <envVars serialization="custom">
        <unserializable-parents/>
        <tree-map>
          <default>
            <comparator class="hudson.util.CaseInsensitiveComparator"/>
          </default>
          <int>2</int>
          <string>APPLICATION_ENVIRONMENT</string>
          <string>continious_integration</string>
          <string>SPRING_PROFILES_ACTIVE</string>
          <string>continious_integration</string>
        </tree-map>
      </envVars>
    </hudson.slaves.EnvironmentVariablesNodeProperty>
  </globalNodeProperties>
</hudson>

How can I disable editing cells in a WPF Datagrid?

The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.

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;

Object not found! The requested URL was not found on this server. localhost

One thing I found out is that your folder holding your php/html files cannot be named the same name as the folder in your HTDOCS carrying your project.

How do you detect where two line segments intersect?

C and Objective-C

Based on Gareth Rees' answer

const AGKLine AGKLineZero = (AGKLine){(CGPoint){0.0, 0.0}, (CGPoint){0.0, 0.0}};

AGKLine AGKLineMake(CGPoint start, CGPoint end)
{
    return (AGKLine){start, end};
}

double AGKLineLength(AGKLine l)
{
    return CGPointLengthBetween_AGK(l.start, l.end);
}

BOOL AGKLineIntersection(AGKLine l1, AGKLine l2, CGPoint *out_pointOfIntersection)
{
    // http://stackoverflow.com/a/565282/202451

    CGPoint p = l1.start;
    CGPoint q = l2.start;
    CGPoint r = CGPointSubtract_AGK(l1.end, l1.start);
    CGPoint s = CGPointSubtract_AGK(l2.end, l2.start);
    
    double s_r_crossProduct = CGPointCrossProductZComponent_AGK(r, s);
    double t = CGPointCrossProductZComponent_AGK(CGPointSubtract_AGK(q, p), s) / s_r_crossProduct;
    double u = CGPointCrossProductZComponent_AGK(CGPointSubtract_AGK(q, p), r) / s_r_crossProduct;
    
    if(t < 0 || t > 1.0 || u < 0 || u > 1.0)
    {
        if(out_pointOfIntersection != NULL)
        {
            *out_pointOfIntersection = CGPointZero;
        }
        return NO;
    }
    else
    {
        if(out_pointOfIntersection != NULL)
        {
            CGPoint i = CGPointAdd_AGK(p, CGPointMultiply_AGK(r, t));
            *out_pointOfIntersection = i;
        }
        return YES;
    }
}

CGFloat CGPointCrossProductZComponent_AGK(CGPoint v1, CGPoint v2)
{
    return v1.x * v2.y - v1.y * v2.x;
}

CGPoint CGPointSubtract_AGK(CGPoint p1, CGPoint p2)
{
    return (CGPoint){p1.x - p2.x, p1.y - p2.y};
}

CGPoint CGPointAdd_AGK(CGPoint p1, CGPoint p2)
{
    return (CGPoint){p1.x + p2.x, p1.y + p2.y};
}

CGFloat CGPointCrossProductZComponent_AGK(CGPoint v1, CGPoint v2)
{
    return v1.x * v2.y - v1.y * v2.x;
}

CGPoint CGPointMultiply_AGK(CGPoint p1, CGFloat factor)
{
    return (CGPoint){p1.x * factor, p1.y * factor};
}

Many of the functions and structs are private, but you should pretty easy be able to know what's going on. This is public on this repo https://github.com/hfossli/AGGeometryKit/

Android new Bottom Navigation bar or BottomNavigationView

This library, BottomNavigationViewEx, extends Google's BottomNavigationView. You can easily customise Google's library to have bottom navigation bar the way you want it to be. You can disable the shifting mode, change visibility of the icons and texts and so much more. Definitely try it out.

Can jQuery get all CSS styles associated with an element?

Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.

How to hide the title bar for an Activity in XML with existing custom theme

what works for me:

1- in styles.xml:

 <style name="generalnotitle" parent="Theme.AppCompat.Light" >
          <item name="android:windowNoTitle">true</item>   <!-- //this -->     
   </style>

2- in MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {          
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide(); //<< this
    setContentView(R.layout.activity_main);
}
  1. in manifest inherit the style:

    <activity android:name=".MainActivity" android:theme="@style/generalnotitle">
    

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to replace a character with a newline in Emacs?

inline just: C-M-S-% (if binding keys still default) than replace-string^J

Choosing line type and color in Gnuplot 4.0

You might want to look at the Pyxplot plotting package http://pyxplot.org.uk which has very similar syntax to gnuplot, but with the rough edges cleaned up. It handles colors and line styles quite neatly, and homogeneously between x11 and eps/pdf terminals.

The Pyxplot script for what you want to do above would be:

set style 1 lt 1 lw 3 color red
set style 2 lt 1 lw 3 color blue
set style 3 lt 2 lw 3 color red
set style 4 lt 2 lw 3 color blue
plot 'data1.dat' using 1:3 w l style 1,\
  'data1.dat' using 1:4 w l style 2,\
  'data2.dat' using 1:3 w l style 3,\
  'data2.dat' using 1:4 w l style 4`

String array initialization in Java

You can do the following during declaration:

String names[] = {"Ankit","Bohra","Xyz"};

And if you want to do this somewhere after declaration:

String names[];
names = new String[] {"Ankit","Bohra","Xyz"};

Compile Views in ASP.NET MVC

The answer given here works for some MVC versions but not for others.

The simple solution worked for MVC1 but on upgrading to MVC2 the views were no longer being compliled. This was due to a bug in the website project files. See this Haacked article.

See this: http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx

Passing a method as a parameter in Ruby

You want a proc object:

gaussian = Proc.new do |dist, *args|
  sigma = args.first || 10.0
  ...
end

def weightedknn(data, vec1, k = 5, weightf = gaussian)
  ...
  weight = weightf.call(dist)
  ...
end

Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.


Or, depending on your scope of all this, it may be easier to pass in a method name instead.

def weightedknn(data, vec1, k = 5, weightf = :gaussian)
  ...
  weight = self.send(weightf)
  ...
end

In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send with object_that_has_the_these_math_methods.send


Last but not least, you can hang a block off the method.

def weightedknn(data, vec1, k = 5)
  ...
  weight = 
    if block_given?
      yield(dist)
    else
      gaussian.call(dist)
    end
  end
  ...
end

weightedknn(foo, bar) do |dist|
  # square the dist
  dist * dist
end

But it sounds like you would like more reusable chunks of code here.

Hide div after a few seconds

You can try the .delay()

$(".formSentMsg").delay(3200).fadeOut(300);

call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.

http://api.jquery.com/delay/

Can a constructor in Java be private?

yes a constructor can be private. A private Constructor prevents any other class from instantiating example of private constructor

public class CustomHttpClient {
private static HttpClient customHttpClient;

/** A private Constructor prevents any other class from instantiating. */
private CustomHttpClient() {
}}

Multiple submit buttons in an HTML form

Instead of struggling with multiple submits, JavaScript or anything like that to do some previous/next stuff, an alternative would be to use a carousel to simulate the different pages. Doing this :

  • You don't need multiple buttons, inputs or submits to do the previous/next thing, you have only one input type="submit" in only one form.
  • The values in the whole form are there until the form is submitted.
  • The user can go to any previous page and any next page flawlessly to modify the values.

Example using Bootstrap 5.0.0 :

<div id="carousel" class="carousel slide" data-ride="carousel">
    <form action="index.php" method="post" class="carousel-inner">
        <div class="carousel-item active">
            <input type="text" name="lastname" placeholder="Lastname"/>
        </div>
        <div class="carousel-item">
            <input type="text" name="firstname" placeholder="Firstname"/>
        </div>
        <div class="carousel-item">
            <input type="submit" name="submit" value="Submit"/>
        </div>
    </form>
    <a class="btn-secondary" href="#carousel" role="button" data-slide="prev">Previous page</a>
    <a class="btn-primary" href="#carousel" role="button" data-slide="next">Next page</a>
</div>

WPF ListView - detect when selected item is clicked

I couldn't get the accepted answer to work the way I wanted it to (see Farrukh's comment).

I came up with a slightly different solution which also feels more native because it selects the item on mouse button down and then you're able to react to it when the mouse button gets released:

XAML:

<ListView Name="MyListView" ItemsSource={Binding MyItems}>
<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        <EventSetter Event="PreviewMouseLeftButtonUp" Handler="ListViewItem_PreviewMouseLeftButtonUp" />
    </Style>
</ListView.ItemContainerStyle>

Code behind:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    MyListView.SelectedItems.Clear();

    ListViewItem item = sender as ListViewItem;
    if (item != null)
    {
        item.IsSelected = true;
        MyListView.SelectedItem = item;
    }
}

private void ListViewItem_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {
        // do stuff
    }
}

Style input type file?

use uniform js plugin to style input of any type, select, textarea.

The URL is http://uniformjs.com/

error: use of deleted function

You are using a function, which is marked as deleted.
Eg:

int doSomething( int ) = delete;

The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.

If you see this error, you should check the function declaration for =delete.

To know more about this new feature introduced in C++0x, check this out.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

jQuery trigger event when click outside the element

I know that the question has been answered, but I hope my solution helps other people.

stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.

My solution:

$(document).click(function(e) {
    if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
        $(e.target).closest("#div-exception").attr("id") != "div-exception") {
        alert("Clicked outside!");
    }
});

http://jsfiddle.net/NLDu3/

Accessing localhost of PC from USB connected Android mobile device

Hello you can access your xampp localhost by

  1. Control panel -->
  2. windows defender firewall -->
  3. Advance setting (on left side) --> Inbound Rules --> New Rule --> Port --> in specific local port write your Apache ports --> next --> next then you can access your localhost by using local PC IP address:

How to get root access on Android emulator?

I found that default API 23 x86_64 emulator is rooted by default.

Only numbers. Input number in React

Solution

Today I find use parseInt() is also a good and clean practice. A onChange(e) example is below.

Code

onChange(e){
    this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}

Explanation

  1. parseInt() would return NaN if the parameter is not a number.
  2. parseInt('12a') would return 12.

"echo -n" prints "-n"

When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.

CMake: How to build external projects and include their targets

Edit: CMake now has builtin support for this. See new answer.

You can also force the build of the dependent target in a secondary make process

See my answer on a related topic.

Set Label Text with JQuery

I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Is there way to use two PHP versions in XAMPP?

You can download whatever versions of PHP you need and place them into their own directories, e.g.

c:\php5\

c:\php7\

All you need to do is tell your web server (Apache) which version of PHP to use, which you do by loading the appropriate module. In Apache you can do this by finding the file httpd.conf and then editing the appropriate line:

LoadModule php7_module c:\php7\libphp7.so

You'll have to figure out the correct paths of course - this is just for illustration.

Save httpd.conf and restart your server. Note, if you don't restart it, the changes won't take effect.

There's no GUI switch to be able to do this, you need to edit the .conf file and then restart Apache. Doing this only takes a couple of seconds and you could even comment out a version so "switching" only takes a couple of keystrokes, e.g.

Use PHP 5:

LoadModule php5_module c:\php5\libphp5.so
#LoadModule php7_module c:\php7\libphp7.so

Use PHP 7:

#LoadModule php5_module c:\php5\libphp5.so
LoadModule php7_module c:\php7\libphp7.so

You do not need multiple versions of XAMPP, or to dual boot, or use a different machine, or any of the other "solutions" that have suggested convoluted workarounds. The OP wants to use XAMPP and tell it which version of PHP to use. This is the quickest and most efficient way of doing it, and only requires one XAMPP installation.

Edit 1-Nov-2017: Apparently some people are saying there's no .so files on Windows. The answer I gave was adapted from how I have things set up on my Mac (which does use .so files instead of .dll). The principle of the answer however is still exactly correct. You are using Apache's configuration file, httpd.conf to specify where the PHP module (.so or .dll) is located on your system. So the only difference for Windows would be the file name and/or path location. The answer I've given is also correct for a vanilla installation of Apache/PHP (without XAMPP at all).

Fast way to discover the row count of a table in PostgreSQL

Reference taken from this Blog.

You can use below to query to find row count.

Using pg_class:

 SELECT reltuples::bigint AS EstimatedCount
    FROM   pg_class
    WHERE  oid = 'public.TableName'::regclass;

Using pg_stat_user_tables:

SELECT 
    schemaname
    ,relname
    ,n_live_tup AS EstimatedCount 
FROM pg_stat_user_tables 
ORDER BY n_live_tup DESC;

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

Immediate exit of 'while' loop in C++

Yah Im pretty sure you just put

    break;

right where you want it to exit

like

    if (variable == 1)
    {
    //do something
    }
    else
    {
    //exit
    break;
    }

Android: show/hide a view using an animation

If you only want to animate the height of a view (from say 0 to a certain number) you could implement your own animation:

final View v = getTheViewToAnimateHere();
Animation anim=new Animation(){
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        // Do relevant calculations here using the interpolatedTime that runs from 0 to 1
        v.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, (int)(30*interpolatedTime)));
    }};
anim.setDuration(500);
v.startAnimation(anim);

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

After updating to El Capitan, /usr/local has root:wheel rights.

Change the rights back to the user using:

sudo chown -R $(whoami):admin /usr/local

and:

brew doctor && brew update

This helped me to get Homebrew working again.

Can I use DIV class and ID together in CSS?

Of course you can.

Your HTML there is just fine. To style the elements with css you can use the following approaches:

#y {
    ...
}

.x {
    ...
}

#y.x {
    ...
}

Also you can add as many classes as you wish to your element

<div id="id" class="classA classB classC ...">
</div>

And you can style that element using a selector with any combination of the classes and id. For example:

#id.classA.classB.classC {
     ...
}

#id.classC {
}

What is a 'workspace' in Visual Studio Code?

If the Visual Studio Code is a fresh installation;

  1. Click on extensions, Search for "python" and click on install

  2. Click on view -> explorer If there in no folder added a folder to the Workspace (File->Add folder to Workspace)

  3. If you want to use a virtual python environment, Click on File -> Preference -> settings

Click on "{} open settings JSON" which is in top right corner of the window, then add the path to python.exe file which is in the virtual environment

{
    "python.pythonPath": "C:\\PathTo\\VirtualENV\\python.exe"
}
  1. Start a new terminal and check the correct python interpreter is selected

How to output to the console in C++/Windows

Whether to use subsystem:console or subsystem:windows kind of depends on whether how you want to start your application:

  • If you use subsystem:console, then you get all of the stdout written to the terminal. The trouble is that if you start the application from the Start Menu/Desktop, you (by default) get a console appearing as well as the application window (which can look pretty ugly).
  • If you use subsystem:windows, you won't get stdout/stderr even if you run the application from a DOS window, Cygwin, or other terminal.

If you want the middle way which is to output to the terminal IF the application was started in a terminal, then follow the link that Luke provided in his solution (http://dslweb.nwnexus.com/~ast/dload/guicon.htm)

For reference, I ran into this problem with an application that I want to run in either normal Windows mode or batch mode (that is, as part of a script) depending on command-line switches. The whole differentiation between console and Windows applications is a bit bizarre to Unix folks!

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

MySQL Error: #1142 - SELECT command denied to user

In MySQL query browser go to Tools tab>MySQL Administrator > User Administration and then give the privileges to user.

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

Show Curl POST Request Headers? Is there a way to do this?

You can save all headers sent by curl to a file using :

$f = fopen('request.txt', 'w');
curl_setopt($ch,CURLOPT_VERBOSE,true);
curl_setopt($ch,CURLOPT_STDERR ,$f);

Create request with POST, which response codes 200 or 201 and content

Check out HTTP: Method Definitions: POST.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

Using variable in SQL LIKE statement

But in my opinion one important thing.

The "char(number)" it's lenght of variable.

If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:

DECLARE @variable char(5)
SET @variable = 'Test1%'
SELECT * FROM table WHERE Name like @variable

the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )

The rest of potential interested data like [Test11..Test200] will not be returned in the result.

It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).

In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:

DECLARE @variable varchar(max)
SET @variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like @variable

This returns (Test1 but also Test11..Test19 and Test100..Test199).

Checking for an empty field with MySQL

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
     SELECT `userID` 
     FROM `users` 
     WHERE `userID` 
     IN(SELECT `userID`
               FROM `users_indvSettings`
               WHERE `indvSettingID`=5 AND `optionID`='.$time.')
     AND `email` != "" AND `email` IS NOT NULL
     ');

Change mysql user password using command line

Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
FLUSH PRIVILEGES;

Host is your mysql host.

'setInterval' vs 'setTimeout'

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

WCF Service Returning "Method Not Allowed"

Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address

You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs

How to read line by line of a text area HTML tag

This works without needing jQuery:

var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line

Converting time stamps in excel to dates

below formula worked form me in MS EXEL

=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")

CELL_VALUE is timestamp in milliseconds

here is explanation for text function.

How to remove rows with any zero value

Using tidyverse/dplyr, you can also remove rows with any zero value in a subset of variables:

# variables starting with Mac must be non-zero
filter_at(df, vars(starts_with("Mac")), all_vars((.) != 0))

# variables x, y, and z must be non-zero
filter_at(df, vars(x, y, z), all_vars((.) != 0))

# all numeric variables must be non-zero
filter_if(df, is.numeric, all_vars((.) != 0))

How do I save JSON to local text file

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json" and format to .json

ActiveMQ or RabbitMQ or ZeroMQ or

I've used ActiveMQ in a production environment for about 3 years now. While it gets the job done, lining up versions of the client libraries that work properly and are bug free can be an issue. Were currently looking to transition to RabbitMQ.

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

`&mdash;` or `&#8212;` is there any difference in HTML output?

Could be that using the numeral code is more universal, as it's a direct reference to a character in the html entity table, but I guess they both work everywhere. The first notation is just massively easier to remember for a lot of characters.

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

Programmatically Add CenterX/CenterY Constraints

A solution for me was to create a UILabel and add it to the UIButton as a subview. Finally I added a constraint to center it within the button.

UILabel * myTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
myTextLabel.text = @"Some Text";
myTextLabel.translatesAutoresizingMaskIntoConstraints = false;

[myButton addSubView:myTextLabel];

// Add Constraints
[[myTextLabel centerYAnchor] constraintEqualToAnchor:myButton.centerYAnchor].active = true;
[[myTextLabel centerXAnchor] constraintEqualToAnchor:myButton.centerXAnchor].active = true; 

How do I convert a dictionary to a JSON String in C#?

You can use System.Web.Script.Serialization.JavaScriptSerializer:

Dictionary<string, object> dictss = new Dictionary<string, object>(){
   {"User", "Mr.Joshua"},
   {"Pass", "4324"},
};

string jsonString = (new JavaScriptSerializer()).Serialize((object)dictss);

Postgresql: Scripting psql execution with password

Use -w in the command: psql -h localhost -p 5432 -U user -w

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

Do the following in your terminal

sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

After this you have to restart your server

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Git merge is not possible because I have unmerged files

The error message:

merge: remote/master - not something we can merge

is saying that Git doesn't recognize remote/master. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".

Think of "remotes" as an alias for the url to your Git server. master is your locally checked-out version of the branch. origin/master is the latest version of master from your Git server that you have fetched (downloaded). A fetch is always safe because it will only update the "origin/x" version of your branches.

So, to get your master branch back in sync, first download the latest content from the git server:

git fetch

Then, perform the merge:

git merge origin/master

...But, perhaps the better approach would be:

git pull origin master

The pull command will do the fetch and merge for you in one step.

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

How to get DropDownList SelectedValue in Controller in MVC

If you want to use @Html.DropDownList , follow.

Controller:

var categoryList = context.Categories.Select(c => c.CategoryName).ToList();

ViewBag.CategoryList = categoryList;

View:

@Html.DropDownList("Category", new SelectList(ViewBag.CategoryList), "Choose Category", new { @class = "form-control" })

$("#Category").on("change", function () {
 var q = $("#Category").val();

console.log("val = " + q);
});

Django - how to create a file and save it to a model's FileField?

Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.

Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).

Django 1.4.1

Python 2.7.3

#Model
class MonthEnd(models.Model):
    report = models.FileField(db_index=True, upload_to='not_used')

import csv
from os.path import join

#build and store the file
def write_csv():
    path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
    f = open(path, "w+b")

    #wipe the existing content
    f.truncate()

    csv_writer = csv.writer(f)
    csv_writer.writerow(('col1'))

    for num in range(3):
        csv_writer.writerow((num, ))

    month_end_file = MonthEnd()
    month_end_file.report.name = path
    month_end_file.save()

from my_app.models import MonthEnd

#serve it up as a download
def get_report(request):
    month_end = MonthEnd.objects.get(file_criteria=criteria)

    response = HttpResponse(month_end.report, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=report.csv'

    return response

How do I obtain a list of all schemas in a Sql Server database

You can also use the following query to get Schemas for a specific Database user:

select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name

Run certain code every n seconds

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

How do I add a new column to a Spark DataFrame (using PySpark)?

I would like to offer a generalized example for a very similar use case:

Use Case: I have a csv consisting of:

First|Third|Fifth
data|data|data
data|data|data
...billion more lines

I need to perform some transformations and the final csv needs to look like

First|Second|Third|Fourth|Fifth
data|null|data|null|data
data|null|data|null|data
...billion more lines

I need to do this because this is the schema defined by some model and I need for my final data to be interoperable with SQL Bulk Inserts and such things.

so:

1) I read the original csv using spark.read and call it "df".

2) I do something to the data.

3) I add the null columns using this script:

outcols = []
for column in MY_COLUMN_LIST:
    if column in df.columns:
        outcols.append(column)
    else:
        outcols.append(lit(None).cast(StringType()).alias('{0}'.format(column)))

df = df.select(outcols)

In this way, you can structure your schema after loading a csv (would also work for reordering columns if you have to do this for many tables).

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

You have some errors in your appcontext.xml:

  • Use *-2.5.xsd

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-2.5.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
    
  • Typos in tx:annotation-driven and context:component-scan (. instead of -)

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:component-scan base-package="com.mmycompany" />
    

DataTables fixed headers misaligned with columns in wide tables

Instead using sScrollX,sScrollY use separate div style

.scrollStyle
 {
  height:200px;overflow-x:auto;overflow-y:scroll;
 }

Add below after datatable call in script

 jQuery('.dataTable').wrap('<div class="scrollStyle" />');

Its working perfectly after many tries.

com.jcraft.jsch.JSchException: UnknownHostKey

Supply the public rsa key of the host :-

String knownHostPublicKey = "mywebsite.com ssh-rsa AAAAB3NzaC1.....XL4Jpmp/";

session.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

How to empty the content of a div

This method works best to me:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

To use it we can deploy like this:

document.getElementsByID('DIV_Id').remove();

or

document.getElementsByClassName('DIV_Class').remove();

SQLite DateTime comparison

Right now i am developing using System.Data.SQlite NuGet package (version 1.0.109.2). Which using SQLite version 3.24.0.

And this works for me.

SELECT * FROM tables WHERE datetime 
BETWEEN '2018-10-01 00:00:00' AND '2018-10-10 23:59:59';

I don't net to use the datetime() function. Perhaps they already updated the SQL query on that SQLite version.

position fixed is not working

Another cause could be a parent container that contains the CSS animation property. That's what it was for me.

Check if decimal value is null

I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:

var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;

This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

Angular2 dynamic change CSS property

1) Using inline styles

<div [style.color]="myDynamicColor">

2) Use multiple CSS classes mapping to what you want and switch classes like:

 /* CSS */
 .theme { /* any shared styles */ }
 .theme.blue { color: blue; }
 .theme.red { color: red; }

 /* Template */
 <div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
 <div class="theme" [class.blue]="isBlue">

Code samples from: https://angular.io/cheatsheet

More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Command to delete all pods in all kubernetes namespaces

kubectl delete po,ing,svc,pv,pvc,sc,ep,rc,deploy,replicaset,daemonset --all -A

Best way to select random rows PostgreSQL

The one with the ORDER BY is going to be the slower one.

select * from table where random() < 0.01; goes record by record, and decides to randomly filter it or not. This is going to be O(N) because it only needs to check each record once.

select * from table order by random() limit 1000; is going to sort the entire table, then pick the first 1000. Aside from any voodoo magic behind the scenes, the order by is O(N * log N).

The downside to the random() < 0.01 one is that you'll get a variable number of output records.


Note, there is a better way to shuffling a set of data than sorting by random: The Fisher-Yates Shuffle, which runs in O(N). Implementing the shuffle in SQL sounds like quite the challenge, though.

Click a button programmatically

The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.

Index of Currently Selected Row in DataGridView

Try DataGridView.CurrentCellAddress.

Returns: A Point that represents the row and column indexes of the currently active cell.

E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

How to copy files across computers using SSH and MAC OS X Terminal

You may also want to look at rsync if you're doing a lot of files.

If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion

Can MySQL convert a stored UTC time to local timezone?

I propose to use

SET time_zone = 'proper timezone';

being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.

Reverting to a specific commit based on commit id with Git?

I think, bwawok's answer is wrong at some point:

if you do

git reset --soft c14809fa

It will make your local files changed to be like they were then, but leave your history etc. the same.

According to manual: git-reset, "git reset --soft"...

does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).

The command for bwawok's answer might be:

git checkout <commit>

You can use this to peek at old revision: How did my code look yesterday?

(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)

String Comparison in Java

Below Algo "compare two strings lexicographically"

  1. Input two strings string 1 and string 2.

  2. for (int i = 0; i < str1.length() && i < str2.length(); i ++)

    (Loop through each character of both strings comparing them until one of the string terminates):

    a. If unicode value of both the characters is same then continue;

    b. If unicode value of character of string 1 and unicode value of string 2 is different then return (str1[i]-str2[i])

  3. if length of string 1 is less than string2

    return str2[str1.length()]

    else

    return str1[str2.length()]

    // This method compares two strings lexicographically

    public static int compareCustom(String s1, String s2) {
        for (int i = 0; i < s1.length() && i< s2.length(); i++) {
            if(s1.charAt(i) == s2.charAt(i)){
                //System.out.println("Equal");
                continue;
            }
            else{
                return s1.charAt(i) - s2.charAt(i);
            }   
        }
        if(s1.length()<s2.length()){
            return s2.length() - s1.length();
        }
        else if(s1.length()>s2.length()){
            return s1.length()-s2.length();
        }
        else{
            return 0;
        }
    }
    

if two String are equal it will return 0 otherwise return Negative or positive value

Source : - Source

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *

We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.

PHP

<?php

$ext_url = $_POST['ext_url'];

echo file_get_contents($ext_url);

?>

JS

$.ajax({
    method: 'POST',
    url: 'getContentFromUrl.php', // link to your PHP file
    data: {
        // url where our server will send request which can't be done by AJAX
        'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
    },
    success: function(data) {
        // we can find any data on external url, cause we've got all page
        var $h1 = $(data).find('h1').html();

        $('h1').val($h1);
    },
    error:function() {
        console.log('Error');
    }
});

How it works:

  1. Your browser with the help of JS will send request to your server
  2. Your server will send request to any other server and get reply from another server (any website)
  3. Your server will send this reply to your JS

And we can make events onClick, put this event on some button. Hope this will help!

Best practices for styling HTML emails

Campaign Monitor have an excellent support matrix detailing what's supported and what isn't among various mail clients.

You can use a service like Litmus to view how an email appears across several clients and whether they get caught by filters, etc.

stop all instances of node.js server

you can try

killall node

you can also try

killall nodejs

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

You should include jquery.fileupload-process.js and jquery.fileupload-validate.js to make it work.

Then...

$(this).fileupload({
    // ...
    processfail: function (e, data) {
        data.files.forEach(function(file){
            if (file.error) {
                self.$errorMessage.html(file.error);
                return false;
            }
        });
    },
//...
}

processfail callback is launched after a validation fail.

How can I reconcile detached HEAD with master/origin?

In simple words, the detached HEAD state means you are not checked out to HEAD (or tip) of any branch.

Understand With an Example

A branch in most of the cases is sequence of multiple commits like:

Commit 1: master-->branch_HEAD(123be6a76168aca712aea16076e971c23835f8ca)

Commit 2: master-->123be6a76168aca712aea16076e971c23835f8ca-->branch_HEAD(100644a76168aca712aea16076e971c23835f8ca)

As you can see above in case of sequence of commits, your branch points to your latest commit. So in that case if you checkout to commit 123be6a76168aca712aea16076e971c23835f8ca then you would be in detached head state since HEAD of your branch points to 100644a76168aca712aea16076e971c23835f8ca and technically you are checked out at HEAD of no branch. Hence, you are in the detached HEAD state.

Theoretical Explanation

In this Blog it's clearly stating a Git repository is a tree-of-commits, with each commit pointing to its ancestor with each commit pointer is updated and these pointers to each branch are stored in the .git/refs sub-directories. Tags are stored in .git/refs/tags and branches are stored in .git/refs/heads. If you look at any of the files, you'll find each tag corresponds to a single file, with a 40-character commit hash and as explained above by @Chris Johnsen and @Yaroslav Nikitenko, you can check out these references.

Set disable attribute based on a condition for Html.TextBoxFor

One simple approach I have used is conditional rendering:

@(Model.ExpireDate == null ? 
  @Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) : 
  @Html.TextBoxFor(m => m.ExpireDate)
)

What's a good, free serial port monitor for reverse-engineering?

I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

Sql Server equivalent of a COUNTIF aggregate function

SELECT COALESCE(IF(myColumn = 1,COUNT(DISTINCT NumberColumn),NULL),0) column1,
COALESCE(CASE WHEN myColumn = 1 THEN COUNT(DISTINCT NumberColumn) ELSE NULL END,0) AS column2
FROM AD_CurrentView

bash: npm: command not found?

If you have already installed nodejs and still getting this error. npm: command not found..

run this

apt-get install -y npm

When do you use the "this" keyword?

You should not use "this" unless you absolutely must.

There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.

What do the terms "CPU bound" and "I/O bound" mean?

When your program is waiting for I/O (ie. a disk read/write or network read/write etc), the CPU is free to do other tasks even if your program is stopped. The speed of your program will mostly depend on how fast that IO can happen, and if you want to speed it up you will need to speed up the I/O.

If your program is running lots of program instructions and not waiting for I/O, then it is said to be CPU bound. Speeding up the CPU will make the program run faster.

In either case, the key to speeding up the program might not be to speed up the hardware, but to optimize the program to reduce the amount of IO or CPU it needs, or to have it do I/O while it also does CPU intensive stuff.

Minimum Hardware requirements for Android development

I use an i5 processor with 4Gb RAM. It works very well. I feel this is the minimum configuration required to run both eclipse and android avd simultaneously. Just an old processor with high RAM is not sufficient.

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

angular js unknown provider

Here's another possible scenario where you can see this error:

If you use Sublime Text 2 and the angular plugin, it will generate stubs like this

angular.module('utils', [])
.factory('utilFactory', [''
    function() {
        return {

        }
    }
]);

notice the empty ' ' as the first element of the array after the 'utilFactory' string. If you don't have any dependencies, remove that so it's like this:

angular.module('utils', [])
.factory('utilFactory', [
    function() {
        return {

        }
    }
]);

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.

That time it worked. So i see 3 possible reasons for it working the second time,

  • connecting the second time resolves the problem (after the ssh key was created the first time), or
  • perhaps trying to connect to a compute engine immediately after it was created could also cause a problem which resolves itself after a while, or
  • merely reading this post resolves the problem

I suspect the last is unlikely :)

Insert if not exists Oracle

This is an answer to the comment posted by erikkallen:

You don't need a temp table. If you only have a few rows, (SELECT 1 FROM dual UNION SELECT 2 FROM dual) will do. Why would your example give ORA-0001? Wouldn't merge take the update lock on the index key and not continue until Sess1 has either committed or rolled back? – erikkallen

Well, try it yourself and tell me whether you get the same error or not:

SESS1:

create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;

SESS2: insert into t1 values(2, 2);

SESS1:

MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);

SESS2: commit;

SESS1: ORA-00001

Associating enums with strings in C#

Try adding constants to a static class. You don't end up with a Type, but you will have readable, organised constants:

public static class GroupTypes {

    public const string TheGroup = "OEM";
    public const string TheOtherGroup = "CMB";

}