Programs & Examples On #Table valued parameters

Table-Valued Parameters is a feature introduced in SQL SERVER 2008. In earlier versions of SQL SERVER it is not possible to pass a table variable in stored procedure as a parameter, but in SQL SERVER 2008 we can use Table-Valued Parameter to send multiple rows of data to a stored procedure or a function without creating a temporary table or passing so many parameters.

How to pass table value parameters to stored procedure from .net code

Generic

   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
    {
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)
        {
            tbl.Rows.Add(selector.Invoke(item));

        }

        return tbl;

    }

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How to get Client location using Google Maps API v3?

I couldn't get the above code to work.

Google does a great explanation though here: http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation

Where they first use the W3C Geolocation method and then offer the Google.gears fallback method for older browsers.

The example is here:

http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

Histogram using gnuplot?

I have a little modification to Born2Smile's solution.

I know that doesn't make much sense, but you may want it just in case. If your data is integer and you need a float bin size (maybe for comparison with another set of data, or plot density in finer grid), you will need to add a random number between 0 and 1 inside floor. Otherwise, there will be spikes due to round up error. floor(x/width+0.5) will not do because it will create pattern that's not true to original data.

binwidth=0.3
bin(x,width)=width*floor(x/width+rand(0))

Display progress bar while doing some work in C#?

I have to throw the simplest answer out there. You could always just implement the progress bar and have no relationship to anything of actual progress. Just start filling the bar say 1% a second, or 10% a second whatever seems similar to your action and if it fills over to start again.

This will atleast give the user the appearance of processing and make them understand to wait instead of just clicking a button and seeing nothing happen then clicking it more.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

How can I align YouTube embedded video in the center in bootstrap

<center><div class="video">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div></center>

It seems to work, is this all you were asking for? I guess you could go about taking longer more involved routes, but this seemed simple enough.

How do I force make/GCC to show me the commands?

Library makefiles, which are generated by autotools (the ./configure you have to issue) often have a verbose option, so basically, using make VERBOSE=1 or make V=1 should give you the full commands.

But this depends on how the makefile was generated.

The -d option might help, but it will give you an extremely long output.

How to do one-liner if else statement?

Like user2680100 said, in Golang you can have the structure:

if <statement>; <evaluation> {
    [statements ...]
} else {
    [statements ...]
}

This is useful to shortcut some expressions that need error checking, or another kind of boolean checking, like:


var number int64
if v := os.Getenv("NUMBER"); v != "" {
   if number, err = strconv.ParseInt(v, 10, 64); err != nil {
       os.Exit(42)
   }
} else {
    os.Exit(1)
}

With this you can achieve something like (in C):

Sprite *buffer = get_sprite("foo.png");
Sprite *foo_sprite = (buffer != 0) ? buffer : donut_sprite

But is evident that this sugar in Golang have to be used with moderation, for me, personally, I like to use this sugar with max of one level of nesting, like:


var number int64
if v := os.Getenv("NUMBER"); v != "" {
    number, err = strconv.ParseInt(v, 10, 64)
    if err != nil {
        os.Exit(42)
    }
} else {
    os.Exit(1)
}

You can also implement ternary expressions with functions like func Ternary(b bool, a interface{}, b interface{}) { ... } but i don't like this approach, looks like a creation of a exception case in syntax, and creation of this "features", in my personal opinion, reduce the focus on that matters, that is algorithm and readability, but, the most important thing that makes me don't go for this way is that fact that this can bring a kind of overhead, and bring more cycles to in your program execution.

IIS: Idle Timeout vs Recycle

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

Check if two lists are equal

List<T> equality does not check them element-by-element. You can use LINQ's SequenceEqual method for that:

var a = ints1.SequenceEqual(ints2);

To ignore order, use SetEquals:

var a = new HashSet<int>(ints1).SetEquals(ints2);

This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:

var counts = ints1
    .GroupBy(v => v)
    .ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
    int c;
    if (counts.TryGetValue(n, out c)) {
        counts[n] = c-1;
    } else {
        ok = false;
        break;
    }
}
var res = ok && counts.Values.All(c => c == 0);

Finally, if you are fine with an O(N*LogN) solution, you can sort the two sequences, and compare them for equality using SequenceEqual.

Should Gemfile.lock be included in .gitignore?

The real problem happens when you are working on an open-source Rails app that needs to have a configurable database adapter. I'm developing the Rails 3 branch of Fat Free CRM. My preference is postgres, but we want the default database to be mysql2.

In this case, Gemfile.lock still needs be checked in with the default set of gems, but I need to ignore changes that I have made to it on my machine. To accomplish this, I run:

git update-index --assume-unchanged Gemfile.lock

and to reverse:

git update-index --no-assume-unchanged Gemfile.lock

It is also useful to include something like the following code in your Gemfile. This loads the appropriate database adapter gem, based on your database.yml.

# Loads the database adapter gem based on config/database.yml (Default: mysql2)
# -----------------------------------------------------------------------------
db_gems = {"mysql2"     => ["mysql2", ">= 0.2.6"],
           "postgresql" => ["pg",     ">= 0.9.0"],
           "sqlite3"    => ["sqlite3"]}
adapter = if File.exists?(db_config = File.join(File.dirname(__FILE__),"config","database.yml"))
  db = YAML.load_file(db_config)
  # Fetch the first configured adapter from config/database.yml
  (db["production"] || db["development"] || db["test"])["adapter"]
else
  "mysql2"
end
gem *db_gems[adapter]
# -----------------------------------------------------------------------------

I can't say if this is an established best practice or not, but it works well for me.

HTML button calling an MVC Controller and Action method

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

This should work for you.

One line if statement not working

For simplicity, If you need to default to some value if nil you can use:

@something.nil? = "No" || "Yes"

How can I color a UIImage in Swift?

Swift 4.

Use this extension to create a solid colored image

extension UIImage {   

    public func coloredImage(color: UIColor) -> UIImage? {
        return coloredImage(color: color, size: CGSize(width: 1, height: 1))
    }

    public func coloredImage(color: UIColor, size: CGSize) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(size, false, 0)

        color.setFill()
        UIRectFill(CGRect(origin: CGPoint(), size: size))

        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()

        return image
    }
}

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

How to take column-slices of dataframe in pandas

Here's how you could use different methods to do selective column slicing, including selective label based, index based and the selective ranges based column slicing.

In [37]: import pandas as pd    
In [38]: import numpy as np
In [43]: df = pd.DataFrame(np.random.rand(4,7), columns = list('abcdefg'))

In [44]: df
Out[44]: 
          a         b         c         d         e         f         g
0  0.409038  0.745497  0.890767  0.945890  0.014655  0.458070  0.786633
1  0.570642  0.181552  0.794599  0.036340  0.907011  0.655237  0.735268
2  0.568440  0.501638  0.186635  0.441445  0.703312  0.187447  0.604305
3  0.679125  0.642817  0.697628  0.391686  0.698381  0.936899  0.101806

In [45]: df.loc[:, ["a", "b", "c"]] ## label based selective column slicing 
Out[45]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

In [46]: df.loc[:, "a":"c"] ## label based column ranges slicing 
Out[46]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

In [47]: df.iloc[:, 0:3] ## index based column ranges slicing 
Out[47]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

### with 2 different column ranges, index based slicing: 
In [49]: df[df.columns[0:1].tolist() + df.columns[1:3].tolist()]
Out[49]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

Execute a file with arguments in Python shell

try this:

import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')

Note that when abc.py finishes, control will be returned to the calling program. Note too that abc.py can call quit() if indeed finished.

How to center a Window in Java?

The order of the calls is important:

first -

pack();

second -

setLocationRelativeTo(null);

Create SQL script that create database and tables

An excellent explanation can be found here: Generate script in SQL Server Management Studio

Courtesy Ali Issa Here's what you have to do:

  1. Right click the database (not the table) and select tasks --> generate scripts
  2. Next --> select the requested table/tables (from select specific database objects)
  3. Next --> click advanced --> types of data to script = schema and data

If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!

Check if textbox has empty value

if (inp.val().length > 0) {
    // do something
}

if you want anything more complicated, consider regex or use the validation plugin which takes care of this for you

Google Play on Android 4.0 emulator

Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk , Phonesky.apk)
from here.

Start your emulator:

emulator -avd VM_NAME_HERE -partition-size 500 -no-audio -no-boot-anim

Then use the following commands:

# Remount in rw mode.
# NOTE: more recent system.img files are ext4, not yaffs2
adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system

# Allow writing to app directory on system partition
adb shell chmod 777 /system/app

# Install following apk
adb push GoogleLoginService.apk /system/app/.
adb push GoogleServicesFramework.apk /system/app/.
adb push Phonesky.apk /system/app/. # Vending.apk in older versions
adb shell rm /system/app/SdkSetup*

Best way to read a large file into a byte array in C#?

Use the BufferedStream class in C# to improve performance. A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers improve read and write performance.

See the following for a code example and additional explanation: http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx

Parse JSON in TSQL

SQL server 2016 supports json data parsing using OPENJSON. You can use OPENJSON to map json data to rows and columns.

Your json Data

[
 { "id" : 2,"name": "John"},
 { "id" : 5,"name": "John"}
]

Here is how you can handle json in sql

//@pJson is json data passed from code.  

INSERT INTO YourTable (id, Name)
 SELECT id, name
 FROM OPENJSON(@pJson)
 WITH (id int,
       name nvarchar(max))

Here is a detailed article which covers this topic.

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

Calling a function every 60 seconds

There are 2 ways to call-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

above function will call on every 60 seconds.

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

What is the standard way to add N seconds to datetime.time in Python?

Old question, but I figured I'd throw in a function that handles timezones. The key parts are passing the datetime.time object's tzinfo attribute into combine, and then using timetz() instead of time() on the resulting dummy datetime. This answer partly inspired by the other answers here.

def add_timedelta_to_time(t, td):
    """Add a timedelta object to a time object using a dummy datetime.

    :param t: datetime.time object.
    :param td: datetime.timedelta object.

    :returns: datetime.time object, representing the result of t + td.

    NOTE: Using a gigantic td may result in an overflow. You've been
    warned.
    """
    # Create a dummy date object.
    dummy_date = date(year=100, month=1, day=1)

    # Combine the dummy date with the given time.
    dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)

    # Add the timedelta to the dummy datetime.
    new_datetime = dummy_datetime + td

    # Return the resulting time, including timezone information.
    return new_datetime.timetz()

And here's a really simple test case class (using built-in unittest):

import unittest
from datetime import datetime, timezone, timedelta, time

class AddTimedeltaToTimeTestCase(unittest.TestCase):
    """Test add_timedelta_to_time."""

    def test_wraps(self):
        t = time(hour=23, minute=59)
        td = timedelta(minutes=2)
        t_expected = time(hour=0, minute=1)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)

    def test_tz(self):
        t = time(hour=4, minute=16, tzinfo=timezone.utc)
        td = timedelta(hours=10, minutes=4)
        t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)


if __name__ == '__main__':
    unittest.main()

How to calculate the IP range when the IP address and the netmask is given?

I know this is an older question, but I found this nifty library on nuget that seems to do just the trick for me:

http://nuget.org/packages/TakeIo.NetworkAddress/

How to search for a part of a word with ElasticSearch

Using wilcards (*) prevent the calc of a score

Is there any way to install Composer globally on Windows?

An alternative variant (see Lusitanian answer) is to register .phar files as executable on your system, exemplary phar.reg file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.phar]
@="phar_auto_file"

[HKEY_CLASSES_ROOT\phar_auto_file\shell\open\command]
@="\"c:\\PROGRA~1\\php\\php.exe\" \"%1\" %*"

Just replace the path to php.exe to your PHP executable. You can then also extend the %PATHEXT% commandline variable with .PHAR which will allow you to type composer instead of composer.phar as long as composer.phar is inside the %Path%.

Split string into string array of single characters

Try this:

var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

Check for special characters in string

Check if a string contains at least one password special character:

For reference: ASCII Table -- Printable Characters

Special character ranges in the ASCII table are:

  • Space to /
  • : to @
  • [ to `
  • { to ~

Therefore, use this:

/[ -/:-@[-`{-~]/.test(string)

What is the default encoding of the JVM?

It's going to be locale-dependent. Different locale, different default encoding.

How to reset selected file with input tag file type in Angular 2?

template:

<input [(ngModel)]="componentField" type="file" (change)="fileChange($event)" placeholder="Upload file">

component:

fileChange(event) {
        alert(this.torrentFileValue);
        this.torrentFileValue = '';
    }
}

How to update values in a specific row in a Python Pandas DataFrame?

If you have one large dataframe and only a few update values I would use apply like this:

import pandas as pd

df = pd.DataFrame({'filename' :  ['test0.dat', 'test2.dat'], 
                                  'm': [12, 13], 'n' : [None, None]})

data = {'filename' :  'test2.dat', 'n':16}

def update_vals(row, data=data):
    if row.filename == data['filename']:
        row.n = data['n']
    return row

df.apply(update_vals, axis=1)

How can I break up this long line in Python?

Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code:

logger.info("Skipping {0} because it's thumbnail was "
  "already in our system as {1}.".format(line[indexes['url']],
  video.title))

Check if an element is present in a Bash array

Obvious caveats aside, if your array was actually like the one above, you could do

if [[ ${arr[*]} =~ d ]]
then
  do your thing
else
  do something
fi

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

String.format() to format double in java

Use DecimalFormat

 NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
 DecimalFormat decimalFormatter = (DecimalFormat) nf;
 decimalFormatter.applyPattern("#,###,###.##");
 String fString = decimalFormatter.format(myDouble);
 System.out.println(fString);

The imported project "C:\Microsoft.CSharp.targets" was not found

Sometimes the problem might be with hardcoded VS version in .csproj file. If you have in your csproj something like this:

[...]\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets"

You should check if the number is correct (the reason it's wrong can be the project was created with another version of Visual Studio). If it's wrong, replace it with your current version of build tools OR use the VS variable:

[...]\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets"

How do I set up HttpContent for my HttpClient PostAsync second parameter?

This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.

In summary, you can't directly set up an instance of HttpContent because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

Read url to string in few lines of java code

If you have the input stream (see Joe's answer) also consider ioutils.toString( inputstream ).

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString(java.io.InputStream)

How to initialize a nested struct?

Well, any specific reason to not make Proxy its own struct?

Anyway you have 2 options:

The proper way, simply move proxy to its own struct, for example:

type Configuration struct {
    Val string
    Proxy Proxy
}

type Proxy struct {
    Address string
    Port    string
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: Proxy{
            Address: "addr",
            Port:    "port",
        },
    }
    fmt.Println(c)
    fmt.Println(c.Proxy.Address)
}

The less proper and ugly way but still works:

c := &Configuration{
    Val: "test",
    Proxy: struct {
        Address string
        Port    string
    }{
        Address: "addr",
        Port:    "80",
    },
}

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}

Rails 3 migrations: Adding reference column?

Please note that you will most likely need an index on that column too.

class AddUserReferenceToTester < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
    add_index  :testers, :user_id
  end
end

How to interactively (visually) resolve conflicts in SourceTree / git

From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.

Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.

Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

How to "comment-out" (add comment) in a batch/cmd?

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

Find and replace entire mysql database

Short answer: You can't.

Long answer: You can use the INFORMATION_SCHEMA to get the table definitions and use this to generate the necessary UPDATE statements dynamically. For example you could start with this:

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_schema'

I'd try to avoid doing this though if at all possible.

Why do I have to "git push --set-upstream origin <branch>"?

TL;DR: git branch --set-upstream-to origin/solaris


The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.

If you do not have upstream for the current branch, however, Git changes its behavior on git push, and on other commands as well.

The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default which now defaults to simple. For several versions of Git before and after 2.0, every time you ran git push, Git would spew lots of noise trying to convince you to set push.default just to get git push to shut up.

You do not mention which version of Git you are running, nor whether you have configured push.default, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default to simple to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.

What is an upstream?

An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.

Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.

The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B or local like master). That is, if the current branch B has upstream U, git rev-parse U should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv, will show the upstream setting but mark it as "gone".

What good is an upstream?

If your push.default is set to simple or upstream, the upstream setting will make git push, used with no additional arguments, just work.

That's it—that's all it does for git push. But that's fairly significant, since git push is one of the places where a simple typo causes major headaches.

If your push.default is set to nothing, matching, or current, setting an upstream does nothing at all for git push.

(All of this assumes your Git version is at least 2.0.)

The upstream affects git fetch

If you run git fetch with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin.)

The upstream affects git merge and git rebase too

If you run git merge or git rebase with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.

The upstream affects git pull

You should never2 use git pull anyway, but if you do, git pull uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull does the same thing as git fetch—because it actually runs git fetch—and then does the same thing as git merge or git rebase, because it actually runs git merge or git rebase.

(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)

The upstream affects git status

This may actually be the most important. Once you have an upstream set, git status can report the difference between your current branch and its upstream, in terms of commits.

If, as is the normal case, you are on branch B with its upstream set to origin/B, and you run git status, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.

This is because git status runs:

  • git rev-list --count @{u}..HEAD: how many commits do you have on B that are not on origin/B?
  • git rev-list --count HEAD..@{u}: how many commits do you have on origin/B that are not on B?

Setting an upstream gives you all of these things.

How come master already has an upstream set?

When you first clone from some remote, using:

$ git clone git://some.host/path/to/repo.git

or similar, the last step Git does is, essentially, git checkout master. This checks out your local branch master—only you don't have a local branch master.

On the other hand, you do have a remote-tracking branch named origin/master, because you just cloned it.

Git guesses that you must have meant: "make me a new local master that points to the same commit as remote-tracking origin/master, and, while you're at it, set the upstream for master to origin/master."

This happens for every branch you git checkout that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.

But this doesn't work for new branches, i.e., branches with no remote-tracking branch yet.

If you create a new branch:

$ git checkout -b solaris

there is, as yet, no origin/solaris. Your local solaris cannot track remote-tracking branch origin/solaris because it does not exist.

When you first push the new branch:

$ git push origin solaris

that creates solaris on origin, and hence also creates origin/solaris in your own Git repository. But it's too late: you already have a local solaris that has no upstream.3

Shouldn't Git just set that, now, as the upstream automatically?

Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.

The fact is, it doesn't today, unless you use --set-upstream or -u during the git push. That's what the message is telling you.

You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris on origin, through an earlier push, and as your git branch output shows, you already have origin/solaris in your local repository.

You just don't have it set as the upstream for solaris.

To set it now, rather than during the first push, use git branch --set-upstream-to. The --set-upstream-to sub-command takes the name of any existing branch, such as origin/solaris, and sets the current branch's upstream to that other branch.

That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch, then look around, then run git merge or git rebase as appropriate, then make new commits and run git push, without a bunch of additional fussing-around.


1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".

2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch actually did, and they can then see what git merge or git rebase will do next.

3If you run your first git push as git push -u origin solaris—i.e., if you add the -u flag—Git will set origin/solaris as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to is easier, if you forgot.

4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.

C# DateTime.ParseExact

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);

How do I exclude Weekend days in a SQL Server query?

The answer depends on your server's week-start set up, so it's either

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)

if Sunday is the first day of the week for your server

or

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)

if Monday is the first day of the week for your server

Comment if you've got any questions :-)

How can I know if a process is running?

Maybe (probably) I am reading the question wrongly, but are you looking for the HasExited property that will tell you that the process represented by your Process object has exited (either normally or not).

If the process you have a reference to has a UI you can use the Responding property to determine if the UI is currently responding to user input or not.

You can also set EnableRaisingEvents and handle the Exited event (which is sent asychronously) or call WaitForExit() if you want to block.

What is the best way to parse html in C#?

I think @Erlend's use of HTMLDocument is the best way to go. However, I have also had good luck using this simple library:

SgmlReader

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

Variables declared outside function

When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global declaration.

When you access a variable in a function, its value is looked up using the LEGB scoping rules.


So, the first example

  x = 1
  def inc():
      x += 5
  inc()

produces an UnboundLocalError because Python determined x inside inc to be a local variable,

while accessing x works in your second example

 def inc():
    print x

because here, in accordance with the LEGB rule, Python looks for x in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

Make a phone call programmatically

Swift

if let url = NSURL(string: "tel://\(number)"), 
    UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

How to grab substring before a specified character jQuery or JavaScript

try this:

streetaddress.substring(0, streetaddress.indexOf(','));

How do I get the localhost name in PowerShell?

In PowerShell Core v6 (works on macOS, Linux and Windows):

[Environment]::MachineName

How do I update the GUI from another thread?

just use synchronization context of ui

using System.Threading;

// ...

public partial class MyForm : Form
{
    private readonly SynchronizationContext uiContext;

    public MyForm()
    {
        InitializeComponent();
        uiContext = SynchronizationContext.Current; // get ui thread context
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(() =>
            {// set ui thread context to new thread context                            
             // for operations with ui elements to be performed in proper thread
             SynchronizationContext
                 .SetSynchronizationContext(uiContext);
             label1.Text = "some text";
            });
        t.Start();
    }
}

Python 3: EOF when reading a line (Sublime Text 2 is angry)

I had the same problem. The problem with the Sublime Text's default console is that it does not support input.

To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.

There is an article that explains the solution in detail.

GitHub page for SublimeREPL

How to install pip for Python 3 on Mac OS X?

For a fresh new Mac, you need to follow below steps:-

  1. Make sure you have installed Xcode
  2. sudo easy_install pip
  3. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  4. brew doctor
  5. brew doctor
  6. brew install python3

And you are done, just type python3 on terminal and you will see python 3 installed.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I was getting the same the error inside a shared function, but it was only happening for some calls to this shared function. I eventually realized that one of classes calling the shared function wasn't wrapping it inside of a Unit of Work. Once I updated this classes functions with a Unit of Work everything worked as expected.

So just posting this for any future visitors who run into this same error, but for whom the accepted answer doesn't apply.

How to find char in string and get all the indexes?

Lev's answer is the one I'd use, however here's something based on your original code:

def find(str, ch):
    for i, ltr in enumerate(str):
        if ltr == ch:
            yield i

>>> list(find("ooottat", "o"))
[0, 1, 2]

How to scan multiple paths using the @ComponentScan annotation?

make sure you have added this dependency in your pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

How to check for a valid Base64 encoded string

I know you said you didn't want to catch an exception. But, because catching an exception is more reliable, I will go ahead and post this answer.

public static bool IsBase64(this string base64String) {
     // Credit: oybek https://stackoverflow.com/users/794764/oybek
     if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
        || base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
        return false;

     try{
         Convert.FromBase64String(base64String);
         return true;
     }
     catch(Exception exception){
     // Handle the exception
     }
     return false;
}

Update: I've updated the condition thanks to oybek to further improve reliability.

Split a string by a delimiter in python

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

React - uncaught TypeError: Cannot read property 'setState' of undefined

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

Regex, every non-alphanumeric character except white space or colon

If you mean "non-alphanumeric characters", try to use this:

var reg =/[^a-zA-Z0-9]/g      //[^abc]

Query Mongodb on month, day, year... of a datetime

You can use MongoDB_DataObject wrapper to perform such query like below:

$model = new MongoDB_DataObject('orders');

$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');

$model->find();

while ($model->fetch()) {
    var_dump($model);
}

OR, similarly, using direct query string:

$model = new MongoDB_DataObject();

$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');

while ($model->fetch()) {
    var_dump($model);
}

How do I seed a random class to avoid getting duplicate random values

A good seed initialisation can be done like this

Random rnd = new Random((int)DateTime.Now.Ticks);

The ticks will be unique and the cast into a int with probably a loose of value will be OK.

How to rename files and folder in Amazon S3?

Here's how you do it in .NET, using S3 .NET SDK:

var client = new Amazon.S3.AmazonS3Client(_credentials, _config);
client.CopyObject(oldBucketName, oldfilepath, newBucketName, newFilePath);
client.DeleteObject(oldBucketName, oldfilepath);

P.S. try to use use "Async" versions of the client methods where possible, even though I haven't done so for readability

Class file for com.google.android.gms.internal.zzaja not found

Use:

compile 'com.google.firebase:firebase-auth:11.0.4'

This works.

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I had this problem before, and the reason is very simple: Check your variables, if there were strings, so put it in quotes '$your_string_variable_here' ,, if it were numerical keep it without any quotes. for example, if I had these data: $name ( It will be string ) $phone_number ( It will be numerical ) So, it will be like that:

$query = "INSERT INTO users (name, phone) VALUES ('$name', $phone)"; Just like that and it will be fixed ^_^

How to fix .pch file missing on build?

In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.

AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.

I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.

I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.

Hoppefully this helps somebody.

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
    
    Task.Factory.ContinueWhenAll( 
       tasks,
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);
       }
    );
    

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
             {
             //...
             });
          },  
          TaskCreationOptions.AttachedToParent
    );
    
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

jQuery ui dialog change title after load-callback

I have found simpler solution:

$('#clickToCreate').live('click', function() {
     $('#yourDialogId')
         .dialog({
              title: "Set the title to Create"
         })
         .dialog('open'); 
});


$('#clickToEdit').live('click', function() {
     $('#yourDialogId')
         .dialog({
              title: "Set the title To Edit"
         })
         .dialog('open'); 
});

Hope that helps!

How can I truncate a double to only two decimal places in Java?

I have a slightly modified version of Mani's.

private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
    return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}

public static void main(String[] args) {
    System.out.println(truncateDecimal(0, 2));
    System.out.println(truncateDecimal(9.62, 2));
    System.out.println(truncateDecimal(9.621, 2));
    System.out.println(truncateDecimal(9.629, 2));
    System.out.println(truncateDecimal(9.625, 2));
    System.out.println(truncateDecimal(9.999, 2));
    System.out.println(truncateDecimal(3.545555555, 2));

    System.out.println(truncateDecimal(9.0, 2));
    System.out.println(truncateDecimal(-9.62, 2));
    System.out.println(truncateDecimal(-9.621, 2));
    System.out.println(truncateDecimal(-9.629, 2));
    System.out.println(truncateDecimal(-9.625, 2));
    System.out.println(truncateDecimal(-9.999, 2));
    System.out.println(truncateDecimal(-9.0, 2));
    System.out.println(truncateDecimal(-3.545555555, 2));

}

Output:

0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

"Comparison method violates its general contract!"

Just because this is what I got when I Googled this error, my problem was that I had

if (value < other.value)
  return -1;
else if (value >= other.value)
  return 1;
else
  return 0;

the value >= other.value should (obviously) actually be value > other.value so that you can actually return 0 with equal objects.

How to solve "Connection reset by peer: socket write error"?

The correct way to 'solve' it is to close the connection and forget about the client. The client has closed the connection while you where still writing to it, so he doesn't want to know you, so that's it, isn't it?

How to clone all remote branches in Git?

Just do this:

$ git clone git://example.com/myproject
$ cd myproject
$ git checkout branchxyz
Branch branchxyz set up to track remote branch branchxyz from origin.
Switched to a new branch 'branchxyz'
$ git pull
Already up-to-date.
$ git branch
* branchxyz
  master
$ git branch -a
* branchxyz
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/branchxyz
  remotes/origin/branch123

You see, 'git clone git://example.com/myprojectt' fetches everything, even the branches, you just have to checkout them, then your local branch will be created.

HTML Drag And Drop On Mobile Devices

For vue 3, there is https://github.com/SortableJS/vue.draggable.next

For vue 2, it's https://github.com/SortableJS/Vue.Draggable

The latter you can use like this:

<draggable v-model="myArray" group="people" @start="drag=true" @end="drag=false">
   <div v-for="element in myArray" :key="element.id">{{element.name}}</div>
</draggable>

These are based on sortable.js

Performing a query on a result from another query?

I don't know if you even need to wrap it. Won't this work?

SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms    ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' 
  AND date_add('2009-06-25', INTERVAL 4 DAY)
  AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);

If your goal is to return both result sets then you'll need to store it some place temporarily.

How to make an autocomplete address field with google maps api?

I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.

In Bash, how do I add a string after each line in a file?

I prefer echo. using pure bash:

cat file | while read line; do echo ${line}$string; done

How do I get into a Docker container's shell?

docker attach will let you connect to your Docker container, but this isn't really the same thing as ssh. If your container is running a webserver, for example, docker attach will probably connect you to the stdout of the web server process. It won't necessarily give you a shell.

The docker exec command is probably what you are looking for; this will let you run arbitrary commands inside an existing container. For example:

docker exec -it <mycontainer> bash

Of course, whatever command you are running must exist in the container filesystem.

In the above command <mycontainer> is the name or ID of the target container. It doesn't matter whether or not you're using docker compose; just run docker ps and use either the ID (a hexadecimal string displayed in the first column) or the name (displayed in the final column). E.g., given:

$ docker ps
d2d4a89aaee9        larsks/mini-httpd   "mini_httpd -d /cont   7 days ago          Up 7 days                               web                 

I can run:

$ docker exec -it web ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
18: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP 
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.3/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:3/64 scope link 
       valid_lft forever preferred_lft forever

I could accomplish the same thing by running:

$ docker exec -it d2d4a89aaee9 ip addr

Similarly, I could start a shell in the container;

$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$

How to remove extension from string (only real extension!)

You can set the length of the regular expression pattern by using the {x,y} operator. {3,4} would match if the preceeding pattern occurs 3 or 4 times.

But I don't think you really need it. What will you do with a file named "This.is"?

How do you use bcrypt for hashing passwords in PHP?

You can create a one-way hash with bcrypt using PHP's crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.

PHP - Crypt Function

How to set a tkinter window to a constant size

If you want a window as a whole to have a specific size, you can just give it the size you want with the geometry command. That's really all you need to do.

For example:

mw.geometry("500x500")

Though, you'll also want to make sure that the widgets inside the window resize properly, so change how you add the frame to this:

back.pack(fill="both", expand=True)

No server in Eclipse; trying to install Tomcat

The reason you might not be getting any results is because you might not be having the J2EE environment setup in your Eclipse IDE. Follow these steps to solve the problem.

  1. Goto Help -> Install new Software Select relevant dropdown entry {Oxygen - http://download.eclipse.org/releases/<?>} (or Similar option/version) in the "Work with" tab.

  2. Search for Web,XML,Java EE and OSGi Enterprise Development Check the boxes corresponding to,Eclipse Java EE Developer Tools JST Server Adapters JST Server Adapters Extensions Click next and accept the license agreement.

How to send password securely over HTTP?

You can use a challenge response scheme. Say the client and server both know a secret S. Then the server can be sure that the client knows the password (without giving it away) by:

  1. Server sends a random number, R, to client.
  2. Client sends H(R,S) back to the server (where H is a cryptographic hash function, like SHA-256)
  3. Server computes H(R,S) and compares it to the client's response. If they match, the server knows the client knows the password.

Edit:

There is an issue here with the freshness of R and the fact that HTTP is stateless. This can be handled by having the server create a secret, call it Q, that only the server knows. Then the protocol goes like this:

  1. Server generates random number R. It then sends to the client H(R,Q) (which cannot be forged by the client).
  2. Client sends R, H(R,Q), and computes H(R,S) and sends all of it back to the server (where H is a cryptographic hash function, like SHA-256)
  3. Server computes H(R,S) and compares it to the client's response. Then it takes R and computes (again) H(R,Q). If the client's version of H(R,Q) and H(R,S) match the server's re-computation, the server deems the client authenticated.

To note, since H(R,Q) cannot be forged by the client, H(R,Q) acts as a cookie (and could therefore be implemented actually as a cookie).

Another Edit:

The previous edit to the protocol is incorrect as anyone who has observed H(R,Q) seems to be able to replay it with the correct hash. The server has to remember which R's are no longer fresh. I'm CW'ing this answer so you guys can edit away at this and work out something good.

python how to pad numpy array with zeros

In case you need to add a fence of 1s to an array:

>>> mat = np.zeros((4,4), np.int32)
>>> mat
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
>>> mat[0,:] = mat[:,0] = mat[:,-1] =  mat[-1,:] = 1
>>> mat
array([[1, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 1]])

How to delete last character from a string using jQuery?

You can also try this in plain javascript

"1234".slice(0,-1)

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc

Git command to display HEAD commit id?

You can use this command

$ git rev-list HEAD

You can also use the head Unix command to show the latest n HEAD commits like

$ git rev-list HEAD | head - 2

Angular 2 Checkbox Two Way Data Binding

You must add name="selected" attribute to input element.

For example:

<div class="checkbox">
  <label>
    <input name="selected" [(ngModel)]="saveUsername.selected" type="checkbox">Save username
  </label>
</div>

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {

        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // Parse the file. 
        while (reader.Read()) ;

    }
    // Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

How can I check if an InputStream is empty without reading from it?

Based on the suggestion of using the PushbackInputStream, you'll find an exemple implementation here:

/**
 * @author Lorber Sebastien <i>([email protected])</i>
 */
public class NonEmptyInputStream extends FilterInputStream {

  /**
   * Once this stream has been created, do not consume the original InputStream 
   * because there will be one missing byte...
   * @param originalInputStream
   * @throws IOException
   * @throws EmptyInputStreamException
   */
  public NonEmptyInputStream(InputStream originalInputStream) throws IOException, EmptyInputStreamException {
    super( checkStreamIsNotEmpty(originalInputStream) );
  }


  /**
   * Permits to check the InputStream is empty or not
   * Please note that only the returned InputStream must be consummed.
   *
   * see:
   * http://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it
   *
   * @param inputStream
   * @return
   */
  private static InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException, EmptyInputStreamException {
    Preconditions.checkArgument(inputStream != null,"The InputStream is mandatory");
    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if ( b == -1 ) {
      throw new EmptyInputStreamException("No byte can be read from stream " + inputStream);
    }
    pushbackInputStream.unread(b);
    return pushbackInputStream;
  }

  public static class EmptyInputStreamException extends RuntimeException {
    public EmptyInputStreamException(String message) {
      super(message);
    }
  }

}

And here are some passing tests:

  @Test(expected = EmptyInputStreamException.class)
  public void test_check_empty_input_stream_raises_exception_for_empty_stream() throws IOException {
    InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
    new NonEmptyInputStream(emptyStream);
  }

  @Test
  public void test_check_empty_input_stream_ok_for_non_empty_stream_and_returned_stream_can_be_consummed_fully() throws IOException {
    String streamContent = "HELLooooô wörld";
    InputStream inputStream = IOUtils.toInputStream(streamContent, StandardCharsets.UTF_8);
    inputStream = new NonEmptyInputStream(inputStream);
    assertThat(IOUtils.toString(inputStream,StandardCharsets.UTF_8)).isEqualTo(streamContent);
  }

How can I display an RTSP video stream in a web page?

I know that this post is old but I was looking for something very similar the other day (view my IP cam's RTSP video feed on a simple html page without any fancy ActiveX plugins). Lucky me, I found a solution! It is based on ffmpeg, NodeJS, NGINX (not mandatory but useful) and Node Media Server.

The description in the link is detailed and easy to follow, but I still had some tweaks to deal with before I got it to work (regarding endpoints on the NodeJS server). I made an own question for it and got a good and working answer.

Call a child class method from a parent class object

NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

However.. you should be able to do it like:

void calculate(Person p) {
    ((Student)p).method();
}

a safe way would be:

void calculate(Person p) {
    if(p instanceof Student) ((Student)p).method();
}

Unable to set default python version to python3 in ubuntu

To change Python 3.6.8 as the default in Ubuntu 18.04 from Python 2.7 you can try the command line tool update-alternatives.

sudo update-alternatives --config python

If you get the error "no alternatives for python" then set up an alternative yourself with the following command:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2

Change the path /usr/bin/python3 to your desired python version accordingly.

The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.6.8 and as a result the /usr/bin/python3.6.8 was set as default python version automatically by update-alternatives command.

we can anytime switch between the above listed python alternative versions using below command and entering a selection number:

update-alternatives --config python

CSS center display inline block?

Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table

body {
    background: #bbb;
    text-align: center;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: inline-block;
    overflow: hidden;
}

GET and POST methods with the same Action name in the same Controller

Today I was checking some resources about the same question and I got an example very interesting.

It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:

@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}

The action:

[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}

By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.

When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.

The located assembly's manifest definition does not match the assembly reference

This can also occur if you are using both AssemblyInfo.cs with the AssemblyVersion tags and your .csproj file has with a different value. By either matching the AssemblyInfo or removing the section all together the problem goes away.

How to add a margin to a table row <tr>

I gave up and inserted a simple jQuery code as below. This will add a tr after every tr, if you have so many trs like me. Demo: https://jsfiddle.net/acf9sph6/

<table>
  <tbody>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
  </tbody>
</table>
<script>
$(function () {
       $("tr.my-tr").after('<tr class="tr-spacer"/>');
});
</script>
<style>
.tr-spacer
{
    height: 20px;
}
</style>

Node: log in a file instead of the console

Update 2013 - This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend Winston

Update Late 2013 - We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js https://gist.github.com/rtgibbons/7354879


Should be as simple as this.

var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
      , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });

// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

What is the difference between 'my' and 'our' in Perl?

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources:

How to decorate a class?

I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)

What you're thinking of is a metaclass. The __new__ function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.

Example:

def substitute_init(self, id, *args, **kwargs):
    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = substitute_init
        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.

How can I easily switch between PHP versions on Mac OSX?

Example: Let us switch from php 7.4 to 7.3

brew unlink [email protected]
brew install [email protected]
brew link [email protected]

If you get Warning: [email protected] is keg-only and must be linked with --force Then try with:

brew link [email protected] --force

How can I add 1 day to current date?

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);

How to round an image with Glide library?

You have to use CircularImageView to Display that type of Image...

You are using Glide library which used to load images..

Create One ClassFile in your Project and Load it in Imageview... and You will get Desired Result...

Try Following Code...

XML

 <com.yourpackage.CircularImageView
    android:id="@+id/imageview"
    android:layout_width="96dp"
    android:layout_height="96dp"
    app:border="true"
    app:border_width="3dp"
    app:border_color="@color/white"
    android:src="@drawable/image" />

CircularImageView.java

public class CircularImageView extends ImageView {
    private int borderWidth;
    private int canvasSize;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;

    public CircularImageView(final Context context) {
        this(context, null);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.circularImageViewStyle);
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        paintBorder.setAntiAlias(true);

        // load the styled attributes and set their properties
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);

        if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
            int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
            setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
            setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
        }

        if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
            addShadow();
    }

    public void setBorderWidth(int borderWidth) {
        this.borderWidth = borderWidth;
        this.requestLayout();
        this.invalidate();
    }

    public void setBorderColor(int borderColor) {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);
        this.invalidate();
    }

    public void addShadow() {
        setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
        // load the bitmap
        image = drawableToBitmap(getDrawable());

        // init shader
        if (image != null) {

            canvasSize = canvas.getWidth();
            if(canvas.getHeight()<canvasSize)
                canvasSize = canvas.getHeight();

            BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);

            // circleCenter is the x or y of the view's center
            // radius is the radius in pixels of the cirle to be drawn
            // paint contains the shader that will texture the shape
            int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // The parent has determined an exact size for the child.
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // The parent has not imposed any constraint on the child.
            result = canvasSize;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // Measure the text (beware: ascent is a negative number)
            result = canvasSize;
        }

        return (result + 2);
    }

    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

Note :

You can use

CircularImageView imgIcon = (CircularImageView)findViewById(R.id.imageview);

or

ImageView imgIcon = (ImageView)findViewById(R.id.imageview);

it wont affect your other libraries... dont have to change your code for downloading image or anything else... it simply can be defined using XML too..

White space showing up on right side of page when background image should extend full length of page

The problem is in the file :

style.css - line 721

#sub_footer {
    background: url("../images/exterior/sub_footer.png") repeat-x;
    background: -moz-linear-gradient(0% 100% 90deg,#102c40, #091925);
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#091925), to(#102c40));
    -moz-box-shadow: 3px 3px 4px #999999;
    -webkit-box-shadow: 3px 3px 4px #999999;
    box-shadow: 3px 3px 4px #999999;
    padding-top:10px;
    font-size:9px;
    min-height:40px;
}

remove the lines :

-moz-box-shadow: 3px 3px 4px #999999;
-webkit-box-shadow: 3px 3px 4px #999999;
box-shadow: 3px 3px 4px #999999; 

This basically gives a shadow gradient only to the footer. In Firefox, it is the first line that is causing the problem.

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

How to get the current taxonomy term ID (not the slug) in WordPress?

Just copy paste below code!

This will print your current taxonomy name and description(optional)

<?php 
   $tax = $wp_query->get_queried_object();
   echo ''. $tax->name . '';
   echo "<br>";
   echo ''. $tax->description .''; 
?>

LINQ equivalent of foreach for IEnumerable<T>

There is no ForEach extension for IEnumerable; only for List<T>. So you could do

items.ToList().ForEach(i => i.DoStuff());

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Close Form Button Event

Try This: Application.ExitThread();

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

Live Video Streaming with PHP

There are a lot of "off-the-shelf" 'servers' that will run in your environment. Most of these utilize the aforementioned Flex or Silverlight to implement the actual video itself but I'm pretty sure all will run under LAMP/PHP.

The challenges will picking the best software from everything that's available and getting your hosting-provider to let you stream video (it goes without saying that streaming is heavy on bandwidth).

Is there a way to automatically build the package.json file for Node.js projects

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save

or

npm install <pkg> --save-dev

...to install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

How to make html <select> element look like "disabled", but pass values?

<select id="test" name="sel">
  <option disabled>1</option>
  <option disabled>2</option>
</select>   

or you can use jQuery

$("#test option:not(:selected)").prop("disabled", true);

How to make git mark a deleted and a new file as a file move?

Here's a quick and dirty solution for one, or a few, renamed and modified files that are uncommitted.

Let's say the file was named foo and now it's named bar:

  1. Rename bar to a temp name:

    mv bar side
    
  2. Checkout foo:

    git checkout HEAD foo
    
  3. Rename foo to bar with Git:

    git mv foo bar
    
  4. Now rename your temporary file back to bar.

    mv side bar
    

This last step is what gets your changed content back into the file.

While this can work, if the moved file is too different in content from the original git will consider it more efficient to decide this is a new object. Let me demonstrate:

$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ git add README.md work.js # why are the changes unstaged, let's add them.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ git stash # what? let's go back a bit
Saved working directory and index state WIP on dir: f7a8685 update
HEAD is now at f7a8685 update
$ git status
On branch workit
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .idea/

nothing added to commit but untracked files present (use "git add" to track)
$ git stash pop
Removing README
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README
    modified:   work.js

Dropped refs/stash@{0} (1ebca3b02e454a400b9fb834ed473c912a00cd2f)
$ git add work.js
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README

$ git add README # hang on, I want it removed
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ mv README.md Rmd # Still? Try the answer I found.
$ git checkout README
error: pathspec 'README' did not match any file(s) known to git.
$ git checkout HEAD README # Ok the answer needed fixing.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README.md
    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ git mv README README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ mv Rmd README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ # actually that's half of what I wanted; \
  # and the js being modified twice? Git prefers it in this case.

std::enable_if to conditionally compile a member function

SFINAE only works if substitution in argument deduction of a template argument makes the construct ill-formed. There is no such substitution.

I thought of that too and tried to use std::is_same< T, int >::value and ! std::is_same< T, int >::value which gives the same result.

That's because when the class template is instantiated (which happens when you create an object of type Y<int> among other cases), it instantiates all its member declarations (not necessarily their definitions/bodies!). Among them are also its member templates. Note that T is known then, and !std::is_same< T, int >::value yields false. So it will create a class Y<int> which contains

class Y<int> {
    public:
        /* instantiated from
        template < typename = typename std::enable_if< 
          std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< true >::type >
        int foo();

        /* instantiated from

        template < typename = typename std::enable_if< 
          ! std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< false >::type >
        int foo();
};

The std::enable_if<false>::type accesses a non-existing type, so that declaration is ill-formed. And thus your program is invalid.

You need to make the member templates' enable_if depend on a parameter of the member template itself. Then the declarations are valid, because the whole type is still dependent. When you try to call one of them, argument deduction for their template arguments happen and SFINAE happens as expected. See this question and the corresponding answer on how to do that.

Professional jQuery based Combobox control?

An official jQuery UI ComboBox/Autocomplete component is in the making... (previously in beta for jQuery UI 1.5.x), see jQuery UI Wiki

UPDATE:

Autocomplete functionality is now a core feature of jQuery UI, see docs.

How to execute raw SQL in Flask-SQLAlchemy app

If you want to avoid tuples, another way is by calling the first, one or all methods:

query = db.engine.execute("SELECT * FROM blogs "
                           "WHERE id = 1 ")

assert query.first().name == "Welcome to my blog"

Parse JSON from HttpURLConnection object

This function will be used get the data from url in form of HttpResponse object.

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

Include Gson library and org.apache.http.util.EntityUtils;

How to show hidden divs on mouseover?

If the divs are hidden, they will never trigger the mouseover event.

You will have to listen to the event of some other unhidden element.

You can consider wrapping your hidden divs into container divs that remain visible, and then act on the mouseover event of these containers.

_x000D_
_x000D_
<div style="width: 80px; height: 20px; background-color: red;" _x000D_
        onmouseover="document.getElementById('div1').style.display = 'block';">_x000D_
   <div id="div1" style="display: none;">Text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You could also listen for the mouseout event if you want the div to disappear when the mouse leaves the container div:

onmouseout="document.getElementById('div1').style.display = 'none';"

Load jQuery with Javascript and use jQuery

The reason you are getting this error is that JavaScript is not waiting for the script to be loaded, so when you run

jQuery(document).ready(function(){...

there is not guarantee that the script is ready (and never will be).

This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.

var jQueryIsReady = function(){
    //Your JQuery code here
}

var checkJquery = function(){
    if(typeof jQuery === "undefined"){
        return false;
    }else{
        clearTimeout(interval);
        jQueryIsReady();
    }
}
var interval = setInterval(checkJquery,1000);

How to select different app.config for several build configurations

I have heard good things about SlowCheetah, but was unable to get it to work. I did the following: add am tag to each for a specific configuration.

Ex:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'UAT|AnyCPU'">
    <OutputPath>bin\UAT\</OutputPath>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AppConfig>App.UAT.config</AppConfig>
  </PropertyGroup>

How to find out whether a file is at its `eof`?

You can compare the returned value of fp.tell() before and after calling the read method. If they return the same value, fp is at eof.

Furthermore, I don't think your example code actually works. The read method to my knowledge never returns None, but it does return an empty string on eof.

SVN undo delete before commit

You could remove the folder and update the parent directory before committing:

rm -r some_dir

svn update some_dir_parent

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.

var n = 5;
for (int i = 0; i < n; i++)
{
    //Create label
    Label label = new Label();
    label.Text = String.Format("Label {0}", i);
    //Position label on screen
    label.Left = 10;
    label.Top = (i + 1) * 20;
    //Create textbox
    TextBox textBox = new TextBox();
    //Position textbox on screen
    textBox.Left = 120;
    textBox.Top = (i + 1) * 20;
    //Add controls to form
    this.Controls.Add(label);
    this.Controls.Add(textBox);
}

This will not only add them to the form but position them decently as well.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

I just wrote a crazy set of CSS for this that seems to work perfectly:

table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}
table td,
table th {
  border-right: 1px solid #CCC;
  border-top: 1px solid #CCC;
  padding: 3px 5px;
  vertical-align: top;
}
table td:first-child,
table th:first-child {
  border-left: 1px solid #CCC;
}
table tr:last-child td,
table tr:last-child th {
  border-bottom: 1px solid #CCC;
}
table thead + tbody tr:first-child td {
  border-top: 0;
}
table thead td,
table th {
  background: #EDEDED;
}

/* complicated rounded table corners! */
table thead:first-child tr:last-child td:first-child {
  border-bottom-left-radius: 0;
}
table thead:first-child tr:last-child td:last-child {
  border-bottom-right-radius: 0;
}
table thead + tbody tr:first-child td:first-child {
  border-top-left-radius: 0;
}
table thead + tbody tr:first-child td:last-child {
  border-top-right-radius: 0;
}
table tr:first-child td:first-child,
table thead tr:first-child td:first-child {
  border-top-left-radius: 5px;
}
table tr:first-child td:last-child,
table thead tr:first-child td:last-child {
  border-top-right-radius: 5px;
}
table tr:last-child td:first-child,
table thead:last-child tr:last-child td:first-child {
  border-bottom-left-radius: 5px;
}
table tr:last-child td:last-child,
table thead:last-child tr:last-child td:last-child {
  border-bottom-right-radius: 5px;
}

/* end complicated rounded table corners !*/

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

How to normalize a signal to zero mean and unit variance?

It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)

This should work:

%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)

%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)

Pure CSS scroll animation

You can do it with anchor tags using css3 :target pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example

Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.

How do I find the MySQL my.cnf location

Be aware that although mariadDB loads configuration details from the various my.cnf files as listed in the other answers here, it can also load them from other files with different names.

That means that if you make a change in one of the my.cnf files, it may get overwritten by another file of a different name. To make the change stick, you need to change it in the right (last loaded) config file - or, maybe, change it in all of them.

So how do you find all the config files that might be loaded? Instead of looking for my.cnf files, try running:

grep -r datadir /etc/mysql/

This will find all the places in which datadir is mentioned. In my case, it produces this answer:

/etc/mysql/mariadb.conf.d/50-server.cnf:datadir     = /var/lib/mysql 

When I edit that file (/etc/mysql/mariadb.conf.d/50-server.cnf) to change the value for datadir, it works, whereas changing it in my.cnf does not. So whatever option you are wanting to change, try looking for it this way.

How to find which views are using a certain table in SQL Server (2008)?

To find table dependencies you can use the sys.sql_expression_dependencies catalog view:

SELECT 
referencing_object_name = o.name, 
referencing_object_type_desc = o.type_desc, 
referenced_object_name = referenced_entity_name, 
referenced_object_type_desc =so1.type_desc 
FROM sys.sql_expression_dependencies sed 
INNER JOIN sys.views o ON sed.referencing_id = o.object_id 
LEFT OUTER JOIN sys.views so1 ON sed.referenced_id =so1.object_id 
WHERE referenced_entity_name = 'Person'  

You can also try out ApexSQL Search a free SSMS and VS add-in that also has the View Dependencies feature. The View Dependencies feature has the ability to visualize all SQL database objects’ relationships, including those between encrypted and system objects, SQL server 2012 specific objects, and objects stored in databases encrypted with Transparent Data Encryption (TDE)

Disclaimer: I work for ApexSQL as a Support Engineer

Eclipse: Java was started but returned error code=13

Like Vito mentions, this error occurs after Java updates as the path:

C:\ProgramData\Oracle\Java\javapath

is added to the Path environment variable, causing Eclipse to run using the wrong java version.

To fix the problem:

1) Right-click on Computer and choose Properties.

2) Click Advanced system settings

3) Click Environment Variables...

4) Find the Path variable in the System variables section.

5) Choose it and click Edit...

6) Find and delete the above mentioned path.

This fixed it for me. I should mention that I already have the path:

c:\Program Files\Java\jdk1.7.0_21\bin

in the Path variable, but the new path was added to the beginning of the Path variable and therefore resolution would use that path first.

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

What's the difference between @Component, @Repository & @Service annotations in Spring?

In order to simplify this illustration, let us consider technicality by use case, These annotations are used to be injected and as I said literally "Used to be injected" , that mean, if you know how to use Dependency Injection "DI" and you should, then you will always look for these annotations, and by annotating the classes with these Stereo Types, you are informing the DI container to scan them to be ready for Injection on other places, this is the practical target.

Now lets move to each one; first @Service, If you are building some logic for specific business case you need to separate that in a place which will contain your business logic, this service is normal Class or you can use it as interface if you want , and it is written like this

@Service
public class Doer {
   // Your logic 
}

// To use it in another class, suppose in Controller 
@Controller
public class XController {
 // You have to inject it like this 
 @Autowired 
 private Doer doer;
}

All are the same way when you inject them, @Repository it's an interface which apply the implementation for the Repository Pattern Repository design pattern, generally it's used when you are dealing with some data store or database, and you will find that, it contains multiple ready implementation for you to handle database operations; it can be CrudRepository, JpaRepository etc.

// For example
public interface DoerRepository implements JpaRepository<Long, XEntity> {}

Finally the @Component, this is the generic form for registered beans in Spring, that's spring is always looking for bean marked with @Component to be registered, then both @Service and @Repository are special cases of @Component, however the common use case for component is when you're making something purely technical not for covering direct business case! like formatting dates or handing special request serialization mechanism and so on.

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

Jersey client: How to add a list as query parameter

GET Request with JSON Query Param

package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientGET {

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

            String BASE_URI="http://vaquarkhan.net:8080/khanWeb";               
            Client client = Client.create();    
            WebResource webResource = client.resource(BASE_URI);

            ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

            /*if (response.getStatus() != 200) {
               throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
            }
*/
            String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
            //String output = response.getEntity(String.class);

            System.out.println("Output from Server .... \n");
            System.out.println(output);                         

        } catch (Exception e) {

            e.printStackTrace();    
        }    
    }    
}

Post Request :

package com.rest.jersey.jerseyclient;

import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClientPOST {

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

            KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");                      

            ClientConfig clientConfig = new DefaultClientConfig();

            clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

            Client client = Client.create(clientConfig);

               // final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
               // client.addFilter(authFilter);
               // client.addFilter(new LoggingFilter());

            //
            WebResource webResource = client
                    .resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");

              ClientResponse response = webResource.accept("application/json")
                .type("application/json").put(ClientResponse.class, khanDTOInput);


            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
            }

            String output = response.getEntity(String.class);

            System.out.println("Server response .... \n");
            System.out.println(output);

        } catch (Exception e) {

            e.printStackTrace();

        }    
    }    
}

Can I set text box to readonly when using Html.TextBoxFor?

Using the example of @Hunter, in the new { .. } part, add readonly = true, I think that will work.

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Check if multiple strings exist in another string

Just to add some diversity with regex:

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

or if your list is too long - any(re.findall(r'|'.join(a), str, re.IGNORECASE))

How to press back button in android programmatically?

Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

What is the difference between the kernel space and the user space?

Briefly : Kernel runs in Kernel Space, the kernel space has full access to all memory and resources, you can say the memory divide into two parts, part for kernel , and part for user own process, (user space) runs normal programs, user space cannot access directly to kernel space so it request from kernel to use resources. by syscall (predefined system call in glibc)

there is a statement that simplify the different "User Space is Just a test load for the Kernel " ...

To be very clear : processor architecture allow CPU to operate in two mode, Kernel Mode and User Mode, the Hardware instruction allow switching from one mode to the other.

memory can be marked as being part of user space or kernel space.

When CPU running in User Mode, the CPU can access only memory that is being in user space, while cpu attempts to access memory in Kernel space the result is a "hardware exception", when CPU running in Kernel mode, the CPU can access directly to both kernel space and user space ...

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

How to open the terminal in Atom?

In the Atom IDE:

  1. Open file>settings
  2. Click "+" (install)
  3. Search for a terminal package called "platformio-ide-terminal"
  4. Click "install".
  5. Press Crtl+` to toggle the terminal

Automapper missing type map configuration or unsupported mapping - Error

In my case, I had created the map, but was missing the ReverseMap function. Adding it got rid of the error.

      private static void RegisterServices(ContainerBuilder bldr)
      {
         var config = new MapperConfiguration(cfg =>
         {
            cfg.AddProfile(new CampMappingProfile());
         });
         ...
       }


      public CampMappingProfile()
      {
         CreateMap<Talk, TalkModel>().ReverseMap();
         ...
      }

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

urlencoded Forward slash is breaking URL

Here's my humble opinion. !!!! Don't !!!! change settings on the server to make your parameters work correctly. This is a time bomb waiting to happen someday when you change servers.

The best way I have found is to just convert the parameter to base 64 encoding. So in my case, I'm calling a php service from Angular and passing a parameter that could contain any value.

So my typescript code in the client looks like this:

    private encodeParameter(parm:string){
    if (!parm){
        return null;
    }
    return btoa(parm);
}

And to retrieve the parameter in php:

    $item_name = $request->getAttribute('item_name');
    $item_name = base64_decode($item_name); 

Pass variables to Ruby script via command line

Run this code on the command line and enter the value of N:

N  = gets; 1.step(N.to_i, 1) { |i| print "hello world\n" }

Converting Java objects to JSON with Jackson

I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.

I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here.

For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl

Choose the version your project needs. (Typically you can go with the latest stable build).

Once they are imported in to your project's libraries, add the following import lines to your code:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import org.codehaus.jackson.map.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";

ObjectMapper mapper = new ObjectMapper();

try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

The result should looks like this: {"firstName":"Sample","lastName":"User","email":"[email protected]"}

Creating and appending text to txt file in VB.NET

While I realize this is an older thread, I noticed the if block above is out of place with using:

Following is corrected:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim filePath As String =
      String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
    Using writer As New StreamWriter(filePath, True)
        If File.Exists(filePath) Then
            writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
        Else
            writer.WriteLine("Start Error Log for today")
        End If
    End Using
End Sub

Chrome says my extension's manifest file is missing or unreadable

Kindly check whether you have installed right version of ChromeDriver or not . In my case , installing correct version helped.

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

MySQL, Concatenate two columns

You can use the CONCAT function like this:

SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`

Update:

To get that result you can try this:

SET @rn := 0;

SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(@rn := @rn+1,3,'0'))
FROM `table`

Javascript AES encryption

In my searches for AES encryption i found this from some Standford students. Claims to be fastest out there. Supports CCM, OCB, GCM and Block encryption. http://crypto.stanford.edu/sjcl/

Where is body in a nodejs http.get response?

A portion of Coffee here:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

And compiled

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});

How to find server name of SQL Server Management Studio

Open up SQL Server Configuration Manager (search for it in the Start menu). Click on SQL Server Services. The instance name of SQL Server is in parenthesis inline with SQL Server service. If it says MSSQLSERVER, then it's the default instance. To connect to it in Management Studio, just type . (dot) OR (local) and click Connect. If the instance name is different, then use .\[instance name] to connect to it (for example if the instance name is SQL2008, connect to .\SQL2008).

Also make sure SQL Server and SQL Server Browser services are running, otherwise you won't be able to connect.

Edit:

Here's a screenshot of how it looks like on my machine. In this case, I have two instances installed: SQLExpress and SQL2008.

enter image description here

How do I view the SQL generated by the Entity Framework?

You can do the following in EF 4.1:

var result = from x in appEntities
             where x.id = 32
             select x;

System.Diagnostics.Trace.WriteLine(result .ToString());

That will give you the SQL that was generated.

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

How to start and stop/pause setInterval?

(function(){
    var i = 0;
    function stop(){
        clearTimeout(i);
    }

    function start(){
        i = setTimeout( timed, 1000 );
    }

    function timed(){
       document.getElementById("input").value++;
       start();
    }

    window.stop = stop;
    window.start = start;
})()

http://jsfiddle.net/TE3Z2/

Split a string by another string in C#

There is an overload of Split that takes strings.

"THExxQUICKxxBROWNxxFOX".Split(new [] { "xx" }, StringSplitOptions.None);

You can use either of these StringSplitOptions

  • None - The return value includes array elements that contain an empty string
  • RemoveEmptyEntries - The return value does not include array elements that contain an empty string

So if the string is "THExxQUICKxxxxBROWNxxFOX", StringSplitOptions.None will return an empty entry in the array for the "xxxx" part while StringSplitOptions.RemoveEmptyEntries will not.

Execute a terminal command from a Cocoa app

Custos Mortem said:

I'm surprised no one really got into blocking/non-blocking call issues

For blocking/non-blocking call issues regarding NSTask read below:

asynctask.m -- sample code that shows how to implement asynchronous stdin, stdout & stderr streams for processing data with NSTask

Source code of asynctask.m is available at GitHub.

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

ERROR 1044 (42000): Access denied for 'root' With All Privileges

First, Identify the user you are logged in as:

 select user();
 select current_user();

The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost in mysql.

Grant_priv to root@localhost. Here is how you can check.

mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host      | user             | password                                  | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root             | ***************************************** | N          | Y          |
| localhost | debian-sys-maint | ***************************************** | Y          | Y          |
| localhost | staging          | ***************************************** | N          | N          |
+-----------+------------------+-------------------------------------------+------------+------------+

You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';

I logged back in, it was fine.

How to run mvim (MacVim) from Terminal?

If you go the brew route, the best way to install would be:

brew install macvim --with-override-system-vim

That will provide mvim, vim, vi, view, etc. in /usr/local/bin (all symlinked to the copy in the Cellar). This also removes the need to create any aliases and also changes your vi, vim, etc. to all use the same Vim distribution as your MacVim.

Converting an integer to binary in C

You can use function this function to return char* with string representation of the integer:

   char* itob(int i) {
      static char bits[8] = {'0','0','0','0','0','0','0','0'};
      int bits_index = 7;
      while ( i > 0 ) {
         bits[bits_index--] = (i & 1) + '0';
         i = ( i >> 1);
      }
      return bits;
   }

It's not a perfect implementation, but if you test with a simple printf("%s", itob(170)), you'll get 01010101 as I recall 170 was. Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.

Adding a slide effect to bootstrap dropdown

Intro

As of the time of writing, the original answer is now 8 years old. Still I feel like there isn't yet a proper solution to the original question.

Bootstrap has gone a long way since then and is now at 4.5.2. This answer addresses this very version.

The problem with all other solutions so far

The issue with all the other answers is, that while they hook into show.bs.dropdown / hide.bs.dropdown, the follow-up events shown.bs.dropdown / hidden.bs.dropdown are either fired too early (animation still ongoing) or they don't fire at all because they were suppressed (e.preventDefault()).

A clean solution

Since the implementation of show() and hide() in Bootstraps Dropdown class share some similarities, I've grouped them together in toggleDropdownWithAnimation() when mimicing the original behaviour and added little QoL helper functions to showDropdownWithAnimation() and hideDropdownWithAnimation().
toggleDropdownWithAnimation() creates a shown.bs.dropdown / hidden.bs.dropdown event the same way Bootstrap does it. This event is then fired after the animation completed - just like you would expect.

/**
 * Toggle visibility of a dropdown with slideDown / slideUp animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {boolean} show Show (true) or hide (false) the dropdown menu.
 * @param {number} duration Duration of the animation in milliseconds
 */
function toggleDropdownWithAnimation($containerElement, show, duration = 300): void {
    // get the element that triggered the initial event
    const $toggleElement = $containerElement.find('.dropdown-toggle');
    // get the associated menu
    const $dropdownMenu = $containerElement.find('.dropdown-menu');
    // build jquery event for when the element has been completely shown
    const eventArgs = {relatedTarget: $toggleElement};
    const eventType = show ? 'shown' : 'hidden';
    const eventName = `${eventType}.bs.dropdown`;
    const jQueryEvent = $.Event(eventName, eventArgs);

    if (show) {
        // mimic bootstraps element manipulation
        $containerElement.addClass('show');
        $dropdownMenu.addClass('show');
        $toggleElement.attr('aria-expanded', 'true');
        // put focus on initial trigger element
        $toggleElement.trigger('focus');
        // start intended animation
        $dropdownMenu
            .stop() // stop any ongoing animation
            .hide() // hide element to fix initial state of element for slide down animation
            .slideDown(duration, () => {
            // fire 'shown' event
            $($toggleElement).trigger(jQueryEvent);
        });
    }
    else {
        // mimic bootstraps element manipulation
        $containerElement.removeClass('show');
        $dropdownMenu.removeClass('show');
        $toggleElement.attr('aria-expanded', 'false');
        // start intended animation
        $dropdownMenu
            .stop() // stop any ongoing animation
            .show() // show element to fix initial state of element for slide up animation
            .slideUp(duration, () => {

            // fire 'hidden' event
            $($toggleElement).trigger(jQueryEvent);
        });
    }
}

/**
 * Show a dropdown with slideDown animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {number} duration Duration of the animation in milliseconds
 */
function showDropdownWithAnimation($containerElement, duration = 300) {
    toggleDropdownWithAnimation($containerElement, true, duration);
}

/**
 * Hide a dropdown with a slideUp animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {number} duration Duration of the animation in milliseconds
 */
function hideDropdownWithAnimation($containerElement, duration = 300) {
    toggleDropdownWithAnimation($containerElement, false, duration);
}

Bind Event Listeners

Now that we have written proper callbacks for showing / hiding a dropdown with an animation, let's actually bind these to the correct events.

A common mistake I've seen a lot in other answers is binding event listeners to elements directly. While this works fine for DOM elements present at the time the event listener is registered, it does not bind to elements added later on.

That's why you are generally better off binding directly to the document:

$(function () {

    /* Hook into the show event of a bootstrap dropdown */
    $(document).on('show.bs.dropdown', '.dropdown', function (e) {
        // prevent bootstrap from executing their event listener
        e.preventDefault();
        
        showDropdownWithAnimation($(this));
    });

    /* Hook into the hide event of a bootstrap dropdown */
    $(document).on('hide.bs.dropdown', '.dropdown', function (e) {
        // prevent bootstrap from executing their event listener
        e.preventDefault();
          
        hideDropdownWithAnimation($(this));
    });

});

When would you use the Builder Pattern?

For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.

Could we use a factory instead? Yes

Why didn't we? Builder makes more sense I guess.

Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).

Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.

Generating UNIQUE Random Numbers within a range

This probably will solve your problem:

<?php print_r(array_rand(range(1,50), 5)); ?>