Programs & Examples On #Cidr

Classless Inter-Domain Routing, a method for allocating TCP/IP network addresses and routing data packets. Divides IP address into network id (high bits) and host id (low bits) as determined by netmask. In 1993, replaced the older classful network routing.

How can I check if an ip is in a network in Python?

From various sources above, and from my own research, this is how I got subnet and address calculation working. These pieces are enough to solve the question and other related questions.

class iptools:
    @staticmethod
    def dottedQuadToNum(ip):
        "convert decimal dotted quad string to long integer"
        return struct.unpack('>L', socket.inet_aton(ip))[0]

    @staticmethod
    def numToDottedQuad(n):
        "convert long int to dotted quad string"
        return socket.inet_ntoa(struct.pack('>L', n))

    @staticmethod
    def makeNetmask(mask):
        bits = 0
        for i in xrange(32-int(mask), 32):
            bits |= (1 << i)
        return bits

    @staticmethod
    def ipToNetAndHost(ip, maskbits):
        "returns tuple (network, host) dotted-quad addresses given"
        " IP and mask size"
        # (by Greg Jorgensen)
        n = iptools.dottedQuadToNum(ip)
        m = iptools.makeMask(maskbits)
        net = n & m
        host = n - mask
        return iptools.numToDottedQuad(net), iptools.numToDottedQuad(host)

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Centering the pagination in bootstrap

This this, it worked for me:

Style:

.pagination {
  display: flex;
  justify-content: center;
}

.pagination li {
  display: block;
 }

And blade:

<div class="pagination">                                              
  {{ $myCollection->render() }}
</div>

keycloak Invalid parameter: redirect_uri

You need to check the keycloak admin console for fronted configuration. It must be wrongly configured for redirect url and web origins.

ImportError: No module named 'bottle' - PyCharm

pycharm 2019.3 ,my solution is below: enter image description here

Token Authentication vs. Cookies

A typical web app is mostly stateless, because of its request/response nature. The HTTP protocol is the best example of a stateless protocol. But since most web apps need state, in order to hold the state between server and client, cookies are used such that the server can send a cookie in every response back to the client. This means the next request made from the client will include this cookie and will thus be recognized by the server. This way the server can maintain a session with the stateless client, knowing mostly everything about the app's state, but stored in the server. In this scenario at no moment does the client hold state, which is not how Ember.js works.

In Ember.js things are different. Ember.js makes the programmer's job easier because it holds indeed the state for you, in the client, knowing at every moment about its state without having to make a request to the server asking for state data.

However, holding state in the client can also sometimes introduce concurrency issues that are simply not present in stateless situations. Ember.js, however, deals also with these issues for you; specifically ember-data is built with this in mind. In conclusion, Ember.js is a framework designed for stateful clients.

Ember.js does not work like a typical stateless web app where the session, the state and the corresponding cookies are handled almost completely by the server. Ember.js holds its state completely in Javascript (in the client's memory, and not in the DOM like some other frameworks) and does not need the server to manage the session. This results in Ember.js being more versatile in many situations, e.g. when your app is in offline mode.

Obviously, for security reasons, it does need some kind of token or unique key to be sent to the server everytime a request is made in order to be authenticated. This way the server can look up the send token (which was initially issued by the server) and verify if it's valid before sending a response back to the client.

In my opinion, the main reason why to use an authentication token instead of cookies as stated in Ember Auth FAQ is primarily because of the nature of the Ember.js framework and also because it fits more with the stateful web app paradigm. Therefore the cookie mechanism is not the best approach when building an Ember.js app.

I hope my answer will give more meaning to your question.

Sample database for exercise

This is what I am using for learning sql: employees-db

this is a sample database with an integrated test suite, used to test your applications and database servers

3rd party edit

According to launchpad.net the database has moved to github.

The database contains about 300,000 employee records with 2.8 million salary entries. The export data is 167 MB, which is not huge, but heavy enough to be non-trivial for testing.

The data was generated, and as such there are inconsistencies and subtle problems. Rather than removing them, we decided to leave the contents untouched, and use these issues as data cleaning exercises.

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

Git error on git pull (unable to update local ref)

I had the same error, I was updating from within Eclipse and I got many errors. So I tried updating from a DOS command window, and got the same issue.

Then I tried the solution " git gc --prune=now " This gave messages that the files were locked in the refs directory.

Eclipse must have had a locked on something in the "refs" directory.
The solution I found was to simply close Eclipse. Then I updated the repository from DOS with a " git PULL " command, and everything worked fine.

Undoing a git rebase

I actually put a backup tag on the branch before I do any nontrivial operation (most rebases are trivial, but I'd do that if it looks anywhere complex).

Then, restoring is as easy as git reset --hard BACKUP.

Getting the document object of an iframe

Try the following

var doc=document.getElementById("frame").contentDocument;

// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;

Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.

Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy

fatal: git-write-tree: error building trees

To follow up on malat's response, you can avoid losing changes by creating a patch and reapply it at a later time.

git diff --no-prefix > patch.txt
patch -p0 < patch.txt

Store your patch outside the repository folder for safety.

Floating point inaccuracy examples

A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float and back to a double. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

Custom Cell Row Height setting in storyboard is not responding

One other thing you can do is to go to your Document Outline, select the table view that your prototype cell is nested. Then on the Size Inspector, change your table view Row Height to your desired value and uncheck the Automatic box.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode

For angular running under IIS on Windows

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode

For angular running under Node/Express

var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;

More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

PHP Regex to get youtube video ID?

The following will work for all youtube links

<?php
    // Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
    // http://youtu.be/dQw4w9WgXcQ
    // http://www.youtube.com/embed/dQw4w9WgXcQ
    // http://www.youtube.com/watch?v=dQw4w9WgXcQ
    // http://www.youtube.com/?v=dQw4w9WgXcQ
    // http://www.youtube.com/v/dQw4w9WgXcQ
    // http://www.youtube.com/e/dQw4w9WgXcQ
    // http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
    // http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
    // http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
    // http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
    // It also works on the youtube-nocookie.com URL with the same above options.
    // It will also pull the ID from the URL in an embed code (both iframe and object tags)

$url = "https://www.youtube.com/watch?v=v2_MLFVdlQM";

    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

    $youtube_id = $match[1];

echo $youtube_id;
    ?>

Styling of Select2 dropdown select boxes

Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:

$('b[role="presentation"]').hide();

I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:

$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');

Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:

.select2-container .select2-choice {
    padding: 5px 10px;
    height: 40px;
    width: 132px; 
    font-size: 1.2em;  
}

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
}

The result is the styling the way I want it:

screenshot

Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

JS:

$('b[role="presentation"]').hide();
$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');

Angular cli generate a service and include the provider in one step

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

Eclipse: All my projects disappeared from Project Explorer

File - Import - Existing projects into workspace - browse - choose your workspase - done!

Turning multi-line string into single comma-separated

This might work for you:

cut -d' ' -f5 file | paste -d',' -s
+12.0,+15.5,+9.0,+13.5

or

sed '/^.*\(+[^ ]*\).*/{s//\1/;H};${x;s/\n/,/g;s/.//p};d' file
+12.0,+15.5,+9.0,+13.5

or

sed 's/\S\+\s\+//;s/\s.*//;H;$!d;x;s/.//;s/\n/,/g' file

For each line in the file; chop off the first field and spaces following, chop off the remainder of the line following the second field and append to the hold space. Delete all lines except the last where we swap to the hold space and after deleting the introduced newline at the start, convert all newlines to ,'s.

N.B. Could be written:

sed 's/\S\+\s\+//;s/\s.*//;1h;1!H;$!d;x;s/\n/,/g' file

Replace whitespaces with tabs in linux

You can also use astyle. I found it quite useful and it has several options too:

Tab and Bracket Options:
   If  no  indentation  option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4.  If no brackets option is set, the
   brackets will not be changed.

   --indent=spaces, --indent=spaces=#, -s, -s#
          Indent using # spaces per indent. Between 1 to 20.  Not specifying # will result in a default of 4 spaces per indent.

   --indent=tab, --indent=tab=#, -t, -t#
          Indent using tab characters, assuming that each tab is # spaces long.  Between 1 and 20. Not specifying # will result in a default assumption  of
          4 spaces per tab.`

Where to find extensions installed folder for Google Chrome on Mac?

For Mac EI caption/Mac Sierra, Chrome extension folders were located at

/Users/$USER/Library/Application\ Support/Google/Chrome/Profile*/Extensions/

Android: Is it possible to display video thumbnails?

Currently I Use following code :

Bitmap bMap = ThumbnailUtils.createVideoThumbnail(file.getAbsolutePath(), MediaStore.Video.Thumbnails.MICRO_KIND);

But I found better solution with Glide library with following code ( It also cache your image and have better performance than previous approach )

Glide.with(context)
                .load(uri)
                .placeholder(R.drawable.ic_video_place_holder)
                .into(imageView);

File Upload ASP.NET MVC 3.0

In Controller

 if (MyModal.ImageFile != null)
                    {
                        MyModal.ImageURL = string.Format("{0}.{1}", Guid.NewGuid().ToString(), MyModal.ImageFile.FileName.Split('.').LastOrDefault());
                        if (MyModal.ImageFile != null)
                        {
                            var path = Path.Combine(Server.MapPath("~/Content/uploads/"), MyModal.ImageURL);
                            MyModal.ImageFile.SaveAs(path);
                        }
                    }

In View

<input type="hidden" value="" name="..."><input id="ImageFile" type="file" name="ImageFile" src="@Model.ImageURL">

In Modal Class

 public HttpPostedFileBase ImageFile { get; set; }

Create a folder as uploads in Content folder in project

What is the difference between a 'closure' and a 'lambda'?

From the view of programming languages, they are completely two different things.

Basically for a Turing complete language we only needs very limited elements, e.g. abstraction, application and reduction. Abstraction and application provides the way you can build up lamdba expression, and reduction dertermines the meaning of the lambda expression.

Lambda provides a way you can abstract the computation process out. for example, to compute the sum of two numbers, a process which takes two parameters x, y and returns x+y can be abstracted out. In scheme, you can write it as

(lambda (x y) (+ x y))

You can rename the parameters, but the task that it completes doesn't change. In almost all of programming languages, you can give the lambda expression a name, which are named functions. But there is no much difference, they can be conceptually considered as just syntax sugar.

OK, now imagine how this can be implemented. Whenever we apply the lambda expression to some expressions, e.g.

((lambda (x y) (+ x y)) 2 3)

We can simply substitute the parameters with the expression to be evaluated. This model is already very powerful. But this model doesn't enable us to change the values of symbols, e.g. We can't mimic the change of status. Thus we need a more complex model. To make it short, whenever we want to calculate the meaning of the lambda expression, we put the pair of symbol and the corresponding value into an environment(or table). Then the rest (+ x y) is evaluated by looking up the corresponding symbols in the table. Now if we provide some primitives to operate on the environment directly, we can model the changes of status!

With this background, check this function:

(lambda (x y) (+ x y z))

We know that when we evaluate the lambda expression, x y will be bound in a new table. But how and where can we look z up? Actually z is called a free variable. There must be an outer an environment which contains z. Otherwise the meaning of the expression can't be determined by only binding x and y. To make this clear, you can write something as follows in scheme:

((lambda (z) (lambda (x y) (+ x y z))) 1)

So z would be bound to 1 in an outer table. We still get a function which accepts two parameters but the real meaning of it also depends on the outer environment. In other words the outer environment closes on the free variables. With the help of set!, we can make the function stateful, i.e, it's not a function in the sense of maths. What it returns not only depends on the input, but z as well.

This is something you already know very well, a method of objects almost always relies on the state of objects. That's why some people say "closures are poor man's objects. " But we could also consider objects as poor man's closures since we really like first class functions.

I use scheme to illustrate the ideas due to that scheme is one of the earliest language which has real closures. All of the materials here are much better presented in SICP chapter 3.

To sum up, lambda and closure are really different concepts. A lambda is a function. A closure is a pair of lambda and the corresponding environment which closes the lambda.

How to center the text in PHPExcel merged cell

We can also set the vertical alignment with using this way

$style_cell = array(
   'alignment' => array(
       'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
       'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
   ) 
); 

with this cell set the vertically aligned into the middle.

how to use ng-option to set default value of select element

<select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
    <option value="">English(EN)</option>
    <option value="23">Corsican(CO)</option>
    <option value="43">French(FR)</option>
    <option value="16">German(GR)</option>

Just add option with empty value. It will work.

DEMO Plnkr

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Angular 4 Pipe Filter

I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
    transform(array: Array<Object>, filter: Object): any {
        let notAllKeysUndefined = false;
        let newArray = [];

        if(array.length > 0) {
            for (let k in filter){
                if (filter.hasOwnProperty(k)) {
                    if(filter[k] != undefined && filter[k] != '') {
                        for (let i = 0; i < array.length; i++) {
                            let filterRule = filter[k];

                            if(typeof filterRule === 'object') {
                                for(let fkey in filterRule) {
                                    if (filter[k].hasOwnProperty(fkey)) {
                                        if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
                                            if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
                                                newArray.push(array[i]);
                                            }
                                            notAllKeysUndefined = true;
                                        }
                                    }
                                }
                            } else {
                                if(this.shouldPushInArray(array[i][k], filter[k])) {
                                    newArray.push(array[i]);
                                }
                                notAllKeysUndefined = true;
                            }
                        }
                    }
                }
            }
            if(notAllKeysUndefined) {
                return newArray;
            }
        }

        return array;
    }

    private shouldPushInArray(item, filter) {
        if(typeof filter !== 'string') {
            item = item.toString();
            filter = filter.toString();
        }

        // Filter main logic
        item = item.toLowerCase();
        filter = filter.toLowerCase();
        if(item.indexOf(filter) !== -1) {
            return true;
        }
        return false;
    }
}

Facebook Callback appends '#_=_' to Return URL

The easiest and clean solution to remove "#_=_" (PHP):

Instead of "header("Location: xxx.php");" to use "echo ("location.href = 'xxx.php';");"

Gradle proxy configuration

If this issue with HTTP error 407 happened to selected packages only then the problem is not in the proxy setting and internet connection. You even may expose your PC to the internet through NAT and still will face this problem. Typically at the same time you can download desired packages in browser. The only solution I find: delete the .gradle folder in your profile (not in the project). After that sync the project, it will take a long time but restore everything.

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

List all kafka topics

You have a stale version of the package with commands that no longer accept zookeeper but rather bootstrap-server as the connection. Confluent will then connect with Zookeeper internally.

https://www.confluent.io/download/ (5.3 or greater)

Get DOM content of cross-domain iframe

If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.

If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:

    <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?> 

Iterate keys in a C++ map

I know this doesn't answer your question, but one option you may want to look at is just having two vectors with the same index being "linked" information..

So in..

std::vector<std::string> vName;

std::vector<int> vNameCount;

if you want the count of names by name you just do your quick for loop over vName.size(), and when ya find it that is the index for vNameCount that you are looking for.

Sure this may not give ya all the functionality of the map, and depending may or may not be better, but it might be easier if ya don't know the keys, and shouldn't add too much processing.

Just remember when you add/delete from one you have to do it from the other or things will get crazy heh :P

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

  • changed distrubutionUrl from 4.1 to 4.4

  • changed build gradle version to 3.1.1 under project/android

works for me.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

For me none of the solutions here solved it. Frustrated, I restarted my Macbook's iTerm terminal, and voila! My github authorization started working again.

Weird, but maybe iTerm has its own way of handling SSH authorizations or that my terminal session wasn't authorized somehow.

Python loop that also accesses previous and next values

Two simple solutions:

  1. If variables for both previous and next values have to be defined:
alist = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']

prev = alist[0]
curr = alist[1]

for nxt in alist[2:]:
    print(f'prev: {prev}, curr: {curr}, next: {nxt}')
    prev = curr
    curr = nxt

Output[1]:
prev: Zero, curr: One, next: Two
prev: One, curr: Two, next: Three
prev: Two, curr: Three, next: Four
prev: Three, curr: Four, next: Five
  1. If all values in the list have to be traversed by the current value variable:
alist = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']

prev = None
curr = alist[0]

for nxt in alist[1:] + [None]:
    print(f'prev: {prev}, curr: {curr}, next: {nxt}')
    prev = curr
    curr = nxt

Output[2]:
prev: None, curr: Zero, next: One
prev: Zero, curr: One, next: Two
prev: One, curr: Two, next: Three
prev: Two, curr: Three, next: Four
prev: Three, curr: Four, next: Five
prev: Four, curr: Five, next: None

How to loop through a directory recursively to delete files with certain extensions

The other answers provided will not include files or directories that start with a . the following worked for me:

#/bin/sh
getAll()
{
  local fl1="$1"/*;
  local fl2="$1"/.[!.]*; 
  local fl3="$1"/..?*;
  for inpath in "$1"/* "$1"/.[!.]* "$1"/..?*; do
    if [ "$inpath" != "$fl1" -a "$inpath" != "$fl2" -a "$inpath" != "$fl3" ]; then 
      stat --printf="%F\0%n\0\n" -- "$inpath";
      if [ -d "$inpath" ]; then
        getAll "$inpath"
      #elif [ -f $inpath ]; then
      fi;
    fi;
  done;
}

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

Angular: Can't find Promise, Map, Set and Iterator

I found the reference in boot.ts wasn't the correct path. Updating that path to /// <reference path=">../../../node_modules/angular2/typings/browser.d.ts" /> resolved the Promise errors.

What does AND 0xFF do?

The danger of the second expression comes if the type of byte1 is char. In that case, some implementations can have it signed char, which will result in sign extension when evaluating.

signed char byte1 = 0x80;
signed char byte2 = 0x10;

unsigned short value1 = ((byte2 << 8) | (byte1 & 0xFF));
unsigned short value2 = ((byte2 << 8) | byte1);

printf("value1=%hu %hx\n", value1, value1);
printf("value2=%hu %hx\n", value2, value2);

will print

value1=4224 1080     right
value2=65408 ff80    wrong!!

I tried it on gcc v3.4.6 on Solaris SPARC 64 bit and the result is the same with byte1 and byte2 declared as char.

TL;DR

The masking is to avoid implicit sign extension.

EDIT: I checked, it's the same behaviour in C++.

EDIT2: As requested explanation of sign extension. Sign extension is a consequence of the way C evaluates expressions. There is a rule in C called promotion rule. C will implicitly cast all small types to int before doing the evaluation. Let's see what happens to our expression:

unsigned short value2 = ((byte2 << 8) | byte1);

byte1 is a variable containing bit pattern 0xFF. If char is unsigned that value is interpreted as 255, if it is signed it is -128. When doing the calculation, C will extend the value to an int size (16 or 32 bits generally). This means that if the variable is unsigned and we will keep the value 255, the bit-pattern of that value as int will be 0x000000FF. If it is signed we want the value -128 which bit pattern is 0xFFFFFFFF. The sign was extended to the size of the tempory used to do the calculation. And thus oring the temporary will yield the wrong result.

On x86 assembly it is done with the movsx instruction (movzx for the zero extend). Other CPU's had other instructions for that (6809 had SEX).

iOS - Build fails with CocoaPods cannot find header files

Here's another reason: All the header paths seemed fine, but we still had an error in the precompiled (.pch) file trying to read a pod header

(i.e. #import <CocoaLumberjack/CocoaLumberjack.h>).

Looking at the raw build output, I finally noticed that the error was breaking our Watch OS Extension Target, not the main target we were building, because we were also importing the .pch precompiled header file into the Watch OS targets, and it was failing there. Make sure your accompanying Watch OS target settings don't try to import the .pch file (especially if you set that import from the master target setting, like I did!)

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

Draw an X in CSS

HTML

<div class="close-orange"></div>

CSS

.close-orange {
  height: 100px;
  width: 100px;
  background-color: #FA6900;
  border-radius: 5px;
}
.close-orange:before,.close-orange:after{
  content:'';
  position:absolute;
  width: 50px;
  height: 4px;
  background-color:white;
  border-radius:2px;
  top: 55px;
}
.close-orange:before{
  -webkit-transform:rotate(45deg);
  -moz-transform:rotate(45deg);
  transform:rotate(45deg);
  left: 32.5px;
}
.close-orange:after{
  -webkit-transform:rotate(-45deg);
  -moz-transform:rotate(-45deg);
  transform:rotate(-45deg);
  left: 32.5px;
}

https://jsfiddle.net/cooperwebdesign/dw4xd289/

Pass Method as Parameter using C#

While the accepted answer is absolutely correct, I would like to provide an additional method.

I ended up here after doing my own searching for a solution to a similar question. I am building a plugin driven framework, and as part of it I wanted people to be able to add menu items to the applications menu to a generic list without exposing an actual Menu object because the framework may deploy on other platforms that don't have Menu UI objects. Adding general info about the menu is easy enough, but allowing the plugin developer enough liberty to create the callback for when the menu is clicked was proving to be a pain. Until it dawned on me that I was trying to re-invent the wheel and normal menus call and trigger the callback from events!

So the solution, as simple as it sounds once you realize it, eluded me until now.

Just create separate classes for each of your current methods, inherited from a base if you must, and just add an event handler to each.

Difference between JSONObject and JSONArray

Best programmatically Understanding.

when syntax is {}then this is JsonObject

when syntax is [] then this is JsonArray

A JSONObject is a JSON-like object that can be represented as an element in the JSONArray. JSONArray can contain a (or many) JSONObject

Hope this will helpful to you !

Accessing MP3 metadata with Python

I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.

And I found out this: PyID3Lib, while that particular python binding release date is old, it uses the ID3Lib, which itself is up to date.

Notable to mention is that both are LGPL, and are good to go.

ORA-28000: the account is locked error getting frequently

Login to SQL Plus client on the oracle database server machine.

enter user-name: system

enter password: password [Only if, if you have not changed your default password while DB installation]

press enter. after which, you will be seeing the connection status.

Now,

SQL> ALTER USER [USER_NAME] ACCOUNT UNLOCK;

press enter.

you will be seeing message: user altered.

Now try login with the user name on db client[sqldeveloper].

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

How to determine the screen width in terms of dp or dip at runtime in Android?

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

@font-face not working

try to put below html in head tag.It worked for me.

 <title>ABC</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

ASP.NET file download from server

Simple solution for downloading a file from the server:

protected void btnDownload_Click(object sender, EventArgs e)
        {
            string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "image/jpeg";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(Server.MapPath("~/File/001.jpg"));
            response.Flush();
            response.End();
        }

Open and write data to text file using Bash?

#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 

Uncaught SyntaxError: Unexpected token :

My mistake was forgetting single/double quotation around url in javascript:

so wrong code was:

window.location = https://google.com;

and correct code:

window.location = "https://google.com";

Can I install Python 3.x and 2.x on the same Windows computer?

I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

Name them pythonX.Y.bat and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat. (E.g. copy python2.6.bat python2.bat.) Then you can use python2 file.py from anywhere.

However, this doesn't help or even affect the Windows file association situation. For that you'll need a launcher program that reads the #! line, and then associate that with .py and .pyw files.

How to convert an entire MySQL database characterset and collation to UTF-8?

The safest way is to modify the columns first to a binary type and then modify it back to it type using the desired charset.

Each column type have its respective binary type, as follows:

  1. CHAR => BINARY
  2. TEXT => BLOB
  3. TINYTEXT => TINYBLOB
  4. MEDIUMTEXT => MEDIUMBLOB
  5. LONGTEXT => LONGBLOB
  6. VARCHAR => VARBINARY

Eg.:

ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] MODIFY [COLUMN_NAME] VARBINARY;

ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] MODIFY [COLUMN_NAME] VARCHAR(140) CHARACTER SET utf8mb4;

I tried in several latin1 tables and it kept all the diacritics.

You can extract this query for all columns doing this:

SELECT
CONCAT('ALTER TABLE ', TABLE_SCHEMA,'.', TABLE_NAME,' MODIFY ', COLUMN_NAME,' VARBINARY;'),
CONCAT('ALTER TABLE ', TABLE_SCHEMA,'.', TABLE_NAME,' MODIFY ', COLUMN_NAME,' ', COLUMN_TYPE,' CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;')
FROM information_schema.columns
WHERE TABLE_SCHEMA IN ('[TABLE_SCHEMA]')
AND COLUMN_TYPE LIKE 'varchar%'
AND (COLLATION_NAME IS NOT NULL AND COLLATION_NAME NOT LIKE 'utf%');

After you do this on all your columns then you do it on all tables:

ALTER TABLE [TABLE_SCHEMA].[TABLE_NAME] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

To generate this query for all your table, use the following query:

SELECT
CONCAT('ALTER TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_COLLATION NOT LIKE 'utf8%'
and TABLE_SCHEMA in ('[TABLE_SCHEMA]');

And now that you modified all your columns and tables, do the same on the database:

ALTER DATABASE [DATA_BASE_NAME] CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci;

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the for...in statement:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

First solution

for (const field of Object.keys(this.formErrors)) {
    ...
}

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Second solution

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {
        ...
    }
}

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.

How do I send a file as an email attachment using Linux command line?

From source machine

mysqldump --defaults-extra-file=sql.cnf database | gzip | base64 | mail [email protected]

On Destination machine. Save the received mail body as db.sql.gz.b64; then..

base64 -D -i db.sql.gz.b64 | gzip -d | mysql --defaults-extra-file=sql.cnf

Can I do Model->where('id', ARRAY) multiple where conditions?

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();

or:

$items = DB::table('items')->whereIn('id',[1,2,..])->get();

get list of pandas dataframe columns based on data type

use df.info(verbose=True) where df is a pandas datafarme, by default verbose=False

how to bind datatable to datagridview in c#

for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by :

public DataTable  getAllUsers()
    {
        OracleConnection Connection = new OracleConnection(stringConnection);
        Connection.ConnectionString = stringConnection;
        Connection.Open();

        DataSet dataSet = new DataSet();

        OracleCommand cmd = new OracleCommand("semect * from Users");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Connection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet.Tables[0];
    }

step 2- set the return result to DataGridView :

public void setTableToDgv(DataGridView DGV, DataTable table)
    {
        DGV.DataSource = table;
    }

using example:

    setTableToDgv(dgv_client,getAllUsers());

How to linebreak an svg text within javascript?

This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea, but it does have auto-wrapped text.

However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
  <text x="0" y="0">
    <tspan x="0" dy="1.2em">very long text</tspan>
    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>
  </text>
</g>

Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.

Creating layout constraints programmatically

Swift version

Updated for Swift 3

This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:

Width and Height

enter image description here

Center in Container

enter image description here

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here (choose one of the methods below)
    // ...
}

Method 1: Anchor Style

// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • See also the Programmatically Creating Constraints documentation.
  • See this answer for a similar example of adding a pinning constraint.

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

Could not find module "@angular-devkit/build-angular"

  • Delete the node_modules.
  • Clear the cache using npm cache clean --verify.
  • And then npm install again.

Works like a charm for me.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

Where can I find php.ini?

Try one of this solution

  1. In your terminal type find / -name "php.ini"

  2. In your terminal type php -i | grep php.ini . It should show the file path as Configuration File (php.ini) Path => /etc

  3. If you can access one your php files , open it in a editor (notepad) and insert below code after <?php in a new line phpinfo(); This will tell you the php.ini location
  4. You can also talk to php in interactive mode. Just type php -a in the terminal and type phpinfo(); after php initiated.

ReactJS - Get Height of an element

Following is an up to date ES6 example using a ref.

Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount() because we can only determine the height of an element after it is rendered in the DOM.

import React, {Component} from 'react'
import {render} from 'react-dom'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    )
  }
}

render(<DivSize />, document.querySelector('#container'))

You can find the running example here: https://codepen.io/bassgang/pen/povzjKw

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

How to create war files

Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.

(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)

jar -cvf projectname.war *

Reference Link

How to dynamically insert a <script> tag via jQuery after page load?

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

Java String new line

It can be done several ways. I am mentioning 2 simple ways.

  1. Very simple way as below:

    System.out.println("I\nam\na\nboy");
    
  2. It can also be done with concatenation as below:

    System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
    

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
    MessageBox.Show("Valid Date");
}
else
{
    MessageBox.Show("Invalid Date... Please Give Correct Date....");
}

Java balanced expressions check {[()]}

This is my own implementation. I tried to make it the shortest an clearest way possible:

public static boolean isBraceBalanced(String braces) {
    Stack<Character> stack = new Stack<Character>();

    for(char c : braces.toCharArray()) {
        if(c == '(' || c == '[' || c == '{') {
            stack.push(c);
        } else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
                  (c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
                  (c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
            return false;
        }
    }

    return stack.isEmpty();
}

Nginx reverse proxy causing 504 Gateway Timeout

You can also face this situation if your upstream server uses a domain name, and its IP address changes (e.g.: your upstream points to an AWS Elastic Load Balancer)

The problem is that nginx will resolve the IP address once, and keep it cached for subsequent requests until the configuration is reloaded.

You can tell nginx to use a name server to re-resolve the domain once the cached entry expires:

location /mylocation {
    # use google dns to resolve host after IP cached expires
    resolver 8.8.8.8;
    set $upstream_endpoint http://your.backend.server/;
    proxy_pass $upstream_endpoint;
}

The docs on proxy_pass explain why this trick works:

Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.

Kudos to "Nginx with dynamic upstreams" (tenzer.dk) for the detailed explanation, which also contains some relevant information on a caveat of this approach regarding forwarded URIs.

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I am using Ubuntu. I just disabled ssl mode of apache2 and it worked for me.

a2dismod ssl

and then restarted apache2.

service apache2 restart

What are some uses of template template parameters?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

How do I exit from a function?

Yo can simply google for "exit sub in c#".

Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)

Or another solution is to get not of these conditions:

private void button1_Click(object sender, EventArgs e)
{
    if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
    {
        //do events
    }
}

And better use String.IsNullOrEmpty:

private void button1_Click(object sender, EventArgs e)
{
    if (!(String.IsNullOrEmpty(textBox1.Text)
    || String.IsNullOrEmpty(textBox2.Text)
    || String.IsNullOrEmpty(textBox3.Text)))
    {
        //do events
    }
}

AngularJS - Building a dynamic table based on a json

TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free

"Debug certificate expired" error in Eclipse Android plugins

In Windows debug.keystore file is localtes at C:\Users\%Username%\.android folder. This file is created when you install your android SDK and is valid only for a year. After this perod you will start getting this error Error getting final archive: Debug certificate expired on xx/xx/xxxx.

To remove this error simply delete the file and run the program again. In my Eclipse I have enabled Project->Build Automatically so it directly worked but in case you have disabled it you will need to clean the project Project->Clean.. select your project and press ok. Then you will need to build it manually. 3rd click on your project and select Build project.(Note - You will only see this option if you have diabled Build Automatically feature in your Projects Menu)

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

Webfont Smoothing and Antialiasing in Firefox and Opera

Adding

font-weight: normal;

To your @font-face fonts will fix the bold appearance in Firefox.

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

SyntaxError: missing ) after argument list

You had a unescaped " in the onclick handler, escape it with \"

$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "'  onclick=\"(canLaunch('" + v.LibraryItemId + " '))\">View &raquo;</a></div></div>")

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/

Don't do this for a production site!

Image style height and width not taken in outlook mails

This works for me in Outlook:

<img src="image.jpg" width="120" style="display:block;width:100%" />

I hope it works for you.

Excel function to make SQL-like queries on worksheet data?

You can use Get External Data (dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh 
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

How to filter in NaN (pandas)?

Pandas uses numpy's NaN value. Use numpy.isnan to obtain a Boolean vector from a pandas series.

HTML image not showing in Gmail

In addition to what was said by Howard

You have to keep in mind that Google encodes spaces as + To avoid this, the ulr must be encoded in RFC 3986, which means spaces encoded at %20, for example:

https://example.com/My Folder/image 1.jpg to https://example.com/My%20Folder/image%201.jpg

AngularJS: how to implement a simple file upload with multipart form?

It is more efficient to send a file directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

$scope.upload = function(url, file) {
    var config = { headers: { 'Content-Type': undefined },
                   transformResponse: angular.identity
                 };
    return $http.post(url, file, config);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.

To send multiple files, see Doing Multiple $http.post Requests Directly from a FileList


I figured I should start with input type="file", but then found out that AngularJS can't bind to that..

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

Working Demo of "select-ng-files" Directive that Works with ng-model1

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileArray" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileArray">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_


$http.post with content type multipart/form-data

If one must send multipart/form-data:

<form role="form" enctype="multipart/form-data" name="myForm">
    <input type="text"  ng-model="fdata.UserName">
    <input type="text"  ng-model="fdata.FirstName">
    <input type="file"  select-ng-files ng-model="filesArray" multiple>
    <button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
    var fd = new FormData();
    fd.append("data", angular.toJson($scope.fdata));
    for (i=0; i<$scope.filesArray.length; i++) {
        fd.append("file"+i, $scope.filesArray[i]);
    };

    var config = { headers: {'Content-Type': undefined},
                   transformRequest: angular.identity
                 }
    return $http.post(url, fd, config);
};

When sending a POST with the FormData API, it is important to set 'Content-Type': undefined. The XHR send method will then detect the FormData object and automatically set the content type header to multipart/form-data with the proper boundary.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to check the presence of php and apache on ubuntu server through ssh

You could inspect the available apache2 modules:

$ ls /usr/lib/apache2/modules/

Or try to enable the php module, if you have the appropriate access:

$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..

restrict edittext to single line

for me i do it like this , go to your textView in xml file and add this two lines

` android:maxLines="1"

android:inputType="text"`

how to find 2d array size in c++

Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},
                   {6, 7, 8, 9, 0}
                 };

  int rows =  sizeof ary / sizeof ary[0]; // 2 rows  

  int cols = sizeof ary[0] / sizeof(int); // 5 cols

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Move cursor to end of file in vim

If you want to paste some clipboard content at the end of the file type:

:$ put +

$ ............ last line
put .......... paste 
+ ............ clipboard

Rename file with Git

Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:

(you don't even need to clone that repo, git mv xx and git push back to GitHub!)

renaming

You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by /.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!

moving

How to call jQuery function onclick?

Please have a look at http://jsfiddle.net/2dJAN/59/

$("#submit").click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});

cleanest way to skip a foreach if array is empty

i've got the following function in my "standard library"

/// Convert argument to an array.
function a($a = null) {
    if(is_null($a))
        return array();
    if(is_array($a))
        return $a;
    if(is_object($a))
        return (array) $a;
    return $_ = func_get_args();
}

Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions

  foreach(a($whatever) as $item)....

  $foo = array_map(a($array_or_string)....

  etc

Write single CSV file using spark-csv

by using Listbuffer we can save data into single file:

import java.io.FileWriter
import org.apache.spark.sql.SparkSession
import scala.collection.mutable.ListBuffer
    val text = spark.read.textFile("filepath")
    var data = ListBuffer[String]()
    for(line:String <- text.collect()){
      data += line
    }
    val writer = new FileWriter("filepath")
    data.foreach(line => writer.write(line.toString+"\n"))
    writer.close()

Include PHP inside JavaScript (.js) files

Instead of messing with generic php-handlers do a 1-file exception using a rewrite:

Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:

RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]

Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:

<?php header('Content-Type: application/javascript'); ?>

Et voilà, you can now use php-tags in your ".js"-file.

Convert json data to a html table

Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.

Code snippet:

_x000D_
_x000D_
var myList = [_x000D_
  { "name": "abc", "age": 50 },_x000D_
  { "age": "25", "hobby": "swimming" },_x000D_
  { "name": "xyz", "hobby": "programming" }_x000D_
];_x000D_
_x000D_
// Builds the HTML Table out of myList._x000D_
function buildHtmlTable(selector) {_x000D_
  var columns = addAllColumnHeaders(myList, selector);_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var row$ = $('<tr/>');_x000D_
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {_x000D_
      var cellValue = myList[i][columns[colIndex]];_x000D_
      if (cellValue == null) cellValue = "";_x000D_
      row$.append($('<td/>').html(cellValue));_x000D_
    }_x000D_
    $(selector).append(row$);_x000D_
  }_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records._x000D_
function addAllColumnHeaders(myList, selector) {_x000D_
  var columnSet = [];_x000D_
  var headerTr$ = $('<tr/>');_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var rowHash = myList[i];_x000D_
    for (var key in rowHash) {_x000D_
      if ($.inArray(key, columnSet) == -1) {_x000D_
        columnSet.push(key);_x000D_
        headerTr$.append($('<th/>').html(key));_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  $(selector).append(headerTr$);_x000D_
_x000D_
  return columnSet;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body onLoad="buildHtmlTable('#excelDataTable')">_x000D_
  <table id="excelDataTable" border="1">_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How do I remove blank pages coming between two chapters in Appendix?

In my case, I still wanted the open on odd pages option but this would produce a blank page with the chapter name in the header. I didn't want the header. And so to avoid this I used this at the end of the chapter:

\clearpage

\thispagestyle{plain}

This let's you keep the blank page on the last even page of the chapter but without the header.

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

What is the yield keyword used for in C#?

The C# yield keyword, to put it simply, allows many calls to a body of code, referred to as an iterator, that knows how to return before it's done and, when called again, continues where it left off - i.e. it helps an iterator become transparently stateful per each item in a sequence that the iterator returns in successive calls.

In JavaScript, the same concept is called Generators.

Why doesn't file_get_contents work?

Wrap your $adr in urlencode(). I was having this problem and this solved it for me.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

Console app arguments, how arguments are passed to Main method

How is main called?

When you are using the console application template the code will be compiled requiring a method called Main in the startup object as Main is market as entry point to the application.

By default no startup object is specified in the project propery settings and the Program class will be used by default. You can change this in the project property under the "Build" tab if you wish.

Keep in mind that which ever object you assign to be the startup object must have a method named Main in it.

How are args passed to main method

The accepted format is MyConsoleApp.exe value01 value02 etc...

The application assigns each value after each space into a separate element of the parameter array.

Thus, MyConsoleApp.exe value01 value02 will mean your args paramter has 2 elements:

[0] = "value01"

[1] = "value02"

How you parse the input values and use them is up to you.

Hope this helped.

Additional Reading:

Creating Console Applications (Visual C#)

Command-Line Arguments (C# Programming Guide)

How to parse JSON in Kotlin?

You can use this library https://github.com/cbeust/klaxon

Klaxon is a lightweight library to parse JSON in Kotlin.

C# Break out of foreach loop after X number of items

Why not just use a regular for loop?

for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}

Updated to resolve bug pointed out by Ruben and Pragmatrix.

Returning a value from thread?

Simply use the delegate approach.

int val;
Thread thread = new Thread(() => { val = Multiply(1, 2); });
thread.Start();

Now make Multiply function that will work on another thread:

int Multiply(int x, int y)
{
    return x * y;
}

async at console app in C#?

In most project types, your async "up" and "down" will end at an async void event handler or returning a Task to your framework.

However, Console apps do not support this.

You can either just do a Wait on the returned task:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

or you can use your own context like the one I wrote:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

More information for async Console apps is on my blog.

Is std::vector copying the objects with a push_back?

std::vector always makes a copy of whatever is being stored in the vector.

If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.

In c, in bool, true == 1 and false == 0?

You neglected to say which version of C you are concerned about. Let's assume it's this one:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

As you can see by reading the specification, the standard definitions of true and false are 1 and 0, yes.

If your question is about a different version of C, or about non-standard definitions for true and false, then ask a more specific question.

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

Add attribute 'checked' on click jquery

A simple answer is to add checked attributes within a checkbox:

$('input[id='+$(this).attr("id")+']').attr("checked", "checked");

How does OkHttp get Json string?

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got the same error for pandas latest version. Then saw this warning

FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.

This shall work for you.

Let JSON object accept bytes or let urlopen output strings

For anyone else trying to solve this using the requests library:

import json
import requests

r = requests.get('http://localhost/index.json')
r.raise_for_status()
# works for Python2 and Python3
json.loads(r.content.decode('utf-8'))

Java Set retain order?

To retain the order use List or a LinkedHashSet.

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

How do you display code snippets in MS Word preserving format and syntax highlighting?

I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.

How does the compilation/linking process work?

This topic is discussed at CProgramming.com:
https://www.cprogramming.com/compilingandlinking.html

Here is what the author there wrote:

Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.

Compilation

Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.

Linking

Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.

You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)

To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.

Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

What is the difference between const int*, const int * const, and int const *?

  • if const is to the left of *, it refers to the value (it doesn't matter whether it's const int or int const)
  • if const is to the right of *, it refers to the pointer itself
  • it can be both at the same time

An important point: const int *p does not mean the value you are referring to is constant!!. It means that you can't change it through that pointer (meaning, you can't assign $*p = ...`). The value itself may be changed in other ways. Eg

int x = 5;
const int *p = &x;
x = 6; //legal
printf("%d", *p) // prints 6
*p = 7; //error 

This is meant to be used mostly in function signatures, to guarantee that the function can't accidentally change the arguments passed.

Declare a dictionary inside a static class

public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };             
    }
}

Probably initialise in the constructor.

JavaScript/regex: Remove text between parentheses

If you need to remove text inside nested parentheses, too, then:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

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

In CentOS/RedHat (assuming you installed the jenkins package)

vim /etc/sysconfig/jenkins

....
# Port Jenkins is listening on.
# Set to -1 to disable
#
JENKINS_PORT="8080"

change it to any port you want.

How to convert a Map to List in Java?

I guess you want to convert the values contained in the Map to a list? Easiest is to call the values() method of the Map interface. This will return the Collection of value objects contained in the Map.

Note that this Collection is backed by the Map object and any changes to the Map object will reflect here. So if you want a separate copy not bound to your Map object, simply create a new List object like an ArrayList passing the value Collection as below.

ArrayList<String> list = new ArrayList<String>(map.values());

How to use comparison and ' if not' in python?

Why think? If not confuses you, switch your if and else clauses around to avoid the negation.

i want to make sure that ( u0 <= u < u0+step ) before do sth.

Just write that.

if u0 <= u < u0+step:
    "do sth" # What language is "sth"?  No vowels.  An odd-looking word.
else:
    u0 = u0+ step

Why overthink it?

If you need an empty if -- and can't work out the logic -- use pass.

 if some-condition-that's-too-complex-for-me-to-invert:
     pass
 else: 
     do real work here

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

After experimenting on that case: android:textColor="@colors/text_color" is wrong since @color is not filename dependant. You can name your resource file foobar.xml, it doesn't matter but if you have defined some colors in it you can access them using @color/some_color.

Update:

file location: res/values/colors.xml The filename is arbitrary. The element's name will be used as the resource ID. (Source)

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Get all directories within directory nodejs

Alternatively, if you are able to use external libraries, you can use filehound. It supports callbacks, promises and sync calls.

Using promises:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory() // only search for directories
  .find()
  .then((subdirectories) => {
    console.log(subdirectories);
  });

Using callbacks:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory()
  .find((err, subdirectories) => {
    if (err) return console.error(err);

    console.log(subdirectories);
  });

Sync call:

const Filehound = require('filehound');

const subdirectories = Filehound.create()
  .path("MyFolder")
  .directory()
  .findSync();

console.log(subdirectories);

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

PHP call Class method / function

To answer your question, the current method would be to create the object then call the method:

$functions = new Functions();
$var = $functions->filter($_GET['params']);

Another way would be to make the method static since the class has no private data to rely on:

public static function filter($data){

This can then be called like so:

$var = Functions::filter($_GET['params']);

Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions and the public in the method. This can then be called like you tried:

$var = filter($_GET['params']);

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setText("Passed!");
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setText("Failed!");
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

google-services.json for different productFlavors

UPDATE: The following explanation is for one Android Studio project, with one Firebase Project and different Firebase Apps inside that project. If the aim is to have different JSON files for different Firebase Apps in different Firebase Projects inside the same Android Studio project, (or if you don't know what's the difference) look here..

You need one Firebase App per Android Application ID (usually package name). Is common to have one Application ID per Gradle build variant (This is gonna be likely if you use Gradle build types and Gradle build flavours)


As of Google Services 3.0 and using Firebase it's not necessary to create different files for different flavours. Creating different files for different flavours can be not clear or straightforward in case you have productFlavours and Build types which compose with each other.

In the same file you'll have the all the configurations you need for all your build types and flavours.

In the Firebase console you need to add one app per package name. Imagine that you have 2 flavours (dev and live) and 2 build types (debug and release). Depending on your config but it's likely that you have 4 different package names like:

  • com.stackoverflow.example (live - release)
  • com.stackoverflow.example.dev (live - dev)
  • com.stackoverflow.example.debug (debug - release)
  • com.stackoverflow.example.dev.debug (debug - dev)

You need 4 different Android Apps in the Firebase Console. (On each one you need to add the SHA-1 for debug and live for each computer you are using)

When you download the google-services.json file, actually it doesn't really matter from what app you download it, all of them contain the same info related to all your apps.

Now you need to locate this file in app level (app/).

enter image description here

If you open that file you'll see that if contains all the information for all your package names.

A pain point use to be the plugin. In order to get it working you need to locate the plugin at the bottom of your file. So this line..

apply plugin: 'com.google.gms.google-services'

...needs to be on the bottom of your app build.gradle file.

For most of the said here, it applies to previous versions as well. I've never had different files for different configs, but now with the Firebase console is easier because they provide one single file with everything you need for all you configs.

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

How to make a Div appear on top of everything else on the screen?

dropdowns always show up on top, only solution for this problem is to hide dropdowns when image is displayed (display:block or visibility:visibile) and show them when image hidden (display:none or visibility:hidden)

Removing unwanted table cell borders with CSS

sometimes even after clearing borders.

the reason is that you have images inside the td, giving the images display:block solves it.

How can I scroll a div to be visible in ReactJS?

To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:

_x000D_
_x000D_
  componentDidUpdate() {_x000D_
    let panel, node;_x000D_
    if (this.refs.selectedSection && this.refs.selectedItem) {_x000D_
      // This is the container you want to scroll.          _x000D_
      panel = this.refs.listPanel;_x000D_
      // This is the element you want to make visible w/i the container_x000D_
      // Note: You can nest refs here if you want an item w/i the selected item          _x000D_
      node = ReactDOM.findDOMNode(this.refs.selectedItem);_x000D_
    }_x000D_
_x000D_
    if (panel && node &&_x000D_
      (node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {_x000D_
      panel.scrollTop = node.offsetTop - panel.offsetTop;_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Launching an application (.EXE) from C#?

Just put your file.exe in the \bin\Debug folder and use:

Process.Start("File.exe");

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

How do I install Java on Mac OSX allowing version switching?

You can use asdf to install and switch between multiple java versions. It has plugins for other languages as well. You can install asdf with Homebrew

brew install asdf

When asdf is configured, install java plugin

asdf plugin-add java

Pick a version to install

asdf list-all java

For example to install and configure adoptopenjdk8

asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10

And finally if needed, configure JAVA_HOME for your shell. Just add to your shell init script such as ~/.zshrc in case of zsh:

. ~/.asdf/plugins/java/set-java-home.zsh

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Both will work but xhtml standard requires you to specify the type too:

<script type="text/javascript">..</script> 

<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
  charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
  type        %ContentType;  #REQUIRED -- content type of script language --
  src         %URI;          #IMPLIED  -- URI for an external script --
  defer       (defer)        #IMPLIED  -- UA may defer execution of script --
  >

type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Notices the emphasis above.

http://www.w3.org/TR/html4/interact/scripts.html

Note: As of HTML5 (far away), the type attribute is not required and is default.

How do I open a second window from the first window in WPF?

You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:

var window2 = new Window2();
window2.Show();

Determine whether a key is present in a dictionary

In the same vein as martineau's response, the best solution is often not to check. For example, the code

if x in d:
    foo = d[x]
else:
    foo = bar

is normally written

foo = d.get(x, bar)

which is shorter and more directly speaks to what you mean.

Another common case is something like

if x not in d:
    d[x] = []

d[x].append(foo)

which can be rewritten

d.setdefault(x, []).append(foo)

or rewritten even better by using a collections.defaultdict(list) for d and writing

d[x].append(foo)

Notice: Array to string conversion in

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

How do I fire an event when a iframe has finished loading in jQuery?

I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:

Step 1: Wrap your Iframe in a div wrapper

Step 2: Add a background image to your div wrapper:

.wrapperdiv{
  background-image:url(img/loading.gif);
  background-repeat:no-repeat;
  background-position:center center; /*Can place your loader where ever you like */
}

Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"

The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.

Give it a try.

How to install easy_install in Python 2.7.1 on Windows 7

for 32-bit Python, the installer is here. after you run the installer, you will have easy_install.exe in your \Python27\Scripts directory

if you are looking for 64-bit installers, this is an excellent resource:

http://www.lfd.uci.edu/~gohlke/pythonlibs/

the author has installers for both Setuptools and Distribute. Either one will give you easy_install.exe

How to create a GUID / UUID

There are many correct answers here, but sadly, included code samples are quite cryptic and difficult to understand. This is how I create version 4 (random) UUIDs.

Note that following pieces of code make use of binary literals for improved readability, thus require ECMAScript 6.

Node version

function uuid4() {
  let array = new Uint8Array(16)
  crypto.randomFillSync(array)

  // manipulate 9th byte
  array[8] &= 0b00111111 // clear first two bits
  array[8] |= 0b10000000 // set first two bits to 10

  // manipulate 7th byte
  array[6] &= 0b00001111 // clear first four bits
  array[6] |= 0b01000000 // set first four bits to 0100

  const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  let idx = 0

  return pattern.replace(
    /XX/g,
    () => array[idx++].toString(16).padStart(2, "0"), // padStart ensures leading zero, if needed
  )
}

Browser version

Only the 2nd line is different.

function uuid4() {
  let array = new Uint8Array(16)
  crypto.getRandomValues(array)

  // manipulate 9th byte
  array[8] &= 0b00111111 // clear first two bits
  array[8] |= 0b10000000 // set first two bits to 10

  // manipulate 7th byte
  array[6] &= 0b00001111 // clear first four bits
  array[6] |= 0b01000000 // set first four bits to 0100

  const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  let idx = 0

  return pattern.replace(
    /XX/g,
    () => array[idx++].toString(16).padStart(2, "0"), // padStart ensures leading zero, if needed
  )
}

Tests

And finally, corresponding tests (Jasmine).

describe(".uuid4()", function() {
  it("returns a UUIDv4 string", function() {
    const uuidPattern = "XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX"
    const uuidPatternRx = new RegExp(uuidPattern.
      replaceAll("X", "[0-9a-f]").
      replaceAll("Y", "[89ab]"))

    for (let attempt = 0; attempt < 1000; attempt++) {
      let retval = uuid4()
      expect(retval.length).toEqual(36)
      expect(retval).toMatch(uuidPatternRx)
    }
  })
})

UUID v4 explained

A very good explanation of UUID version 4 is here: https://www.cryptosys.net/pki/uuid-rfc4122.html.

Final notes

Also, there are plenty of third-party packages. However, as long as you have just basic needs, I don't recommend them. Really, there is not much to win and pretty much to lose. Authors may pursue for tiniest bits of performance, "fix" things which aren't supposed to be fixed, and when it comes to security, it is a risky idea. Similarly, they may introduce other bugs or incompatibilities. Careful updates require time.

Regex date format validation on Java

Putting it all together:

  • REGEX doesn't validate values (like "2010-19-19")
  • SimpleDateFormat does not check format ("2010-1-2", "1-0002-003" are accepted)

it's necessary to use both to validate format and value:

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setLenient(false);
    try {
        df.parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}



A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:

private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        System.out.println("created");
        return df;
    }
};

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    try {
        format.get().parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

(same can be done for a Matcher, that also is not thread safe)

Hibernate: "Field 'id' doesn't have a default value"

Another suggestion is to check that you use a valid type for the auto-generated field. Remember that it doesn't work with String, but it works with Long:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long id;

@Constraints.Required
public String contents;

The above syntax worked for generating tables in MySQL using Hibernate as a JPA 2.0 provider.

Display a decimal in scientific notation

No one mentioned the short form of the .format method:

Needs at least Python 3.6

f"{Decimal('40800000000.00000000000000'):.2E}"

(I believe it's the same as Cees Timmerman, just a bit shorter)

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

This is a very common case in DataTables when it's not able to find the request field define in DataTable configuration.
For Example:

                "aoColumns": [{
                    mData: 'mobile', sWidth: "149px;"
               }, {
                    mData: 'name', sWidth: "121px;"
               }, {
                    mData: 'productName', sWidth: "116px;"
                            }
            }];

Here, If DataTable doesn't receive above mentioned properties. It'll generate this warning:

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

To overcome this you just need to simply set a default value in "aoColumns"

For Example:

  "aoColumns": [{
                mData: 'mobile',sDefaultContent :  '',sWidth: "149px;"
           }, {
                mData: 'name',sDefaultContent :  '', sWidth: "121px;"
           }, {
                mData: 'productName',sDefaultContent :  '', sWidth: "116px;"
              }
        }];

sDefaultContent will supress the warning.
Note: This property could be changed based on version of dataTables you are using.

'float' vs. 'double' precision

A float has 23 bits of precision, and a double has 52.

HTML embed autoplay="false", but still plays automatically

Chrome doesn't seem to understand true and false. Use autostart="1" and autostart="0" instead.


Source: (Google Groups: https://productforums.google.com/forum/#!topic/chrome/LkA8FoBoleU)

Download the Android SDK components for offline install

I know this topic is a bit old, but after struggling and waiting a lot to download, Ive changed my DNS settings to use google's one (4.4.4.4 and 8.8.8.8) and it worked!!

My connection is 30mbps from Brazil (Virtua), using isp's provider I was getting 80KB/s and after changing to google dns, I got 2MB/s average.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

On Windows, I got "Unable to delete directory". What's wrong? For instance, clean could fail if you already have opened a command line with target as the current dir. Windows locks some ressources and you need to close the handles on these ressources.

This works for me.

Detect click inside/outside of element with single event handler

Using jQuery, and assuming that you have <div id="foo">:

jQuery(function($){
  $('#foo').click(function(e){
    console.log( 'clicked on div' );
    e.stopPropagation(); // Prevent bubbling
  });
  $('body').click(function(e){
    console.log( 'clicked outside of div' );
  });
});

Edit: For a single handler:

jQuery(function($){
  $('body').click(function(e){
    var clickedOn = $(e.target);
    if (clickedOn.parents().andSelf().is('#foo')){
      console.log( "Clicked on", clickedOn[0], "inside the div" );
    }else{
      console.log( "Clicked outside the div" );
  });
});

Where to find htdocs in XAMPP Mac

There are two ways to find it:

One way is to open Finder>Applications>XAMPP(FolderNotTheInstaller)>htdocs

Another way is cmd+space and searches for manager-osx,

go to Welcome and click the Open Application Folder.

enter image description here

Run Stored Procedure in SQL Developer?

None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:

SET serveroutput on;
DECLARE
  testvar varchar(100);
BEGIN
  testvar := 'dude';
  schema.MY_PROC(testvar);
  dbms_output.enable;
  dbms_output.put_line(testvar);
END;

And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).

NOTE (differences with mine vs. others):

  • No : prior to the variable name
  • No putting .package. or .packages. between the schema name and the procedure name
  • No having to put an & in the variable's value.
  • No using print anywhere
  • No using var to declare the variable

All of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.

Changing CSS Values with Javascript

You can get the "computed" styles of any element.

IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".

You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).

That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)

Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:

<div style="width:50%">....</div>

Do you recommend using semicolons after every statement in JavaScript?

I use semicolon, since it is my habit. Now I understand why I can't have string split into two lines... it puts semicolon at the end of each line.

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

Importing from a relative path in Python

Don't do relative import.

From PEP8:

Relative imports for intra-package imports are highly discouraged.

Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.

Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.

Laravel csrf token mismatch for ajax POST Request

If you are using template files, than you can put your meta tag in the head section (or whatever you name it) which contain your meta tags.

@section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@endsection

Next thing, you need to put the headers attribute to your ajax(in my example, I am using datatable with server-side processing:

"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}

Here is the full datatable ajax example:

$('#datatable_users').DataTable({
        "responsive": true,
        "serverSide": true,
        "processing": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": {
            "type": "POST",
            "headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
            "url": "/getUsers",
            "dataType": "json",
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) {
                console.log(data);
            },
            "complete": function(response) {
                console.log(response);
           }
        }
    });

After doing this, you should get 200 status for your ajax request.

How do I store an array in localStorage?

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars).

Saving a Excel File into .txt format without quotes

The answer from this question provided the answer to this question much more simply.

Write is a special statement designed to generate machine-readable files that are later consumed with Input.

Use Print to avoid any fiddling with data.

Thank you user GSerg

UIGestureRecognizer on UIImageView

I just done this with swift4 by adding 3 gestures together in single view

  1. UIPinchGestureRecognizer : Zoom in and zoom out view.
  2. UIRotationGestureRecognizer : Rotate the view.
  3. UIPanGestureRecognizer : Dragging the view.

Here my sample code

class ViewController: UIViewController: UIGestureRecognizerDelegate{
      //your image view that outlet from storyboard or xibs file.
     @IBOutlet weak var imgView: UIImageView!
     // declare gesture recognizer
     var panRecognizer: UIPanGestureRecognizer?
     var pinchRecognizer: UIPinchGestureRecognizer?
     var rotateRecognizer: UIRotationGestureRecognizer?

     override func viewDidLoad() {
          super.viewDidLoad()
          // Create gesture with target self(viewcontroller) and handler function.  
          self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
          self.pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
          self.rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
          //delegate gesture with UIGestureRecognizerDelegate
          pinchRecognizer?.delegate = self
          rotateRecognizer?.delegate = self
          panRecognizer?.delegate = self
          // than add gesture to imgView
          self.imgView.addGestureRecognizer(panRecognizer!)
          self.imgView.addGestureRecognizer(pinchRecognizer!)
          self.imgView.addGestureRecognizer(rotateRecognizer!)
     }

     // handle UIPanGestureRecognizer 
     @objc func handlePan(recognizer: UIPanGestureRecognizer) {    
          let gview = recognizer.view
          if recognizer.state == .began || recognizer.state == .changed {
               let translation = recognizer.translation(in: gview?.superview)
               gview?.center = CGPoint(x: (gview?.center.x)! + translation.x, y: (gview?.center.y)! + translation.y)
               recognizer.setTranslation(CGPoint.zero, in: gview?.superview)
          }
     }

     // handle UIPinchGestureRecognizer 
     @objc func handlePinch(recognizer: UIPinchGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.scaledBy(x: recognizer.scale, y: recognizer.scale))!
               recognizer.scale = 1.0
         }
     }   

     // handle UIRotationGestureRecognizer 
     @objc func handleRotate(recognizer: UIRotationGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.rotated(by: recognizer.rotation))!
               recognizer.rotation = 0.0
           }
     }

     // mark sure you override this function to make gestures work together 
     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }

}

Any question, just type to comment. thank you

How to get an MD5 checksum in PowerShell

PowerShell One-Liners (string to hash)

MD5

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA1

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA256

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA384

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA512

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

CSS image resize percentage of itself?

This is a not-hard approach:

<div>
    <img src="sample.jpg" />
</div>

then in css:
div {
    position: absolute;
}

img, div {
   width: ##%;
   height: ##%;
}

How to check whether Kafka Server is running?

Firstly you need to create AdminClient bean:

 @Bean
 public AdminClient adminClient(){
   Map<String, Object> configs = new HashMap<>();
   configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
   StringUtils.arrayToCommaDelimitedString(new Object[]{"your bootstrap server address}));
   return AdminClient.create(configs);
 }

Then, you can use this script:

while (true) {
   Map<String, ConsumerGroupDescription> groupDescriptionMap =
         adminClient.describeConsumerGroups(Collections.singletonList(groupId))
         .all()
         .get(10, TimeUnit.SECONDS);

   ConsumerGroupDescription consumerGroupDescription = groupDescriptionMap.get(groupId);

   log.debug("Kafka consumer group ({}) state: {}",
                groupId,
                consumerGroupDescription.state());

   if (consumerGroupDescription.state().equals(ConsumerGroupState.STABLE)) {
        boolean isReady = true;
        for (MemberDescription member : consumerGroupDescription.members()) {
            if (member.assignment() == null || member.assignment().topicPartitions().isEmpty()) {
            isReady = false;
            }
        }

        if (isReady) {
            break;
           }
        }

        log.debug("Kafka consumer group ({}) is not ready. Waiting...", groupId);
        TimeUnit.SECONDS.sleep(1);
}

This script will check the state of the consumer group every second till the state will be STABLE. Because all consumers assigned to topic partitions, you can conclude that server is running and ready.

What is the difference between document.location.href and document.location?

Here is an example of the practical significance of the difference and how it can bite you if you don't realize it (document.location being an object and document.location.href being a string):

We use MonoX Social CMS (http://mono-software.com) free version at http://social.ClipFlair.net and we wanted to add the language bar WebPart at some pages to localize them, but at some others (e.g. at discussions) we didn't want to use localization. So we made two master pages to use at all our .aspx (ASP.net) pages, in the first one we had the language bar WebPart and the other one had the following script to remove the /lng/el-GR etc. from the URLs and show the default (English in our case) language instead for those pages

<script>
  var curAddr = document.location; //MISTAKE
  var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
  if (curAddr != newAddr)
    document.location = newAddr;
</script>

But this code isn't working, replace function just returns Undefined (no exception thrown) so it tries to navigate to say x/lng/el-GR/undefined instead of going to url x. Checking it out with Mozilla Firefox's debugger (F12 key) and moving the cursor over the curAddr variable it was showing lots of info instead of some simple string value for the URL. Selecting Watch from that popup you could see in the watch pane it was writing "Location -> ..." instead of "..." for the url. That made me realize it was an object

One would have expected replace to throw an exception or something, but now that I think of it the problem was that it was trying to call some non-existent "replace" method on the URL object which seems to just give back "undefined" in Javascript.

The correct code in that case is:

<script>
  var curAddr = document.location.href; //CORRECT
  var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
  if (curAddr != newAddr)
    document.location = newAddr;
</script>

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

<form enctype="multipart/form-data" action="post_upload.php" method="POST">

Then the key to success;

<input type="file" name="file[]" multiple />

do NOT forget those brackets! In the post_upload.php try the following:

<?php print_r($_FILES['file']['tmp_name']); ?>

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

$_FILES['file']['tmp_name'][0]

You can use php count() to count the number of files that was selected. Goodluck widdit!

View JSON file in Browser

json-ie.reg. for IE

try this url

http://www.jsonviewer.com/

Flutter : Vertically center column

You could use. mainAxisAlignment:MainAxisAlignment.center This will the material through the center in the column wise. `crossAxisAlignment: CrossAxisAlignment.center' This will align the items in the center in the row wise.

Container( alignment:Alignment.center, Child: Column () )

Simply use. Center ( Child: Column () ) or rap with Padding widget . And adjust the Padding such the the column children are in the center.

@synthesize vs @dynamic, what are the differences?

One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.

Set start value for column with autoincrement

In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:

Here the autoincrement will start at 760

Division of integers in Java

You don't even need doubles for this. Just multiply by 100 first and then divide. Otherwise the result would be less than 1 and get truncated to zero, as you saw.

edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I had the same error, then I tried <asp:PostBackTrigger ControlID="xyz"/> instead of AsyncPostBackTrigger .This worked for me. It is because we don't want a partial postback.

make a phone call click on a button

add "tel:" along with your number to be dialed in your intent and then start your activity.

Intent myIntent = new Intent(Intent.ACTION_CALL);
 String phNum = "tel:" + "1234567890";
 myIntent.setData(Uri.parse(phNum));
  startActivity( myIntent ) ;

changing textbox border colour using javascript

Add an onchange event to your input element:

<input type="text" id="fName" value="" onchange="fName_Changed(this)" />

Javascript:

function fName_Changed(fName)
{
    fName.style.borderColor = (fName.value != 'correct text') ? "#FF0000"; : fName.style.borderColor="";
}

How can I programmatically get the MAC address of an iphone

I wanted something to return the address regardless of whether or not wifi was enabled, so the chosen solution didn't work for me. I used another call I found on some forum after some tweaking. I ended up with the following (excuse my rusty C ) :

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>


char*  getMacAddress(char* macAddress, char* ifName) {

int  success;
struct ifaddrs * addrs;
struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const unsigned char* base;
int i;

success = getifaddrs(&addrs) == 0;
if (success) {
    cursor = addrs;
    while (cursor != 0) {
        if ( (cursor->ifa_addr->sa_family == AF_LINK)
            && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp(ifName,  cursor->ifa_name)==0 ) {
            dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
            base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
            strcpy(macAddress, ""); 
            for (i = 0; i < dlAddr->sdl_alen; i++) {
                if (i != 0) {
                    strcat(macAddress, ":");
                }
                char partialAddr[3];
                sprintf(partialAddr, "%02X", base[i]);
                strcat(macAddress, partialAddr);

            }
        }
        cursor = cursor->ifa_next;
    }

    freeifaddrs(addrs);
}    
return macAddress;
}

And then I would call it asking for en0, as follows:

char* macAddressString= (char*)malloc(18);
NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString, "en0")
                                              encoding:NSMacOSRomanStringEncoding];
free(macAddressString);

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

With the advent of Span<T> released with C# 7.2, the canonical technique to capture the underlying memory representation of a string into a managed byte array is:

byte[] bytes = "rubbish_\u9999_string".AsSpan().AsBytes().ToArray();

Converting it back should be a non-starter because that means you are in fact interpreting the data somehow, but for the sake of completeness:

string s;
unsafe
{
    fixed (char* f = &bytes.AsSpan().NonPortableCast<byte, char>().DangerousGetPinnableReference())
    {
        s = new string(f);
    }
}

The names NonPortableCast and DangerousGetPinnableReference should further the argument that you probably shouldn't be doing this.

Note that working with Span<T> requires installing the System.Memory NuGet package.

Regardless, the actual original question and follow-up comments imply that the underlying memory is not being "interpreted" (which I assume means is not modified or read beyond the need to write it as-is), indicating that some implementation of the Stream class should be used instead of reasoning about the data as strings at all.

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()