Programs & Examples On #Microsoft commerce server

0

What's the difference between SHA and AES encryption?

SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.

You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.

AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.

UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

Xcode Product -> Archive disabled

Change the active scheme Device from Simulator to Generic iOS Device

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

BULK INSERT with identity (auto-increment) column

Add an id column to the csv file and leave it blank:

id,Name,Address
,name1,addr test 1
,name2,addr test 2

Remove KEEPIDENTITY keyword from query:

BULK INSERT Employee  FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

The id identity field will be auto-incremented.

If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

If origin points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example

$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.

Pulling once from the new origin solves the problem:

$ git stash
$ git pull origin master
$ git stash pop

Git push rejected after feature branch rebase

The following works for me:

git push -f origin branch_name

and it does not remove any of my code.

But, if you want to avoid this then you can do the following:

git checkout master
git pull --rebase
git checkout -b new_branch_name

then you can cherry-pick all your commits to the new branch. git cherry-pick COMMIT ID and then push your new branch.

Bootstrap 4 card-deck with number of columns based on viewport

I got this to work by adding a min-width to the cards:

<div class="card mb-3" style="min-width: 18rem;">
  <p>Card content</p>
</div>

The cards don't go below this width, but still properly fill each row and have equal heights.

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

Reading and writing binary file

Here is implementation of standard C++ 14 using vectors and tuples to Read and Write Text,Binary and Hex files.

Snippet code :

try {
if (file_type == BINARY_FILE) {

    /*Open the stream in binary mode.*/
    std::ifstream bin_file(file_name, std::ios::binary);

    if (bin_file.good()) {
        /*Read Binary data using streambuffer iterators.*/
        std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
        vec_buf = v_buf;
        bin_file.close();
    }

    else {
        throw std::exception();
    }

}

else if (file_type == ASCII_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream ascii_file(file_name);
    string ascii_data;

    if (ascii_file.good()) {
        /*Read ASCII data using getline*/
        while (getline(ascii_file, ascii_data))
            str_buf += ascii_data + "\n";

        ascii_file.close();
    }
    else {
        throw std::exception();
    }
}

else if (file_type == HEX_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream hex_file(file_name);

    if (hex_file.good()) {
        /*Read Hex data using streambuffer iterators.*/
        std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
        string hex_str_buf(h_buf.begin(), h_buf.end());
        hex_buf = hex_str_buf;

        hex_file.close();
    }
    else {
        throw std::exception();
    }
}

}

Full Source code can be found here

Query EC2 tags from within instance

Install AWS CLI:

curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
sudo apt-get install unzip
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws

Get the tags for the current instance:

aws ec2 describe-tags --filters "Name=resource-id,Values=`ec2metadata --instance-id`"

Outputs:

{
    "Tags": [
        {
            "ResourceType": "instance", 
            "ResourceId": "i-6a7e559d", 
            "Value": "Webserver", 
            "Key": "Name"
        }
    ]
}

Use a bit of perl to extract the tags:

aws ec2 describe-tags --filters \
"Name=resource-id,Values=`ec2metadata --instance-id`" | \
perl -ne 'print "$1\n" if /\"Value\": \"(.*?)\"/'

Returns:

Webserver

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

CSS Circle with border

You forgot to set the width of the border! Change border: red; to border:1px solid red;

Here the full code to get the circle:

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

R Markdown - changing font size and font type in html output

To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

Add the following somewhere in this section.

body {
  font-size: 16px;
}

The font size above is 16 pt font. You can change the number to whatever you want.

How to 'bulk update' with Django?

Consider using django-bulk-update found here on GitHub.

Install: pip install django-bulk-update

Implement: (code taken directly from projects ReadMe file)

from bulk_update.helper import bulk_update

random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()

for person in people:
    r = random.randrange(4)
    person.name = random_names[r]

bulk_update(people)  # updates all columns using the default db

Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.

Required attribute on multiple checkboxes with the same name?

i had the same problem, my solution was apply the required attribute to all elements

<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>

when the user check one of the elements i remove the required attribute from all elements:

var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
    $checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');

$checkboxes.click(function() {

if($checkedCheckboxes.length) {
        $checkboxes.removeAttr('required');
    } else {
        $checkboxes.attr('required', 'required');
    }

 });

Clear MySQL query cache without restarting server

In my system (Ubuntu 12.04) I found RESET QUERY CACHE and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

and then reset the query cache in mysql client:

RESET QUERY CACHE;

Get the key corresponding to the minimum value within a dictionary

For the case where you have multiple minimal keys and want to keep it simple

def minimums(some_dict):
    positions = [] # output variable
    min_value = float("inf")
    for k, v in some_dict.items():
        if v == min_value:
            positions.append(k)
        if v < min_value:
            min_value = v
            positions = [] # output variable
            positions.append(k)

    return positions

minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})

['e', 'c']

In Gradle, is there a better way to get Environment Variables?

Well; this works as well:

home = "$System.env.HOME"

It's not clear what you're aiming for.

PHP, display image with Header()

Though weirdly named, you can use the getimagesize() function. This will also give you mime information:

Array
(
    [0] => 295 // width
    [1] => 295 // height
    [2] => 3 // http://php.net/manual/en/image.constants.php
    [3] => width="295" height="295" // width and height as attr's
    [bits] => 8
    [mime] => image/png
)

Exploring Docker container's file system

The most upvoted answer is working for me when the container is actually started, but when it isn't possible to run and you for example want to copy files from the container this has saved me before:

docker cp <container-name>:<path/inside/container> <path/on/host/>

Thanks to docker cp (link) you can copy directly from the container as it was any other part of your filesystem. For example, recovering all files inside a container:

mkdir /tmp/container_temp
docker cp example_container:/ /tmp/container_temp/

Note that you don't need to specify that you want to copy recursively.

How do I remove a property from a JavaScript object?

Another alternative is to use the Underscore.js library.

Note that _.pick() and _.omit() both return a copy of the object and don't directly modify the original object. Assigning the result to the original object should do the trick (not shown).

Reference: link _.pick(object, *keys)

Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys).

var myJSONObject = 
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

_.pick(myJSONObject, "ircEvent", "method");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};

Reference: link _.omit(object, *keys)

Return a copy of the object, filtered to omit the blacklisted keys (or array of keys).

var myJSONObject = 
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

_.omit(myJSONObject, "regex");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};

For arrays, _.filter() and _.reject() can be used in a similar manner.

How to find all trigger associated with a table with SQL Server?

You can do this simply with SSMS. Just go to your table name and expand the Triggers node to view a list of triggers associated with that table. Right click to modify your trigger. enter image description here

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

How to call a method with a separate thread in Java?

To achieve this with RxJava 2.x you can use:

Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();

The subscribeOn() method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io() which has a thread pool intended for I/O operations, and Schedulers.computation() which is intended for CPU intensive operations.

Check if a div does NOT exist with javascript

There's an even better solution. You don't even need to check if the element returns null. You can simply do this:

if (document.getElementById('elementId')) {
  console.log('exists')
}

That code will only log exists to console if the element actually exists in the DOM.

Could not load the Tomcat server configuration

I know it's been a while since this question was posted, but I was just getting this exact error, and I have a really simple solution that MIGHT work for some. All I did was double click on the folder 'Servers', which then allowed me to start the server with no error message. Sometimes the solution is right in front of your eyes. This might work for some people like me who go straight to google without trying fix the issue themselves!

Access maven properties defined in the pom

Maven already has a solution to do what you want:

Get MavenProject from just the POM.xml - pom parser?

btw: first hit at google search ;)

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.

"Prevent saving changes that require the table to be re-created" negative effects

The table is only dropped and re-created in cases where that's the only way SQL Server's Management Studio has been programmed to know how to do it.

There are certainly cases where it will do that when it doesn't need to, but there will also be cases where edits you make in Management Studio will not drop and re-create because it doesn't have to.

The problem is that enumerating all of the cases and determining which side of the line they fall on will be quite tedious.

This is why I like to use ALTER TABLE in a query window, instead of visual designers that hide what they're doing (and quite frankly have bugs) - I know exactly what is going to happen, and I can prepare for cases where the only possibility is to drop and re-create the table (which is some number less than how often SSMS will do that to you).

add controls vertically instead of horizontally using flow layout

JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
        e,g`enter code here`
        testPanel.add(nameLabel);
        testPanel.add(textName);
*/
testPanel.setVisible(true);

JavaScript post request like a form submit

No. You can't have the JavaScript post request like a form submit.

What you can have is a form in HTML, then submit it with the JavaScript. (as explained many times on this page).

You can create the HTML yourself, you don't need JavaScript to write the HTML. That would be silly if people suggested that.

<form id="ninja" action="http://example.com/" method="POST">
  <input id="donaldduck" type="hidden" name="q" value="a">
</form>

Your function would just configure the form the way you want it.

function postToURL(a,b,c){
   document.getElementById("ninja").action     = a;
   document.getElementById("donaldduck").name  = b;
   document.getElementById("donaldduck").value = c;
   document.getElementById("ninja").submit();
}

Then, use it like.

postToURL("http://example.com/","q","a");

But I would just leave out the function and just do.

document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();

Finally, the style decision goes in the ccs file.

#ninja{ 
  display:none;
}

Personally I think forms should be addressed by name but that is not important right now.

Showing an image from an array of images - Javascript

Here's your problem:

if(imgArray[i] == img)

You're comparing an array element to a DOM object.

Cannot find or open the PDB file in Visual Studio C++ 2010

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for. Go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically. Or you may just ignore these warnings if you don't need to see correct call stack in these modules.

How to write a foreach in SQL Server?

Suppose that the column PractitionerId is a unique, then you can use the following loop

DECLARE @PractitionerId int = 0
WHILE(1 = 1)
BEGIN
  SELECT @PractitionerId = MIN(PractitionerId)
  FROM dbo.Practitioner WHERE PractitionerId > @PractitionerId
  IF @PractitionerId IS NULL BREAK
  SELECT @PractitionerId
END

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

I forgot to select the column (or set/map the property to a column value):

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name };

Calling queryable.OrderBy("Id") will throw exception, even though DataModel has property Id defined.

The correct query is:

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name, Id = t.Id };

Calling constructors in c++ without new

Quite simply, both lines create the object on the stack, rather than on the heap as 'new' does. The second line actually involves a second call to a copy constructor, so it should be avoided (it also needs to be corrected as indicated in the comments). You should use the stack for small objects as much as possible since it is faster, however if your objects are going to survive for longer than the stack frame, then it's clearly the wrong choice.

Access an arbitrary element in a dictionary in Python

Subclassing dict is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]], otherwise access the dictionary as expected:

class mydict(dict):
    def __getitem__(self, value):
        if isinstance(value, int):
            return self.get(list(self)[value])
        else:
            return self.get(value)

d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
            'e': 'test', 'f': 'dictionary', 'g': 'testing'})

d[0]    # 'hello'
d[1]    # 'this'
d['c']  # 'is'

What is the correct syntax of ng-include?

You have to single quote your src string inside of the double quotes:

<div ng-include src="'views/sidepanel.html'"></div>

Source

Subversion ignoring "--password" and "--username" options

Look to your local svn repo and look into directory .svn . there is file: entries look into them and you'll see lines begins with: svn+ssh://

this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'

if you want to change this, te best way is completly refresh this repository. update/commit what you should for save work. then remove completly directory and last step is create this by svn co/checkout 'URI-for-main-repo' [optionally local directory for store]

you should select connection method to repo file:// svn+ssh:// http:// https:// or other described in documentation.

after that you use svn update/commit as usual.

this topic looks like out of topic. better you go to superuser pages.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

LINQ Aggregate algorithm explained

A short and essential definition might be this: Linq Aggregate extension method allows to declare a sort of recursive function applied on the elements of a list, the operands of whom are two: the elements in the order in which they are present into the list, one element at a time, and the result of the previous recursive iteration or nothing if not yet recursion.

In this way you can compute the factorial of numbers, or concatenate strings.

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

Is there a printf converter to print in binary format?

The combination of functions + macro at the end of this answer can help you.

Use it like that:

float float_var = 9.4;
SHOW_BITS(float_var);

Which will output: Variable 'float_var': 01000001 00010110 01100110 01100110

Note that it is very general and can work with pretty much any type. For instance:

struct {int a; float b; double c;} struct_var = {1,1.1,1.2};
SHOW_BITS(struct_var);

Which will output:

Variable `struct_var`: 00111111 11110011 00110011 00110011 00110011 00110011 00110011 00110011 00111111 10001100 11001100 11001101 00000000 00000000 00000000 00000001

Here's the code:

#define SHOW_BITS(a) ({ \
    printf("Variable `%s`: ", #a);\
    show_bits(&a, sizeof(a));\
})

void show_uchar(unsigned char a)
{
    for(int i = 7; i >= 0; i-= 1) 
        printf("%d", ((a >> i) & 1));
}

void show_bits(void* a, size_t s)
{
    unsigned char* p = (unsigned char*) a;
    for(int i = s-1; i >= 0 ; i -= 1) {
        show_uchar(p[i]);
        printf(" ");
    }
    printf("\n");
}

Moving Git repository content to another repository preserving history

Simplest approach if the code is already tracked by Git then set new repository as your "origin" to push to.

cd existing-project
git remote set-url origin https://clone-url.git
git push -u origin --all
git push origin --tags

Android - Using Custom Font

After trying most of the solutions described in this thread, I accidentally found Calligraphy (https://github.com/chrisjenx/Calligraphy) - a library by Christopher Jenkins that lets you easily add custom fonts to your app. The advantages of his lib comparing to approaches suggested here are:

  1. you don't have to introduce your own overriden TextView component, you use the built-in TextView
  2. you can easily include the library using gradle
  3. The library doesn't limit your choice of fonts; you just add your preferred ones to the assets dir
  4. you not only get custom text views — all the other text-based Android compontents will also be displayed using your custom font.

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android="http://schemas.android.com/apk/res/android" 

xmlns : is xml name space and the URL : "http://schemas.android.com/apk/res/android" is nothing but

XSD which is [XML schema definition] : which is used define rules for XML file .

Example :

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginBottom="4dp"
   android:hint="User Name"
  />
</LinearLayout> 

Let me explain What Kind of Rules ? .

  1. In above XML file we already define layout_width for our layout now IF you will define same attribute second time you will get an error .
  2. EditText is there but if you want add another EditText no problem .

Such Kind of Rules are define in XML XSD : "http://schemas.android.com/apk/res/android"

little bit late but I hope this helps you .

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

How to change the time format (12/24 hours) of an <input>?

It depends on the time format of the user's operating system when the web browser was launched.

So:

  • If your computer's system prefs are set to use a 24-hour clock, the browser will render the <input type="time"> element as --:-- (time range: 00:00–23:59).
  • If you change your computer's syst prefs to use 12-hour, the output won't change until you quit and relaunch the browser. Then it will change to --:-- -- (time range: 12:00 AM – 11:59 PM).

And (as of this writing), browser support is only about 75% (caniuse). Yay: Edge, Chrome, Opera, Android. Boo: IE, Firefox, Safari).

Open and write data to text file using Bash?

Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation

VAR=Test
vi FILE.txt <<EOFXX
i
#This is my var in text file
var = $VAR
#Thats end of text file
^[
ZZ
EOFXX

Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.

#This is my var in text file
var = Test
#Thats end of text file

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

DECLARE @dayNumber INT;
SET @dayNumber = DATEPART(DW, GETDATE());

--Sunday = 1, Saturday = 7.
IF(@dayNumber = 1 OR @dayNumber = 7) 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

This may generate wrong results, because the number produced by the weekday datepart depends on the value set by SET DATEFIRST. This sets the first day of the week. So another way is:

DECLARE @dayName VARCHAR(9);
SET @dayName = DATEName(DW, GETDATE());

IF(@dayName = 'Saturday' OR @dayName = 'Sunday') 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

How to get visitor's location (i.e. country) using geolocation?

you can't get city location by ip. here you can get country with jquery:

$.get("http://ip-api.com/json", function(response) {
console.log(response.country);}, "jsonp");

Test if a property is available on a dynamic variable

In my case, I needed to check for the existence of a method with a specific name, so I used an interface for that

var plugin = this.pluginFinder.GetPluginIfInstalled<IPlugin>(pluginName) as dynamic;
if (plugin != null && plugin is ICustomPluginAction)
{
    plugin.CustomPluginAction(action);
}

Also, interfaces can contain more than just methods:

Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.

From: Interfaces (C# Programming Guide)

Elegant and no need to trap exceptions or play with reflexion...

"This project is incompatible with the current version of Visual Studio"

I Resolved the issue by deleting the files in the below folder

%localappdata%\Microsoft\VisualStudio\12.0\ComponentModelCache

Source: https://forums.xamarin.com/discussion/70388/how-to-fix-incompatible-issue-after-visual-studio-2015-update-3

How do you parse and process HTML/XML in PHP?

XML_HTMLSax is rather stable - even if it's not maintained any more. Another option could be to pipe you HTML through Html Tidy and then parse it with standard XML tools.

How to generate .json file with PHP?

If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php

How to Set focus to first text input in a bootstrap modal after shown

try this code, it might work for you

$(this).find('input:text')[0].focus();

javascript popup alert on link click

Single line works just fine:

<a href="http://example.com/"
 onclick="return confirm('Please click on OK to continue.');">click me</a>

Adding another line with a different link on the same page works fine too:

<a href="http://stackoverflow.com/"
 onclick="return confirm('Click on another OK to continue.');">another link</a>

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

Auto Generate Database Diagram MySQL

In MySql Workbench (6.0) its possible generate one diagram based on tables created. For that you should access to the tools bar, press Model and forward Create Diagram from Catalog Objects and done!

How can I run a html file from terminal?

You could always use the Lynx terminal-based web browser, which can be got by running $ sudo apt-get install lynx.

With Lynx, I believe the file can then be viewed using lynx <filename>

Convert JSON string to array of JSON objects in Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

MySQL SELECT last few days?

You could use a combination of the UNIX_TIMESTAMP() function to do that.

SELECT ... FROM ... WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(thefield) < 259200

How to use the gecko executable with Selenium

It is important to remember that the driver(file) must have execution permission (linux chmod +x geckodriver).

To sum up:

  1. Download gecko driver
  2. Add execution permission
  3. Add system property:

    System.setProperty("webdriver.gecko.driver", "FILE PATH");

  4. Instantiate and use the class

    WebDriver driver = new FirefoxDriver();

  5. Do whatever you want

  6. Close the driver

    driver.close;

Equivalent of LIMIT for DB2

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
  FROM EMP
  ORDER BY SALARY DESC
  FETCH FIRST 20 ROWS ONLY;

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address
FROM ( 
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

Show/hide 'div' using JavaScript

<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

Largest and smallest number in an array

Why are you not using this?

int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
int max = array.Max();
int min = array.Min();

Is it possible to make abstract classes in Python?

Most Previous answers were correct but here is the answer and example for Python 3.7. Yes, you can create an abstract class and method. Just as a reminder sometimes a class should define a method which logically belongs to a class, but that class cannot specify how to implement the method. For example, in the below Parents and Babies classes they both eat but the implementation will be different for each because babies and parents eat a different kind of food and the number of times they eat is different. So, eat method subclasses overrides AbstractClass.eat.

from abc import ABC, abstractmethod

class AbstractClass(ABC):

    def __init__(self, value):
        self.value = value
        super().__init__()

    @abstractmethod
    def eat(self):
        pass

class Parents(AbstractClass):
    def eat(self):
        return "eat solid food "+ str(self.value) + " times each day"

class Babies(AbstractClass):
    def eat(self):
        return "Milk only "+ str(self.value) + " times or more each day"

food = 3    
mom = Parents(food)
print("moms ----------")
print(mom.eat())

infant = Babies(food)
print("infants ----------")
print(infant.eat())

OUTPUT:

moms ----------
eat solid food 3 times each day
infants ----------
Milk only 3 times or more each day

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

On Gradle 5.x I use:

wrapper {
    gradleVersion = '5.5.1'
}

Uncaught TypeError: Cannot set property 'onclick' of null

So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.

I assume it's because it makes sure there's something to reference, but I am not entirely sure.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

In which case do you use the JPA @JoinTable annotation?

EDIT 2017-04-29: As pointed to by some of the commenters, the JoinTable example does not need the mappedBy annotation attribute. In fact, recent versions of Hibernate refuse to start up by printing the following error:

org.hibernate.AnnotationException: 
   Associations marked as mappedBy must not define database mappings 
   like @JoinTable or @JoinColumn

Let's pretend that you have an entity named Project and another entity named Task and each project can have many tasks.

You can design the database schema for this scenario in two ways.

The first solution is to create a table named Project and another table named Task and add a foreign key column to the task table named project_id:

Project      Task
-------      ----
id           id
name         name
             project_id

This way, it will be possible to determine the project for each row in the task table. If you use this approach, in your entity classes you won't need a join table:

@Entity
public class Project {

   @OneToMany(mappedBy = "project")
   private Collection<Task> tasks;

}

@Entity
public class Task {

   @ManyToOne
   private Project project;

}

The other solution is to use a third table, e.g. Project_Tasks, and store the relationship between projects and tasks in that table:

Project      Task      Project_Tasks
-------      ----      -------------
id           id        project_id
name         name      task_id

The Project_Tasks table is called a "Join Table". To implement this second solution in JPA you need to use the @JoinTable annotation. For example, in order to implement a uni-directional one-to-many association, we can define our entities as such:

Project entity:

@Entity
public class Project {

    @Id
    @GeneratedValue
    private Long pid;

    private String name;

    @JoinTable
    @OneToMany
    private List<Task> tasks;

    public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }
}

Task entity:

@Entity
public class Task {

    @Id
    @GeneratedValue
    private Long tid;

    private String name;

    public Long getTid() {
        return tid;
    }

    public void setTid(Long tid) {
        this.tid = tid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This will create the following database structure:

ER Diagram 1

The @JoinTable annotation also lets you customize various aspects of the join table. For example, had we annotated the tasks property like this:

@JoinTable(
        name = "MY_JT",
        joinColumns = @JoinColumn(
                name = "PROJ_ID",
                referencedColumnName = "PID"
        ),
        inverseJoinColumns = @JoinColumn(
                name = "TASK_ID",
                referencedColumnName = "TID"
        )
)
@OneToMany
private List<Task> tasks;

The resulting database would have become:

ER Diagram 2

Finally, if you want to create a schema for a many-to-many association, using a join table is the only available solution.

Please initialize the log4j system properly. While running web service

You have to create your own log4j.properties in the classpath folder.

Convert Rows to columns using 'Pivot' in SQL Server

I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:

SELECT StoreID, 
    Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
    Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
    Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID

One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.

My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

JSON to string variable dump

something along this?

function dump(x, indent) {
    var indent = indent || '';
    var s = '';
    if (Array.isArray(x)) {
        s += '[';
        for (var i=0; i<x.length; i++) {
            s += dump(x[i], indent)
            if (i < x.length-1) s += ', ';
        }
        s +=']';
    } else if (x === null) {
      s = 'NULL';
    } else switch(typeof x) {
        case 'undefined':
            s += 'UNDEFINED';
            break;
        case 'object':
            s += "{ ";
            var first = true;
            for (var p in x) {
                if (!first) s += indent + '  ';
                s += p + ': ';
                s += dump(x[p], indent + '  ');
                s += "\n"
                first = false;
            }
            s += '}';
            break;
        case 'boolean':
            s += (x) ? 'TRUE' : 'FALSE';
            break;
        case 'number':
            s += x;
            break;
        case 'string':
            s += '"' + x + '"';
            break;
        case 'function':
            s += '<FUNCTION>';
            break;
        default:
            s += x;
            break;
    }
    return s;
}

DataGridView - Focus a specific cell

the problem with datagridview is that it select the first row automatically so you want to clear the selection by

grvPackingList.ClearSelection();
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;  

other wise it will not work

Angular ngClass and click event for toggling class

So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:

@Component(
    selector:'foo',
    template:`<a (click)="onClick()"
                         [class.selected]="wasClicked">Link</a>
    `)
export class MyComponent {
    wasClicked = false;

    onClick() {
        this.wasClicked= !this.wasClicked;
    }
}

How to remove specific substrings from a set of strings in Python?

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

.replace doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

Determine the number of NA values in a column

In the interests of completeness you can also use the useNA argument in table. For example table(df$col, useNA="always") will count all of non NA cases and the NA ones.

Find empty or NaN entry in Pandas Dataframe

I've resorted to

df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index

lately. That gets both null and empty-string cells in one go.

How to count no of lines in text file and store the value into a variable using batch script?

You can also mark with a wildcard symbol * to facilitate group files to count.

Z:\SQLData>find /c /v "" FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_*.txt

Result

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS01_V1.TXT: 2041

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIOST00_V1.TXT: 315938

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS00_V1.TXT: 0

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_CNTPTF00_V1.TXT: 277

how to get multiple checkbox value using jquery

Since u have the same class name against all check box, thus

   $(".ads_Checkbox") 

will give u all the checkboxes, and then you can iterate them using each loop like

$(".ads_Checkbox:checked").each(function(){
   alert($(this).val());
});

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

Laravel 4: Redirect to a given url

You can use different types of redirect method in laravel -

return redirect()->intended('http://heera.it');

OR

return redirect()->to('http://heera.it');

OR

use Illuminate\Support\Facades\Redirect;

return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));

OR

return redirect('/')->with(Auth::logout());

OR

return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

How to tell if a string is not defined in a Bash shell script

~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~> 

-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

Alternate word:

~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED

Default value:

~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED

Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

How to remove duplicate values from an array in PHP

<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];    
print_r(arr_unique($arr1));


function arr_unique($arr) {
  sort($arr);
  $curr = $arr[0];
  $uni_arr[] = $arr[0];
  for($i=0; $i<count($arr);$i++){
      if($curr != $arr[$i]) {
        $uni_arr[] = $arr[$i];
        $curr = $arr[$i];
      }
  }
  return $uni_arr;
}

Java: how do I check if a Date is within a certain range?

An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

How to show MessageBox on asp.net?

Message box is only defaultly available for windows form application.If you want to use the message box resource the you would have to use 'using system.windows.forms' to enable the message box for web forms mode.

Using Javascript in CSS

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.

HTC with IE

Use a CSS rule like so:

body {
  behavior:url(script.htc);
}

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

XBL with Firefox

Firefox supports a similar XML-script-executing hack, using XBL.

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>

All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

MySQL query String contains

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

How to execute a java .class from the command line

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were

S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class

My code contained the following line

System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());

First, I had to move to the classpath directory

cd /D "S:\Accessibility\tools\src\test\java"

Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.

set classpath=%classpath%;.;..\..\..\src\main\resources; 

Then, I had to run java using the classname.

java com.accessibility.HelloWorld 

Add CSS or JavaScript files to layout head from views or partial views

Update: basic example available at https://github.com/speier/mvcassetshelper

We are using the following implementation to add JS and CSS files into the layout page.

View or PartialView:

@{
    Html.Assets().Styles.Add("/Dashboard/Content/Dashboard.css");
    Html.Assets().Scripts.Add("/Dashboard/Scripts/Dashboard.js");
}

Layout page:

<head>
    @Html.Assets().Styles.Render()
</head>

<body>
    ...
    @Html.Assets().Scripts.Render()
</body>

HtmlHelper extension:

public static class HtmlHelperExtensions
{
    public static AssetsHelper Assets(this HtmlHelper htmlHelper)
    {
        return AssetsHelper.GetInstance(htmlHelper);
    }    
}

public class AssetsHelper 
{
    public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
    {
        var instanceKey = "AssetsHelperInstance";

        var context = htmlHelper.ViewContext.HttpContext;
        if (context == null) return null;

        var assetsHelper = (AssetsHelper)context.Items[instanceKey];

        if (assetsHelper == null)
            context.Items.Add(instanceKey, assetsHelper = new AssetsHelper());

        return assetsHelper;
    }

    public ItemRegistrar Styles { get; private set; }
    public ItemRegistrar Scripts { get; private set; }

    public AssetsHelper()
    {
        Styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat);
        Scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat);
    }
}

public class ItemRegistrar
{
    private readonly string _format;
    private readonly IList<string> _items;

    public ItemRegistrar(string format)
    {
        _format = format;
        _items = new List<string>();
    }

    public ItemRegistrar Add(string url)
    {
        if (!_items.Contains(url))
            _items.Add(url);

        return this;
    }

    public IHtmlString Render()
    {
        var sb = new StringBuilder();

        foreach (var item in _items)
        {
            var fmt = string.Format(_format, item);
            sb.AppendLine(fmt);
        }

        return new HtmlString(sb.ToString());
    }
}

public class ItemRegistrarFormatters
{
    public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
    public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
}

Android Camera Preview Stretched

Very important point here to understand , the SurfaceView size must be the same as the camera parameters size , it means they have the same aspect ratio then the Stretch effect will go off .

You have to get the correct supported camera preview size using params.getSupportedPreviewSizes() choose one of them and then change your SurfaceView and its holders to this size.

Android design support library for API 28 (P) not working

open file gradle.properties and add these two lines to it:

android.useAndroidX = true
android.enableJetifier = true

clean and build

how to change language for DataTable

You have to either create a language file and then set it using :

"oLanguage": {
  "sUrl": "media/language/your_file.txt"
}

Im not sure what server language you are using but something like this would work in PHP :

"oLanguage": {
  "sUrl": "media/language/custom_lang_<?php echo $language ?>.txt"
}

Where language matches the file name for a specific language.

or change individual settings :

"oLanguage": {
  "sLengthMenu": "Display _MENU_ records per page",
  "sZeroRecords": "Nothing found - sorry",
  "sInfo": "Showing _START_ to _END_ of _TOTAL_ records",
  "sInfoEmpty": "Showing 0 to 0 of 0 records",
  "sInfoFiltered": "(filtered from _MAX_ total records)"
}

For more details read this : http://datatables.net/plug-ins/i18n

React onClick and preventDefault() link refresh/redirect?

A nice and simple option that worked for me was:

<a href="javascript: false" onClick={this.handlerName}>Click Me</a>

Make a table fill the entire window

That is because, of course, there is no ACTUAL page height. Keep in mind that you scroll throughout the contents of a page vertically not horizontally, creating a limited width but unlimited height. What the selected answer did was to make the table take up the visible area and stay there no matter what(absolute positioning).So theoretically what you were trying to do was impossible

Select all occurrences of selected word in VSCode

If you want to do one by one then this is what you can do:

  1. Select a word
  2. Press ctrl + d (in windows).

This will help to select words one by one.

How to update parent's state in React?

I've used a top rated answer from this page many times, but while learning React, i've found a better way to do that, without binding and without inline function inside props.

Just look here:

class Parent extends React.Component {

  constructor() {
    super();
    this.state={
      someVar: value
    }
  }

  handleChange=(someValue)=>{
    this.setState({someVar: someValue})
  }

  render() {
    return <Child handler={this.handleChange} />
  }

}

export const Child = ({handler}) => {
  return <Button onClick={handler} />
}

The key is in an arrow function:

handleChange=(someValue)=>{
  this.setState({someVar: someValue})
}

You can read more here. Hope this will be useful for somebody =)

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

OnClick vs OnClientClick for an asp:CheckBox?

Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

Note: Ensure you don't set AutoEventWireup="false" in page header.

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub

git still shows files as modified after adding to .gitignore

if you have .idea/* already added in your .gitignore and if git rm -r --cached .idea/ command does not work (note: shows error-> fatal: pathspec '.idea/' did not match any files) try this

remove .idea file from your app run this command

rm -rf .idea

run git status now and check while running the app .idea folder will be created again but it will not be tracked

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

In my case I was getting the grey background and it turned out to be inclusion of a zoom value in the map options. Yup, makes no sense.

Check if a Windows service exists and delete in PowerShell

To delete multiple services in Powershell 5.0, since remove service does not exist in this version

Run the below command

Get-Service -Displayname "*ServiceName*" | ForEach-object{ cmd /c  sc delete $_.Name}

Pure CSS animation visibility with delay

You are correct in thinking that display is not animatable. It won't work, and you shouldn't bother including it in keyframe animations.

visibility is technically animatable, but in a round about way. You need to hold the property for as long as needed, then snap to the new value. visibility doesn't tween between keyframes, it just steps harshly.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  99% {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

If you want to fade, you use opacity. If you include a delay, you'll need visibility as well, to stop the user from interacting with the element while it's not visible.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  0% {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

Both examples use animation-fill-mode, which can hold an element's visual state after an animation ends.

Java JTextField with input hint

Take a look at this one: http://code.google.com/p/xswingx/

It is not very difficult to implement it by yourself, btw. A couple of listeners and custom renderer and voila.

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

Didn't seem to be a permission issue for me - tried giving the IIS_IUSRS account full control over everything in the web service, just to see if this was the cause. The fix turned out to be recreating the application hosting the web service (i.e. the actual '.svc') in IIS

I can't install intel HAXM

I faced this problem.I got the solution too.It will work.

Step 1: Go to your BIOS settings and check that INTERNET VIRTUAL TECHNOLOGY is Enabled or Disabled.

And make sure HYPER V is disabled. To disable it : a)Go to Control Panel b)Click on Programs(Uninstall a Program) c)Then click on Turn Windows features on or off , then look for HYPER-V and untick it. And Restart. If disabled then enable it.

Step 2: Try to install Intel HAXM now and restart. If It shows same problem again. go to Step 3.

Step 3: You have to disable Digitally Signed Enforcement. To disable it permanently you have to make sure that Secure Boot option is disabled in your system.

How to check ?

Answer is given in the following link. I found it in Internet.[Thanks whoever made that blog]

link : http://www.windowspasswordsrecovery.com/win8-tips/how-to-disable-uefi-secure-boot-in-windows-8-1-8.html

Step 4: Now restart again.

To disable driver signature enforcement permanently in Windows 10, you need to do the following:

1.Open an elevated command prompt instance.
2.Type/paste the following text:

     `bcdedit.exe /set nointegritychecks on`

or Windows 10

     `bcedit.exe -set loadoptions DISABLE_INTEGRITY_CHECKS`

Windows 10 disable driver signature enforcement

Restart Windows 10.

*If you somehow want to enable it again:

1.Type/paste the following text:

     `bcdedit.exe /set nointegritychecks off`

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

How to split a string and assign it to variables

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

SQL Server Regular expressions in T-SQL

In case anyone else is still looking at this question, http://www.sqlsharp.com/ is a free, easy way to add regular expression CLR functions into your database.

How to fix Terminal not loading ~/.bashrc on OS X Lion

I have the following in my ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Update: Incredibly frustrating, but the Google redirect of the maven.google.com repo seems to mess with loading the resources. If you instead set your repository to maven { url 'https://dl.google.com/dl/android/maven2' } the files will resolve. You can prove this out by attempting to get the fully qualified resource at https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.pom 3.0.0 Alpha

This is because currently the gradle:3.0.0-alpha1 is only being served via the new 'https://maven.google.com' repository, but the site currently 404s at that location otherwise, being a public directory, you'd see a tree listing of all the files available by simply navigating to that location in your browser. When they resolve their outage, your CI build should pass immediately.

How to hide Android soft keyboard on EditText

Simply Use EditText.setFocusable(false); in activity

or use in xml

android:focusable="false"

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

How can I read command line parameters from an R script?

Try library(getopt) ... if you want things to be nicer. For example:

spec <- matrix(c(
        'in'     , 'i', 1, "character", "file from fastq-stats -x (required)",
        'gc'     , 'g', 1, "character", "input gc content file (optional)",
        'out'    , 'o', 1, "character", "output filename (optional)",
        'help'   , 'h', 0, "logical",   "this help"
),ncol=5,byrow=T)

opt = getopt(spec);

if (!is.null(opt$help) || is.null(opt$in)) {
    cat(paste(getopt(spec, usage=T),"\n"));
    q();
}

How to get the file-path of the currently executing javascript code

The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.

/**
 * Current Script Path
 *
 * Get the dir path to the currently executing script file
 * which is always the last one in the scripts array with
 * an [src] attr
 */
var currentScriptPath = function () {

    var scripts = document.querySelectorAll( 'script[src]' );
    var currentScript = scripts[ scripts.length - 1 ].src;
    var currentScriptChunks = currentScript.split( '/' );
    var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];

    return currentScript.replace( currentScriptFile, '' );
}

This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.

Kotlin - How to correctly concatenate a String

There are various way to concatenate strings in kotlin Example -

a = "Hello" , b= "World"
  1. Using + operator a+b

  2. Using plus() operator

    a.plus(b)

Note - + is internally converted to .plus() method only

In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder

StringBuilder str = StringBuilder("Hello").append("World")

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

git pull fails "unable to resolve reference" "unable to update local ref"

Had the same msg but with a directory, got a failed msg on pull.

git --prone did not help me either. Turns out there was a file with the same name as a directory created remotely.

Had to go to .git\logs\refs\remotes\origin and erase the locale file - then pull again, all good.

Rails Active Record find(:all, :order => ) issue

Could be two things. First,

This code is deprecated:

Model.find(:all, :order => ...)

should be:

Model.order(...).all

Find is no longer supported with the :all, :order, and many other options.

Second, you might have had a default_scope that was enforcing some ordering before you called find on Show.

Hours of digging around on the internet led me to a few useful articles that explain the issue:

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

I'm too late to the party but thought this might help someone.

Visual Studio Post Build Event - Copy to Relative Directory Location

I think this is related, but I had a problem when building directly using msbuild command line (from a batch file) vs building from within VS.

Using something like the following:

<PostBuildEvent>
  MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
  start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
</PostBuildEvent>

(note: start XCOPY rather than XCOPY used to get around a permissions issue which prevented copying)

The macro $(SolutionDir) evaluated to ..\ when executing msbuild from a batchfile, which resulted in the XCOPY command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic to see the evaluated output.

Using the macro $(ProjectDir)..\ instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.

PNG transparency issue in IE8

My scenario:

  • I had a background image that had a 24bit alpha png that was set to an anchor link.
  • The anchor was being faded in on hover using Jquery.

eg.

a.button { background-image: url(this.png; }

I found that applying the mark-up provided by Dan Tello didn't work.

However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.

eg.

a.button span { background-image: url(this.png; }

What are file descriptors, explained in simple terms?

Addition to above all simplified responses.

If you are working with files in bash script, it's better to use file descriptor.

For example: If you want to read and write from/to the file "test.txt", use the file descriptor as show below:

FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor

# Reading from the file line by line using file descriptor
while read LINE; do
    echo "$LINE"
done <&5

# Writing to the file using descriptor
echo "Adding the date: `date`" >&5 
exec 5<&- # Closing a file descriptor

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Insert default value when parameter is null

The questioner needs to learn the difference between an empty value provided and null.

Others have posted the right basic answer: A provided value, including a null, is something and therefore it's used. Default ONLY provides a value when none is provided. But the real problem here is lack of understanding of the value of null.

.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Generic:

ALTER TABLE table_name 
DROP COLUMN column1,column2,column3;

E.g:

ALTER TABLE Student 
DROP COLUMN Name, Number, City;

How to remove item from array by value?

What you're after is filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

This will allow you to do the following:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

This was also noted in this thread somewhere else: https://stackoverflow.com/a/20827100/293492

Cannot set property 'innerHTML' of null

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.

In my case I had a missing close div as shown below

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM

How to preserve request url with nginx proxy_pass

for my auth server... this works. i like to have options for /auth for my own humanized readability... or also i have it configured by port/upstream for machine to machine.

.

at the beginning of conf

####################################################
upstream auth {
    server 127.0.0.1:9011 weight=1 fail_timeout=300s;
    keepalive 16;
  }

Inside my 443 server block

          if (-d $request_filename) {
          rewrite [^/]$ $scheme://$http_host$uri/ permanent;
      }

  location /auth {
          proxy_pass http://$http_host:9011;
          proxy_set_header Origin           http://$host;
          proxy_set_header Host             $http_host:9011;
          proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade          $http_upgrade;
          proxy_set_header Connection       $http_connection;
          proxy_http_version 1.1;
      }

At the bottom of conf

#####################################################################
#                                                                   #
#     Proxies for all the Other servers on other ports upstream     #
#                                                                   #
#####################################################################


#######################
#        Fusion       #
#######################

server {
    listen 9001 ssl;

#############  Lock it down  ################

# SSL certificate locations
    ssl_certificate /etc/letsencrypt/live/allineed.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/allineed.app/privkey.pem;

# Exclusions

    include snippets/exclusions.conf;

# Security

    include snippets/security.conf;
    include snippets/ssl.conf;

# Fastcgi cache rules

    include snippets/fastcgi-cache.conf;
    include snippets/limits.conf;
    include snippets/nginx-cloudflare.conf;

###########  Location upstream ##############

    location  ~ / {
        proxy_pass http://auth;
        proxy_set_header Origin           http://$host;
        proxy_set_header Host             $host:$server_port;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade          $http_upgrade;
        proxy_set_header Connection       $http_connection;
        proxy_http_version 1.1;
    }
        if (-d $request_filename) {
        rewrite [^/]$ $scheme://$http_host$uri/ permanent;
    }
}

Not Able To Debug App In Android Studio

In my case, Had to remove the proguard in debug Build Type by completely clearing the text file proguard-rules.pro and making minifyEnabled false in build.gradle file

  debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

How to open in default browser in C#

dotnet core throws an error if we use Process.Start(URL). The following code will work in dotnet core. You can add any browser instead of Chrome.

var processes = Process.GetProcessesByName("Chrome");
var path  = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path,  url);

Get individual query parameters from Uri

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

Hiding and Showing TabPages in tabControl

It looks easier for me to clear all TabPages add add those wished:

PropertyTabControl.TabPages.Clear();
        PropertyTabControl.TabPages.Add(AspectTabPage);
        PropertyTabControl.TabPages.Add(WerkstattTabPage);

or

PropertyTabControl.TabPages.Clear();
        PropertyTabControl.TabPages.Add(TerminTabPage);

How to add an image to the "drawable" folder in Android Studio?

Simplest way is to just drag and drop the image into the drawable folder. The important thing to keep in mind if you are using Android Studio 2.2.x version make sure you are in PROJECT VIEW else it will not allow to drag and drop the image.

enter image description here

How to keep onItemSelected from firing off on a newly instantiated Spinner?

The solution with a boolean flag or a counter didn't help me, 'cause during orientation change onItemSelected() calls "overflew" the flag or the counter.

I subclassed android.widget.Spinner and made tiny additions. The relevant parts are below. This solution worked for me.

private void setHandleOnItemSelected()
{
  final StackTraceElement [] elements = Thread.currentThread().getStackTrace();

  for (int index = 1; index < elements.length; index++)
  {
     handleOnItemSelected = elements[index].toString().indexOf("PerformClick") != -1; //$NON-NLS-1$

     if (handleOnItemSelected)
     {
        break;
     }
  }
}

@Override
public void setSelection(int position, boolean animate)
{
  super.setSelection(position, animate);

  setHandleOnItemSelected();
}

@Override
public void setSelection(int position)
{
  super.setSelection(position);

  setHandleOnItemSelected();
}

public boolean shouldHandleOnItemSelected()
{
  return handleOnItemSelected;
}

Total size of the contents of all the files in a directory

If you want the 'apparent size' (that is the number of bytes in each file), not size taken up by files on the disk, use the -b or --bytes option (if you got a Linux system with GNU coreutils):

% du -sbh <directory>

Is there a way to break a list into columns?

2021 - keep it simple, use CSS Grid

Lots of these answers are outdated, it's 2020 and we shouldn't be enabling people who are still using IE9. It's way more simple to just use CSS grid.

The code is very simple, and you can easily adjust how many columns there are using the grid-template-columns. See this and then play around with this fiddle to fit your needs.

_x000D_
_x000D_
.grid-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
_x000D_
<ul class="grid-list">
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ul>
_x000D_
_x000D_
_x000D_

The executable gets signed with invalid entitlements in Xcode

For those who have the same problem with Provisioning Profile Automatic in the targets Build Settings:

Be very careful when you edit your targets entitlements file! This might break the correspondence to the automatically generated provisioning profile, and you will get this error.

In my case, I had to use temporarily the iCloud production containers with debug builds. To do so, I inserted

<key>com.apple.developer.icloud-container-environment</key>
<string>Production</string>  

in the entitlements file and this worked!
To remind me that I had later to remove these lines, I further inserted simply the following comment:

<key>TODO</key>
<string>The entry below must be out commented or deleted to use the iCloud development environment.</string>  

And this broke the correspondence, and created the error.

How to parse an RSS feed using JavaScript?

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

Creating a UICollectionView programmatically

Swift 3

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let flowLayout = UICollectionViewFlowLayout()

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan

        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.green
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

}

How to generate a random integer number from within a range

Here is a slight simpler algorithm than Ryan Reich's solution:

/// Begin and end are *inclusive*; => [begin, end]
uint32_t getRandInterval(uint32_t begin, uint32_t end) {
    uint32_t range = (end - begin) + 1;
    uint32_t limit = ((uint64_t)RAND_MAX + 1) - (((uint64_t)RAND_MAX + 1) % range);

    /* Imagine range-sized buckets all in a row, then fire randomly towards
     * the buckets until you land in one of them. All buckets are equally
     * likely. If you land off the end of the line of buckets, try again. */
    uint32_t randVal = rand();
    while (randVal >= limit) randVal = rand();

    /// Return the position you hit in the bucket + begin as random number
    return (randVal % range) + begin;
}

Example (RAND_MAX := 16, begin := 2, end := 7)
    => range := 6  (1 + end - begin)
    => limit := 12 (RAND_MAX + 1) - ((RAND_MAX + 1) % range)

The limit is always a multiple of the range,
so we can split it into range-sized buckets:
    Possible-rand-output: 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
    Buckets:             [0, 1, 2, 3, 4, 5][0, 1, 2, 3, 4, 5][X, X, X, X, X]
    Buckets + begin:     [2, 3, 4, 5, 6, 7][2, 3, 4, 5, 6, 7][X, X, X, X, X]

1st call to rand() => 13
    ? 13 is not in the bucket-range anymore (>= limit), while-condition is true
        ? retry...
2nd call to rand() => 7
    ? 7 is in the bucket-range (< limit), while-condition is false
        ? Get the corresponding bucket-value 1 (randVal % range) and add begin
    => 3

How to set "value" to input web element using selenium?

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

OR using JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

symbol(s) not found for architecture i386

In a C++ project using a defined templatized class, while receiving the same error, I selected .cpp file with the defined templatized class in the Project Navigator, then Delete > Remove Reference. Also the associated .h file, while still referenced in the project, needs to have a #include statement to the .cpp as follows:

#ifndef __CircularBuffer__CircularBufferT__
#define __CircularBuffer__CircularBufferT__

... snip ...

#include "CircularBufferT.cpp"
#endif /* defined(__CircularBuffer__CircularBufferT__) */

If you want to see, a simple project example is on github:

This is a little bit of indirection trickery and I don't recall the original source of this workaround.

How do I cancel an HTTP fetch() request?

https://developers.google.com/web/updates/2017/09/abortable-fetch

https://dom.spec.whatwg.org/#aborting-ongoing-activities

// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;

// fetch as usual
fetch(url, { signal }).then(response => {
  ...
}).catch(e => {
  // catch the abort if you like
  if (e.name === 'AbortError') {
    ...
  }
});

// when you want to abort
controller.abort();

works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.


on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:

import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'

// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch

How to use PrintWriter and File classes in Java?

Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as

PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");

all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as

import java.io.*;
public class PrintWriterClass {

public static void main(String arg[]) throws IOException{
    PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
    pw.println("hiiiiiii");
    pw.close();
}   

}

TypeError: module.__init__() takes at most 2 arguments (3 given)

In my case where I had the problem I was referring to a module when I tried extending the class.

import logging
class UserdefinedLogging(logging):

If you look at the Documentation Info, you'll see "logging" displayed as module.

In this specific case I had to simply inherit the logging module to create an extra class for the logging.

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

How to enumerate a range of numbers starting at 1

h = [(i + 1, x) for i, x in enumerate(xrange(2000, 2005))]

CSS text-align: center; is not centering things

If you want the text within the list items to be centred, try:

ul#menu-utility-navigation {
  width: 100%;
}

ul#menu-utility-navigation li {
  text-align: center;
}

bash "if [ false ];" returns true instead of false -- why?

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

How can I check if a string is null or empty in PowerShell?

# cases
$x = null
$x = ''
$x = ' '

# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}

How to fix "The ConnectionString property has not been initialized"

I found that when I create Sqlconnection = new SqlConnection(), I forgot to pass my connectionString variable. So that is why I changed the way I initialize my connectionString (and nothing changed).

And if you like me just don't forget to pass your string connection into SqlConnection parameters.

Sqlconnection = new SqlConnection("ConnString")

Simple GUI Java calculator

What you need is something that calculates the result of the infix notated calculation, have a look at the Shunting-Yard Algorithm.

There's an example in C++ on Wikipedia's page, but it shouldn't be too hard to implement it in Java.
And since it's the primary function of your calculator, I would advise you to not grab some codez from the Web in this Case (except all you want to do is building calculator GUIs).

How to get an Instagram Access Token

Link to oficial API documentation is http://instagram.com/developer/authentication/

Longstory short - two steps:

Get CODE

Open https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code with information from http://instagram.com/developer/clients/manage/

Get access token

curl \-F 'client_id=CLIENT-ID' \
    -F 'client_secret=CLIENT-SECRET' \
    -F 'grant_type=authorization_code' \
    -F 'redirect_uri=YOUR-REDIRECT-URI' \
    -F 'code=CODE' \
    https://api.instagram.com/oauth/access_token

Simplest way to download and unzip files in Node.js cross-platform?

yauzl is a robust library for unzipping. Design principles:

  • Follow the spec. Don't scan for local file headers. Read the central directory for file metadata.
  • Don't block the JavaScript thread. Use and provide async APIs.
  • Keep memory usage under control. Don't attempt to buffer entire files in RAM at once.
  • Never crash (if used properly). Don't let malformed zip files bring down client applications who are trying to catch errors.
  • Catch unsafe filenames entries. A zip file entry throws an error if its file name starts with "/" or /[A-Za-z]:// or if it contains ".." path segments or "\" (per the spec).

Currently has 97% test coverage.

How to find foreign key dependencies in SQL Server?

Because your question is geared towards a single table, you can use this:

EXEC sp_fkeys 'TableName'

I found it on SO here:

https://stackoverflow.com/a/12956348/652519

I found the information I needed pretty quickly. It lists the foreign key's table, column and name.

EDIT

Here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql

How can I check if a background image is loaded?

I've located a solution that worked better for me, and which has the advantage of being usable with several images (case not illustrated in this example).

From @adeneo's answer on this question :

If you have an element with a background image, like this

<div id="test" style="background-image: url(link/to/image.png)"><div>

You can wait for the background to load by getting the image URL and using it for an image object in javascript with an onload handler

var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

var img = new Image();
img.onload = function() {
    alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();

iPhone is not available. Please reconnect the device

Steps I used to fix it:

  1. Updated macOS to 10.15.5.
  2. Updated Xcode to 11.5

It still showed the same error so,

  1. I disconnected the iPhone and reconnected again.
  2. Removed Apple ID and added Apple ID again.

And it worked.

Using Page_Load and Page_PreRender in ASP.Net

The major difference between Page_Load and Page_PreRender is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load() methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender is your last chance to tweak the page before it turns into HTML stream.

Get a list of dates between two dates

select * from table_name where col_Date between '2011/02/25' AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))

Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.

output:
2011/02/25
2011/02/26
2011/02/27

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

Excel: the Incredible Shrinking and Expanding Controls

Now using Excel 2013 and this happens EVERY time I extend my display while Excel is running (and every time I remove the extension).

The fix I've started implementing is using hyperlinks instead of buttons and one to open a userform with all the other activeX controls on.

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

In Go's http package, how do I get the query string on a POST request?

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

How to search images from private 1.0 registry in docker?

Currently there's no search support for Docker Registry v2.

There was a long-running thread on the topic. The current plan is to support search with an extension in the end, which should be ready by v2.1.

As a workaround, execute the following on the machine where your registry v2 is running:

> docker exec -it <your_registry_container_id> bash
> ls /var/lib/registry/docker/registry/v2/repositories/

The images are in subdirectories corresponding to their namespace, e.g. jwilder/nginx-proxy

Set a form's action attribute when submitting?

<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />

Or you can modify it from outside the form, with javascript the normal way:

 document.getElementById('form_id').action = 'somethingelse';

Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here
    </div>

Read a zipped file as a pandas DataFrame

If you want to read a zipped or a tar.gz file into pandas dataframe, the read_csv methods includes this particular implementation.

df = pd.read_csv('filename.zip')

Or the long form:

df = pd.read_csv('filename.zip', compression='zip', header=0, sep=',', quotechar='"')

Description of the compression argument from the docs:

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.

New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.

OpenCV NoneType object has no attribute shape

I had this issue with cap = cv2.VideoCapture(0). I changed this to cap = cv2.VideoCapture(1) and then it worked. Since it wasn't linked to the right webcam it was returning nothing. Maybe this will help good luck.

Laravel: Get Object From Collection By Attribute

As from Laravel 5.5 you can use firstWhere()

In you case:

$green_foods = $foods->firstWhere('color', 'green');

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.