Programs & Examples On #Cycle plugin

Regex to validate JSON

As was written above, if the language you use has a JSON-library coming with it, use it to try decoding the string and catch the exception/error if it fails! If the language does not (just had such a case with FreeMarker) the following regex could at least provide some very basic validation (it's written for PHP/PCRE to be testable/usable for more users). It's not as foolproof as the accepted solution, but also not that scary =):

~^\{\s*\".*\}$|^\[\n?\{\s*\".*\}\n?\]$~s

short explanation:

// we have two possibilities in case the string is JSON
// 1. the string passed is "just" a JSON object, e.g. {"item": [], "anotheritem": "content"}
// this can be matched by the following regex which makes sure there is at least a {" at the
// beginning of the string and a } at the end of the string, whatever is inbetween is not checked!

^\{\s*\".*\}$

// OR (character "|" in the regex pattern)
// 2. the string passed is a JSON array, e.g. [{"item": "value"}, {"item": "value"}]
// which would be matched by the second part of the pattern above

^\[\n?\{\s*\".*\}\n?\]$

// the s modifier is used to make "." also match newline characters (can happen in prettyfied JSON)

if I missed something that would break this unintentionally, I'm grateful for comments!

C library function to perform sort

For sure: qsort() is an implementation of a sort (not necessarily quicksort as its name might suggest).

Try man 3 qsort or have a read at http://linux.die.net/man/3/qsort

AngularJS ui-router login authentication

I wanted to share another solution working with the ui router 1.0.0.X

As you may know, stateChangeStart and stateChangeSuccess are now deprecated. https://github.com/angular-ui/ui-router/issues/2655

Instead you should use $transitions http://angular-ui.github.io/ui-router/1.0.0-alpha.1/interfaces/transition.ihookregistry.html

This is how I achieved it:

First I have and AuthService with some useful functions

angular.module('myApp')

        .factory('AuthService',
                ['$http', '$cookies', '$rootScope',
                    function ($http, $cookies, $rootScope) {
                        var service = {};

                        // Authenticates throug a rest service
                        service.authenticate = function (username, password, callback) {

                            $http.post('api/login', {username: username, password: password})
                                    .success(function (response) {
                                        callback(response);
                                    });
                        };

                        // Creates a cookie and set the Authorization header
                        service.setCredentials = function (response) {
                            $rootScope.globals = response.token;

                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + response.token;
                            $cookies.put('globals', $rootScope.globals);
                        };

                        // Checks if it's authenticated
                        service.isAuthenticated = function() {
                            return !($cookies.get('globals') === undefined);
                        };

                        // Clear credentials when logout
                        service.clearCredentials = function () {
                            $rootScope.globals = undefined;
                            $cookies.remove('globals');
                            $http.defaults.headers.common.Authorization = 'Bearer ';
                        };

                        return service;
                    }]);

Then I have this configuration:

angular.module('myApp', [
    'ui.router',
    'ngCookies'
])
        .config(['$stateProvider', '$urlRouterProvider',
            function ($stateProvider, $urlRouterProvider) {
                $urlRouterProvider.otherwise('/resumen');
                $stateProvider
                        .state("dashboard", {
                            url: "/dashboard",
                            templateUrl: "partials/dashboard.html",
                            controller: "dashCtrl",
                            data: {
                                authRequired: true
                            }
                        })
                        .state("login", {
                            url: "/login",
                            templateUrl: "partials/login.html",
                            controller: "loginController"
                        })
            }])

        .run(['$rootScope', '$transitions', '$state', '$cookies', '$http', 'AuthService',
            function ($rootScope, $transitions, $state, $cookies, $http, AuthService) {

                // keep user logged in after page refresh
                $rootScope.globals = $cookies.get('globals') || {};
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals;

                $transitions.onStart({
                    to: function (state) {
                        return state.data != null && state.data.authRequired === true;
                    }
                }, function () {
                    if (!AuthService.isAuthenticated()) {
                        return $state.target("login");
                    }
                });
            }]);

You can see that I use

data: {
   authRequired: true
}

to mark the state only accessible if is authenticated.

then, on the .run I use the transitions to check the autheticated state

$transitions.onStart({
    to: function (state) {
        return state.data != null && state.data.authRequired === true;
    }
}, function () {
    if (!AuthService.isAuthenticated()) {
        return $state.target("login");
    }
});

I build this example using some code found on the $transitions documentation. I'm pretty new with the ui router but it works.

Hope it can helps anyone.

ES6 class variable alternatives

The way I solved this, which is another option (if you have jQuery available), was to Define the fields in an old-school object and then extend the class with that object. I also didn't want to pepper the constructor with assignments, this appeared to be a neat solution.

function MyClassFields(){
    this.createdAt = new Date();
}

MyClassFields.prototype = {
    id : '',
    type : '',
    title : '',
    createdAt : null,
};

class MyClass {
    constructor() {
        $.extend(this,new MyClassFields());
    }
};

-- Update Following Bergi's comment.

No JQuery Version:

class SavedSearch  {
    constructor() {
        Object.assign(this,{
            id : '',
            type : '',
            title : '',
            createdAt: new Date(),
        });

    }
}

You still do end up with 'fat' constructor, but at least its all in one class and assigned in one hit.

EDIT #2: I've now gone full circle and am now assigning values in the constructor, e.g.

class SavedSearch  {
    constructor() {
        this.id = '';
        this.type = '';
        this.title = '';
        this.createdAt = new Date();
    }
}

Why? Simple really, using the above plus some JSdoc comments, PHPStorm was able to perform code completion on the properties. Assigning all the vars in one hit was nice, but the inability to code complete the properties, imo, isn't worth the (almost certainly minuscule) performance benefit.

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

Remove local git tags that are no longer on the remote repository

this is a good method:

git tag -l | xargs git tag -d && git fetch -t

Source: demisx.GitHub.io

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

How to concatenate string variables in Bash

foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World

In general to concatenate two variables you can just write them one after another:

a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World

How to split an integer into an array of digits?

Strings are just as iterable as arrays, so just convert it to string:

str(12345)

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

Use [] instead of () as below example.

SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
            DataTable data = new DataTable();
            DataSet ds = new DataSet();

iPhone SDK on Windows (alternative solutions)

There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.

How to generate UML diagrams (especially sequence diagrams) from Java code?

Another modelling tool for Java is (my) website GitUML. Generate UML diagrams from Java or Python code stored in GitHub repositories.

One key idea with GitUML is to address one of the problems with "documentation": that diagrams are always out of date. With GitUML, diagrams automatically update when you push code using git.

Browse through community UML diagrams, there are some Java design patterns there. Surf through popular GitHub repositories and visualise the architectures and patterns in them.

diagram browser

Create diagrams using point and click. There is no drag drop editor, just click on the classes in the repository tree that you want to visualise:

select the java classes you want to visualise

The underlying technology is PlantUML based, which means you can refine your diagrams with additional PlantUML markup.

Single Line Nested For Loops

Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops

for x in range(1, 10, 1):
     for y in range(1,x):
             print y,
        print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

Match two strings in one line with grep

grep -i -w 'string1\|string2' filename

This works for exact word match and matching case insensitive words ,for that -i is used

How do I enable logging for Spring Security?

Assuming you're using Spring Boot, another option is to put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

logging:
  level:
    org:
      springframework:
        security: DEBUG

Check if property has attribute

There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));

If you need to retrieve attribute properties then

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
    // Use attr[0], you'll need foreach on attr if MultiUse is true
}

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

Upload files with HTTPWebrequest (multipart/form-data)

something like this is close: (untested code)

byte[] data; // data goes here.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = userNetworkCredentials;
request.Method = "PUT";
request.ContentType = "application/octet-stream";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data,0,data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
temp = reader.ReadToEnd();
reader.Close();

Full-screen responsive background image

I would say, in your layout file give a

<div id="background"></div>

and then in your css do

#background {
 position: fixed;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -100;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
  background: image-url('background.png') no-repeat;
  background-size: cover;
}

And be sure to have the background image in your app/assets/images and also change the

background: image-url('background.png') no-repeat;

'background.png' to your own background pic.

How to enable MySQL Query Log?

First, Remember that this logfile can grow very large on a busy server.

For mysql < 5.1.29:

To enable the query log, put this in /etc/my.cnf in the [mysqld] section

log   = /path/to/query.log  #works for mysql < 5.1.29

Also, to enable it from MySQL console

SET general_log = 1;

See http://dev.mysql.com/doc/refman/5.1/en/query-log.html

For mysql 5.1.29+

With mysql 5.1.29+ , the log option is deprecated. To specify the logfile and enable logging, use this in my.cnf in the [mysqld] section:

general_log_file = /path/to/query.log
general_log      = 1

Alternately, to turn on logging from MySQL console (must also specify log file location somehow, or find the default location):

SET global general_log = 1;

Also note that there are additional options to log only slow queries, or those which do not use indexes.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

I was facing the same issue and fixed it with this command. It works for me, please update it as per your account. This is for Ubuntu machine where AWS-CLI needs to be installed with Docker

algorithm_name='multi-model-xgboost'

account=$(aws sts get-caller-identity --query Account --output text)

# Get the region defined in the current configuration
region=$(aws configure get region)

aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

In regards to deleting the symbolic links, I found this to be useful.

find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

Databound drop down list - initial value

Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.

If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though

Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As    System.EventArgs) Handles DepartmentDropDownList.DataBound
    If Not Page.IsPostBack Then
        DepartmentDropDownList.SelectedValue = "somevalue"
    End If
End Sub

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

Correct Way to Load Assembly, Find Class and Call Run() Method

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

So instead of the answer given previously:

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

I would suggest the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

Now you can unload the assembly and have different security settings.

If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information, see this article on Add-ins and Extensibility on MSDN.

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

JQuery - Storing ajax response into global variable

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

I tried many, many, many different methods, but in the end, it was Charles Guilbert's method that worked best for me.

Hats off to Charles Guilbert! Using his answer, I am able to get data into my variables, even when my page first loads.

Here's an example of the working script:

    jQuery.extend
    (
        {
            getValues: function(url) 
            {
                var result = null;
                $.ajax(
                    {
                        url: url,
                        type: 'get',
                        dataType: 'html',
                        async: false,
                        cache: false,
                        success: function(data) 
                        {
                            result = data;
                        }
                    }
                );
               return result;
            }
        }
    );

    // Option List 1, when "Cats" is selected elsewhere
    optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

    // Option List 1, when "Dogs" is selected elsewhere
    optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

    // Option List 2, when "Cats" is selected elsewhere
    optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

    // Option List 2, when "Dogs" is selected elsewhere
    optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");

Bootstrap 4 - Inline List?

Inline

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>


<ul class="list-inline">
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
_x000D_
_x000D_

and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

PostgreSQL: role is not permitted to log in

Using pgadmin4 :

  1. Select roles in side menu
  2. Select properties in dashboard.
  3. Click Edit and select privileges

Now there you can enable or disable login, roles and other options

How to check for changes on remote (origin) Git repository

One potential solution

Thanks to Alan Haggai Alavi's solution I came up with the following potential workflow:

Step 1:

git fetch origin

Step 2:

git checkout -b localTempOfOriginMaster origin/master
git difftool HEAD~3 HEAD~2
git difftool HEAD~2 HEAD~1
git difftool HEAD~1 HEAD~0

Step 3:

git checkout master
git branch -D localTempOfOriginMaster
git merge origin/master

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

How to disable scrolling temporarily?

Do it simply by adding a class to the body:

.stop-scrolling {
  height: 100%;
  overflow: hidden;
}

Add the class then remove when you want to re-enable scrolling, tested in IE, FF, Safari and Chrome.

$('body').addClass('stop-scrolling')

For mobile devices, you'll need to handle the touchmove event:

$('body').bind('touchmove', function(e){e.preventDefault()})

And unbind to re-enable scrolling. Tested in iOS6 and Android 2.3.3

$('body').unbind('touchmove')

how to create virtual host on XAMPP

Add this Code in C:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName qa-staging.com
ServerAlias www.qa-staging.com
<Directory "c:/xampp/htdocs">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

Now Add your virtual host name in bellow file.

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 qa-staging.com

If you are not able to save this code in host file then right click on notpad select Run as administrator and then you can able to save your custom code now restart your XAMP

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How can I install a .ipa file to my iPhone simulator

Update for Xcode 9.4.1+

Hope my answer is getting seen down here as this took me a while to figure out but I just got it working.

First of all you need to build and run the App on your simulator. Then you open the Activity Monitor. Double click the name of your App to find its content.

enter image description here

In the next screen open the Open Files and Ports tab and find the line with MyAppName.app/MyAppName.

enter image description here

Copy the link but make sure to stop at the MyAppName.app. Do not copy the path following it.

Control click onto the finder icon and select Go to folder.

enter image description here]

Paste the path and click enter. You will see your MyAppName.app file. Copy it to the Desktop and zip it. Move it to your desired 2nd computer and unzip the file. Build a random project to have a simulator open.

Lastly: Literally drag and drop the App from your Desktop into your Simulator. You will see the install and the App opens and does not crash.

enter image description here

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

I can't find my git.exe file in my Github folder

The git.exe from Github for windows is located in a path like C:\Users\<username>\AppData\Local\GitHub\PortableGit_<numbersandletters>\bin\git.exe1 You have to replace <username> and <numbersandletters> to the actual situation on your system.

In Android Studio you can specify the path to the Git executable at File->Settings...->Version Control->Git->Path to Git executable. Here you have to include the actual executable name. As an example, in my case the actual path is: C:\Users\dennis\AppData\Local\GitHub\PortableGit_69703d1db91577f4c666e767a6ca5ec50a48d243\bin\git.exe

Edit: Last git update has put the git.exe file in cmd\ folder instead of bin\ . so now the actual path will be as suggested in the comment below by al3xAndr3w.

C:\Users\<username>\AppData\Local\GitHub\PortableGit_<numbersandletters>\cmd\git.exe

Create code first, many to many, with additional fields in association table

One way to solve this error is to put the ForeignKey attribute on top of the property you want as a foreign key and add the navigation property.

Note: In the ForeignKey attribute, between parentheses and double quotes, place the name of the class referred to in this way.

enter image description here

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

JavaScript or jQuery browser back button click detector

Disable the url button by following function

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
};

How to read a value from the Windows registry

This console app will list all the values and their data from a registry key for most of the potential registry values. There's some weird ones not often used. If you need to support all of them, expand from this example while referencing this Registry Value Type documentation.

Let this be the registry key content you can import from a .reg file format:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\added\subkey]
"String_Value"="hello, world!"
"Binary_Value"=hex:01,01,01,01
"Dword value"=dword:00001224
"QWord val"=hex(b):24,22,12,00,00,00,00,00
"multi-line val"=hex(7):4c,00,69,00,6e,00,65,00,20,00,30,00,00,00,4c,00,69,00,\
  6e,00,65,00,20,00,31,00,00,00,4c,00,69,00,6e,00,65,00,20,00,32,00,00,00,00,\
  00
"expanded_val"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,\
  00,4c,00,45,00,25,00,5c,00,6e,00,65,00,77,00,5f,00,73,00,74,00,75,00,66,00,\
  66,00,00,00

The console app itself:

#include <Windows.h>
#include <iostream>
#include <string>
#include <locale>
#include <vector>
#include <iomanip>

int wmain()
{
    const auto hKey = HKEY_CURRENT_USER;
    constexpr auto lpSubKey = TEXT("added\\subkey");
    auto openedKey = HKEY();
    auto status = RegOpenKeyEx(hKey, lpSubKey, 0, KEY_READ, &openedKey);

    if (status == ERROR_SUCCESS) {
        auto valueCount = static_cast<DWORD>(0);
        auto maxNameLength = static_cast<DWORD>(0);
        auto maxValueLength = static_cast<DWORD>(0);
        status = RegQueryInfoKey(openedKey, NULL, NULL, NULL, NULL, NULL, NULL,
            &valueCount, &maxNameLength, &maxValueLength, NULL, NULL);

        if (status == ERROR_SUCCESS) {
            DWORD type = 0;
            DWORD index = 0;
            std::vector<wchar_t> valueName = std::vector<wchar_t>(maxNameLength + 1);
            std::vector<BYTE> dataBuffer = std::vector<BYTE>(maxValueLength);

            for (DWORD index = 0; index < valueCount; index++) {
                DWORD charCountValueName = static_cast<DWORD>(valueName.size());
                DWORD charBytesData = static_cast<DWORD>(dataBuffer.size());
                status = RegEnumValue(openedKey, index, valueName.data(), &charCountValueName,
                    NULL, &type, dataBuffer.data(), &charBytesData);

                if (type == REG_SZ) {
                    const auto reg_string = reinterpret_cast<wchar_t*>(dataBuffer.data());
                    std::wcout << L"Type: REG_SZ" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData : " << reg_string << std::endl;
                }
                else if (type == REG_EXPAND_SZ) {
                    const auto casted = reinterpret_cast<wchar_t*>(dataBuffer.data());
                    TCHAR buffer[32000];
                    ExpandEnvironmentStrings(casted, buffer, 32000);
                    std::wcout << L"Type: REG_EXPAND_SZ" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData: " << buffer << std::endl;
                }
                else if (type == REG_MULTI_SZ) {
                    std::vector<std::wstring> lines;
                    const auto str = reinterpret_cast<wchar_t*>(dataBuffer.data());
                    auto line = str;
                    lines.emplace_back(line);
                    for (auto i = 0; i < charBytesData / sizeof(wchar_t) - 1; i++) {
                        const auto c = str[i];
                        if (c == 0) {
                            line = str + i + 1;
                            const auto new_line = reinterpret_cast<wchar_t*>(line);
                            if (wcsnlen_s(new_line, 1024) > 0)
                                lines.emplace_back(new_line);
                        }
                    }
                    std::wcout << L"Type: REG_MULTI_SZ" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData: " << std::endl;
                    for (size_t i = 0; i < lines.size(); i++) {
                        std::wcout << L"\t\tLine[" << i + 1 << L"]: " << lines[i] << std::endl;
                    }
                }
                if (type == REG_DWORD) {
                    const auto dword_value = reinterpret_cast<unsigned long*>(dataBuffer.data());
                    std::wcout << L"Type: REG_DWORD" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData : " << std::to_wstring(*dword_value) << std::endl;
                }
                else if (type == REG_QWORD) {
                    const auto qword_value = reinterpret_cast<unsigned long long*>(dataBuffer.data());
                    std::wcout << L"Type: REG_DWORD" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData : " << std::to_wstring(*qword_value) << std::endl;
                }
                else if (type == REG_BINARY) {
                    std::vector<uint16_t> bins;
                    for (auto i = 0; i < charBytesData; i++) {
                        bins.push_back(static_cast<uint16_t>(dataBuffer[i]));
                    }
                    std::wcout << L"Type: REG_BINARY" << std::endl;
                    std::wcout << L"\tName: " << valueName.data() << std::endl;
                    std::wcout << L"\tData:";
                    for (size_t i = 0; i < bins.size(); i++) {
                        std::wcout << L" " << std::uppercase << std::hex << \
                            std::setw(2) << std::setfill(L'0') << std::to_wstring(bins[i]);
                    }
                    std::wcout << std::endl;
                }
            }
        }
    }

    RegCloseKey(openedKey);
    return 0;
}

Expected console output:

Type: REG_SZ
        Name: String_Value
        Data : hello, world!
Type: REG_BINARY
        Name: Binary_Value
        Data: 01 01 01 01
Type: REG_DWORD
        Name: Dword value
        Data : 4644
Type: REG_DWORD
        Name: QWord val
        Data : 1188388
Type: REG_MULTI_SZ
        Name: multi-line val
        Data:
                Line[1]: Line 0
                Line[2]: Line 1
                Line[3]: Line 2
Type: REG_EXPAND_SZ
        Name: expanded_val
        Data: C:\Users\user name\new_stuff

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Use the following script to find and kill all the opened connections to the database before restoring database.

declare @sql as varchar(20), @spid as int

select @spid = min(spid)  from master..sysprocesses  where dbid = db_id('<database_name>') 
and spid != @@spid    

while (@spid is not null)
begin
    print 'Killing process ' + cast(@spid as varchar) + ' ...'
    set @sql = 'kill ' + cast(@spid as varchar)
    exec (@sql)

    select 
        @spid = min(spid)  
    from 
        master..sysprocesses  
    where 
        dbid = db_id('<database_name>') 
        and spid != @@spid
end 

print 'Process completed...'

Hope this will help...

insert a NOT NULL column to an existing table

Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL. If you don't allow NULL, and don't have a default, what is the value going to be?

Since SQL Server supports ADD CONSTRAINT, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL constraint after you've filled it with non-NULL values.

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;
}

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}

rails generate model

The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.

The normal way to get there from scratch is:

$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
    name:string \ 
    description:text \
    price:decimal \
    seller_id:integer \
    email:string img_url:string

View array in Visual Studio debugger?

I use the ArrayDebugView add-in for Visual Studio (http://arraydebugview.sourceforge.net/).

It seems to be a long dead project (but one I'm looking at continuing myself) but the add-in still works beautifully for me in VS2010 for both C++ and C#.

It has a few quirks (tab order, modal dialog, no close button) but the ability to plot the contents of an array in a graph more than make up for it.

Edit July 2014: I have finally built a new Visual Studio extension to replace ArrayebugView's functionality. It is available on the VIsual Studio Gallery, search for ArrayPlotter or go to http://visualstudiogallery.msdn.microsoft.com/2fde2c3c-5b83-4d2a-a71e-5fdd83ce6b96?SRC=Home

How do I set up NSZombieEnabled in Xcode 4?

Cocoa offers a cool feature which greatly enhances your capabilities to debug such situations. It is an environment variable which is called NSZombieEnabled, watch this video that explains setting up NSZombieEnabled in objective-C

Jquery Ajax, return success/error from mvc.net controller

 $.ajax({
    type: "POST",
    data: formData,
    url: "/Forms/GetJobData",
    dataType: 'json',
    contentType: false,
    processData: false,               
    success: function (response) {
        if (response.success) {
            alert(response.responseText);
        } else {
            // DoSomethingElse()
            alert(response.responseText);
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }

});

Controller:

[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
    var mimeType = jobData.File.ContentType;
    var isFileSupported = IsFileSupported(mimeType);

    if (!isFileSupported){        
         //  Send "false"
        return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        //  Send "Success"
        return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
    }   
}

---Supplement:---

basically you can send multiple parameters this way:

Controller:

 return Json(new { 
                success = true,
                Name = model.Name,
                Phone = model.Phone,
                Email = model.Email                                
            }, 
            JsonRequestBehavior.AllowGet);

Html:

<script> 
     $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                contentType: 'application/json; charset=utf-8',            
                success: function (response) {

                   if(response.success){ 
                      console.log(response.Name);
                      console.log(response.Phone);
                      console.log(response.Email);
                    }


                },
                error: function (response) {
                    alert("error!"); 
                }
            });

Simple http post example in Objective-C?

I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...

the objective-c part (coded following Chris' protocol methodo)

// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];

// Specify that it will be a POST request
request.HTTPMethod = @"POST";

// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:nil error:nil];

NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);

Below the php part :

if (isset($_POST['user_name'],$_POST['password'])) 

{

// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else 
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];

$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username',   '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";

mysqli_close($con2);

}
}
else
{
echo "No data input in php";
}

I have been stuck the last days on this one.

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

The problem I had was because I had made a database in my LocalDb.
If that's the case then you have to write is as shown below:

    "SELECT * FROM <DatabaseName>.[dbo].[Projects]"

Replace with your database name.
You can probably also drop the "[ ]"

Session timeout in ASP.NET

Since ASP.Net core 1.0 (vNext or whatever name is used for it) sessions are implemented differently. I changed the session timeout value in Startup.cs, void ConfigureServices using:

services.AddSession(options => options.IdleTimeout = TimeSpan.FromSeconds(42));

Or if you want to use the appsettings.json file, you can do something like:

// Appsettings.json
"SessionOptions": {
    "IdleTimeout": "00:30:00"
}

// Startup.cs
services.AddSession(options => options.IdleTimeout = TimeSpan.Parse(Config.GetSection("SessionOptions")["IdleTimeout"]));

php hide ALL errors

The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!

If you want to hide them anyway: error_reporting(0);

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.

At least then it's only in once place if you need to later refactor.

ggplot2: sorting a plot

I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .

As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.

I get the desired result by adding + xlim(rev(levels(x$variable))) to the ggplot statement:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))

This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim() should work in general.

Executing periodic actions in Python

At the end of foo(), create a Timer which calls foo() itself after 10 seconds.
Because, Timer create a new thread to call foo().
You can do other stuff without being blocked.

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011

What is an API key?

It looks like that many people use API keys as a security solution. The bottom line is: Never treat API keys as secret it is not. On https or not, whoever can read the request can see the API key and can make whatever call they want. An API Key should be just as a 'user' identifier as its not a complete security solution even when used with ssl.

The better description is in Eugene Osovetsky link to: When working with most APIs, why do they require two types of authentication, namely a key and a secret? Or check http://nordicapis.com/why-api-keys-are-not-enough/

Instance member cannot be used on type

It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).

You can make your instance variable a class variable by adding static/class attribute.

You instantiate an instance of your class and call the instance method on that variable.

Cannot find Microsoft.Office.Interop Visual Studio

I think you need to run that .msi to install the dlls. After I ran that .msi I can go to (VS 2012) Add References > Assemblies > Extensions and all of the Microsoft.Office.Interop dlls are there.

On my computer the dlls are found in "c:\Program Files(x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA" so you could check in a similar/equivalent directory on yours just to make sure they're not there?

How to show loading spinner in jQuery?

This is the best way for me:

jQuery:

$(document).ajaxStart(function() {
  $(".loading").show();
});

$(document).ajaxStop(function() {
  $(".loading").hide();
});

Coffee:

  $(document).ajaxStart ->
    $(".loading").show()

  $(document).ajaxStop ->
    $(".loading").hide()

Docs: ajaxStart, ajaxStop

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

Get and Set a Single Cookie with Node.js HTTP Server

var cookie = 'your_cookie';
var cookie_value;
var i = request.headers.indexOf(cookie+'=');
if (i != -1) {
  var eq = i+cookie.length+1;
  var end = request.headers.indexOf(';', eq);
  cookie_value = request.headers.substring(eq, end == -1 ? undefined : end);
}

INSERT INTO...SELECT for all MySQL columns

don't you need double () for the values bit? if not try this (although there must be a better way

insert into this_table_archive (id, field_1, field_2, field_3) 
values
((select id from this_table where entry_date < '2001-01-01'), 
((select field_1 from this_table where entry_date < '2001-01-01'), 
((select field_2 from this_table where entry_date < '2001-01-01'), 
((select field_3 from this_table where entry_date < '2001-01-01'));

How to show what a commit did?

I found out that "git show --stat" is the best out of all here, gives you a brief summary of the commit, what files did you add and modify without giving you whole bunch of stuff, especially if you changed a lot files.

'npm' is not recognized as internal or external command, operable program or batch file

If you used ms build tools to install node the path is here:

C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Microsoft\VisualStudio\NodeJs

Passing by reference in C

pointers and references are two different thigngs.

A couple of things I have not seen mentioned.

A pointer is the address of something. A pointer can be stored and copied like any other variable. It thus have a size.

A reference should be seen as an ALIAS of something. It does not have a size and cannot be stored. It MUST reference something, ie. it cannot be null or changed. Well, sometimes the compiler needs to store the reference as a pointer, but that is an implementation detail.

With references you don't have the issues with pointers, like ownership handling, null checking, de-referencing on use.

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

Change string color with NSAttributedString?

With Swift 4, NSAttributedStringKey has a static property called foregroundColor. foregroundColor has the following declaration:

static let foregroundColor: NSAttributedStringKey

The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an NSAttributedString instance with foregroundColor:

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)

The code below shows a possible UIViewController implementation that relies on NSAttributedString in order to update the text and text color of a UILabel from a UISlider:

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)
        }
    }

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display
            updateDisplay()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display
        updateDisplay()
    }

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)
    }

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status
    }

}

Note however that you don't really need to use NSAttributedString for such an example and can simply rely on UILabel's text and textColor properties. Therefore, you can replace your updateDisplay() implementation with the following code:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)
}

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

Regex for not empty and not whitespace

In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:

(.|\s)*\S(.|\s)*

- this matches any string containing at least one non-whitespace character (the \S in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*.

You can try it with explanation on https://regex101.com/.

Parsing Query String in node.js

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

How to return an array from a function?

"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"

template <class X>
  class Array
{
  X     *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(X* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new X [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(X));
            return m_size;
        }
       return 0;
    }
}; 

just for int

class IntArray
{
  int   *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(int* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new int [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(int));
            return m_size;
        }
       return 0;
    }
}; 

example

Array<float> array;
float  *n_data = NULL;
int     data_size;
if(data_size = array.Get(n_data))
{     // work with array    }

delete [] n_data;

example for int

IntArray   array;
int       *n_data = NULL;
int        data_size;
if(data_size = array.Get(n_data))
{  // work with array  }

delete [] n_data;

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

Is nested function a good approach when required by only one function?

Generally, no, do not define functions inside functions.

Unless you have a really good reason. Which you don't.

Why not?

What is a really good reason to define functions inside functions?

When what you actually want is a dingdang closure.

Get first day of week in PHP?

Here I am considering Sunday as first & Saturday as last day of the week.

$m = strtotime('06-08-2012');  
$today =   date('l', $m);  
$custom_date = strtotime( date('d-m-Y', $m) );   
if ($today == 'Sunday') {  
   $week_start = date("d-m-Y", $m);  
} else {  
  $week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));  
}  

if ($today == 'Saturday') {  
  $week_end = date("d-m-Y", $m);
} else {  
  $week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));  
}
echo '<br>Start: '. $week_start;  
echo '<br>End: '. $week_end;  

Output :

Start: 05-08-2012
End: 11-08-2012

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..

Python copy files to a new directory and rename if file name already exists

I always use the time-stamp - so its not possible, that the file exists already:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)

Adding 1 hour to time variable

Beware of adding 3600!! may be a problem on day change because of unix timestamp format uses moth before day.

e.g. 2012-03-02 23:33:33 would become 2014-01-13 13:00:00 by adding 3600 better use mktime and date functions they can handle this and things like adding 25 hours etc.

How to write loop in a Makefile?

This is not really a pure answer to the question, but an intelligent way to work around such problems:

instead of writing a complex file, simply delegate control to for instance a bash script like: makefile

foo : bar.cpp baz.h
    bash script.sh

and script.sh looks like:

for number in 1 2 3 4
do
    ./a.out $number
done

jQuery UI " $("#datepicker").datepicker is not a function"

Old question - newer version of .NET (4.5.6) - same issue - new answer

Using NuGet

Make sure you have the following installed via NuGet:

  • jQuery
  • AspNet.ScriptManager.jQuery
  • jQuery.UI.Combined
  • AspNet.ScriptManager.jQuery.UI.Combined

Install them from here [ Tools > NuGet Package Manager > Manage NuGet Packages for Solution ]

Then, jquery and jquery.ui.combined should be added to your ScriptManager in Site.Master. Will look something like this:

    <asp:ScriptManager runat="server">
        <Scripts>
            <%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%>
            <%--Framework Scripts--%>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="jquery.ui.combined" />
            <asp:ScriptReference Name="bootstrap" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
            <%--Site Scripts--%>
        </Scripts>
    </asp:ScriptManager>

This solved my same issue. Thank you.

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

You'll either have to upgrade the .NET 2 project to .NET 4, or downgrade the .NET 4 project to .NET 3.5 (or earlier).

How do you upgrade the .net version? I am not sure where to and what to specify. Please help.

Edit: I found the answer myself. Select the project, right click and choose Property Pages. There you can select framework version. or select the project and click Shift+F4

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

After installing with pip, "jupyter: command not found"

Most generally (in case of jupyter not being in /local/bin) use,

which jupyter

Example output

~/miniconda3/bin/jupyter

to see the path for jupyter, then explicitly use that path with sudo

sudo ~/miniconda3/bin/jupyter 

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.

Demo: jsfiddle.net/KcdpW

HTML:

<ul>
    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>
</ul>?

CSS:

ul {
    width: 10em
}
.right {
    float: right
}?

Styling Password Fields in CSS

The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022.

As you can see, even in the StackOverflow font the two characters have different sizes.

The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.

The simple solution is to use a font in which both characters have similar sizes.

The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:

input[type="password"] {
    font-family: caption;
}

2D arrays in Python

I would suggest that you use a dictionary like so:

arr = {}

arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)

print(arr[1])
>>> (1, 2, 4)

If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Using OR operator in a jquery if statement

The code you wrote will always return true because state cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15).... AND is what you need not OR.

Use $.inArray instead. This returns the index of the element in the array.

JSFIDDLE DEMO

var statesArray = [10, 15, 19]; // list out all

var index = $.inArray(state, statesArray);

if(index == -1) {
    console.log("Not there in array");
    return true;

} else {
    console.log("Found it");
    return false;
}

selected value get from db into dropdown select box option using php mysql error

Answer is simple. when u pass value from dropdown.

Just use as if else.

for eg:

foreach($result as $row) {                      
   $GLOBALS['output'] .='<option value="'.$row["dropdownid"].'"'. 
   ($GLOBALS['passselectedvalueid']==$row["dropwdownid"] ? ' Selected' : '').' 
   >'.$row['valueetc'].'</option>';
}

Get MD5 hash of big files in Python

A remix of Bastien Semene code that take Hawkwing comment about generic hashing function into consideration...

def hash_for_file(path, algorithm=hashlib.algorithms[0], block_size=256*128, human_readable=True):
    """
    Block size directly depends on the block size of your filesystem
    to avoid performances issues
    Here I have blocks of 4096 octets (Default NTFS)

    Linux Ext4 block size
    sudo tune2fs -l /dev/sda5 | grep -i 'block size'
    > Block size:               4096

    Input:
        path: a path
        algorithm: an algorithm in hashlib.algorithms
                   ATM: ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
        block_size: a multiple of 128 corresponding to the block size of your filesystem
        human_readable: switch between digest() or hexdigest() output, default hexdigest()
    Output:
        hash
    """
    if algorithm not in hashlib.algorithms:
        raise NameError('The algorithm "{algorithm}" you specified is '
                        'not a member of "hashlib.algorithms"'.format(algorithm=algorithm))

    hash_algo = hashlib.new(algorithm)  # According to hashlib documentation using new()
                                        # will be slower then calling using named
                                        # constructors, ex.: hashlib.md5()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(block_size), b''):
             hash_algo.update(chunk)
    if human_readable:
        file_hash = hash_algo.hexdigest()
    else:
        file_hash = hash_algo.digest()
    return file_hash

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Check whether $_POST-value is empty

Question: Check whether a $_POST value is empty.

Translation: Check to see if an array key/index has a value associated with it.

Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.

1. Some people say use empty().

From the PHP Manual:

"[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."

The following are thus considered empty.

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

If none of these values are valid for your input control, then empty() would work. The problem here is that empty() might be too broad to be used consistently (the same way, for the same reason, on different input control submissions to $_POST or $_GET). A good use of empty() is to check if an entire array is empty (has no elements).

2. Some people say use isset().

isset() (a language construct) cannot operate on entire arrays, as in isset($myArray). It can only operate on variables and array elements (via the index/key): isset($var) and isset($_POST['username']). The isset()language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.

In short, the most accurate check can be accomplished best with isset(), as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset() to check if a $_POST key has no value associated with it (and that is not NULL). isset()is a much stricter test of emptiness (in the sense of your question) than empty().

3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.

You can test anything that evaluates to true or false in an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with empty(), many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.

--Doyle, Beginning PHP 5.3

In conclusion, use isset() and consider combining it with other tests. Example:

May not work due to superglobal screwiness, but would work for other arrays without question.

if (is_array($_POST) && !empty($_POST)) {
    // Now test for your successful controls in $_POST with isset()
} 

Hence, why look for a value associated with a key before you even know for sure that $_POST represents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POST only has the allowed keys, but that conversation is for another day.

Useful reference:

PHP Manual: Type Testing Comparison Tables

angular 2 sort and filter

This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.

I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.

<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>

This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby

EDIT 2: Updated ngFor to new syntax

What is %timeit in python?

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

Check if an apt-get package is installed and then install it if it's not on Linux

This one-liner returns 1 (installed) or 0 (not installed) for the 'nano' package..

$(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed")

even if the package does not exist / is not available.

The example below installs the 'nano' package if it is not installed..

if [ $(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed") -eq 0 ];
then
  apt-get install nano;
fi

Change the Arrow buttons in Slick slider

Here is my example of how to change the arrows for Slick Carousel in React to anything you would like. First you need to set the nextArrow and prevArrow in settings to a function then return a div in that function with whatever icon you would like to use. For mine I used Font Awesome. Then you will need to add a className in your icon, you will see that in the NextArrow and PrevArrow functions. Then add the scss code to customize whatever you would like.

JSX Code:

function NextArrow(props) {
  const { style, onClick } = props;
  return (
    <div style={{ ...style, display: "block" }} onClick={onClick}>
      <FontAwesomeIcon icon={faChevronRight} size="3x" className="slick-arrow-icon-right" />
    </div>
  );
}

function PrevArrow(props) {
  const { style, onClick } = props;
  return (
    <div style={{ ...style, display: "block" }} onClick={onClick}>
      <FontAwesomeIcon icon={faChevronLeft} size="3x" className="slick-arrow-icon-left" />
    </div>
  );
}

function SlickCarouselArrowChange(props) {
  var settings = {
    className: "slider variable-width",
    dots: true,
    infinite: true,
    centerMode: true,
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    autoplay: true,
    autoplaySpeed: 2000,
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
  };

  return (
    <div className="slick-slider">
      <Slider {...settings}>
        {props.searchResults.map((image, index) => (
          <div key={index}>
            <img src={image.urls.small} />{" "}
          </div>
        ))}
      </Slider>
    </div>
  );
}

SCSS Code:

.slick-arrow-icon-left,
.slick-arrow-icon-right {
  position: absolute;
  display: block;
  cursor: pointer;
  background: transparent;
  color: black;
  top: 50%;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  transform: translate(0, -50%);
  padding: 0;
  border: none;
  outline: none;
  transition: 0.5s ease-in-out;
  &:hover,
  &:focus {
    outline: none;
    background: transparent;
    color: black;
    font-size: 40px;
    &::before {
      opacity: 1;
    }
  }
}

.slick-arrow-icon-left {
  left: -50px;
  [dir="rtl"] & {
    left: auto;
    right: -50px;
  }
}

.slick-arrow-icon-right {
  right: -50px;
  [dir="rtl"] & {
    left: -50px;
    right: auto;
  }
}

Example Link:

https://slick-carousel-arrow-change.herokuapp.com/

Source Code:

https://github.com/Apocilyptica/slick-carousel-arrow-change

How do I change JPanel inside a JFrame on the fly?

frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.

Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.

Also note JFrame is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.

From the linked documentation:

Checks if a String is whitespace, empty ("") or null.

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

For comparison StringUtils.isEmpty:

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.

java.lang.String.isBlank() (since Java 11)

java.lang.String.isEmpty()

Android marshmallow request permission?

I have used this wrapper (Recommended) written by google developers. Its super easy to use.

https://github.com/googlesamples/easypermissions

Function dealing with checking and ask for permission if required

public void locationAndContactsTask() {
    String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS };
    if (EasyPermissions.hasPermissions(this, perms)) {
        // Have permissions, do the thing!
        Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
    } else {
        // Ask for both permissions
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                RC_LOCATION_CONTACTS_PERM, perms);
    }
}

Happy coding :)

Event system in Python

I use zope.event. It's the most bare bones you can imagine. :-) In fact, here is the complete source code:

subscribers = []

def notify(event):
    for subscriber in subscribers:
        subscriber(event)

Note that you can't send messages between processes, for example. It's not a messaging system, just an event system, nothing more, nothing less.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

T-SQL loop over query results

You could use a CURSOR in this case:

DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR

SET @getid = CURSOR FOR
SELECT table.id,
       table.name
FROM   table

OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
    FETCH NEXT
    FROM @getid INTO @id, @name
END

CLOSE @getid
DEALLOCATE @getid

Modified to show multiple parameters from the table.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How to insert pandas dataframe via mysqldb into database?

You might output your DataFrame as a csv file and then use mysqlimport to import your csv into your mysql.

EDIT

Seems pandas's build-in sql util provide a write_frame function but only works in sqlite.

I found something useful, you might try this

What is meant by Ems? (Android TextView)

android:ems or setEms(n) sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. See wikipedia Em unit

but only when the layout_width is set to "wrap_content". Other layout_width values override the ems width setting.

Adding an android:textSize attribute determines the physical width of the view to the textSize * length of a text of n 'M's set above.

Why is access to the path denied?

I got this error and solved it in just a moment. Don't know why all of my folders are read-only,I cancelled the read-only and apply it. However, it is still read-only. So I moved the file into the root folder, it works - so weird.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Check if image exists on server using JavaScript?

Basicaly a promisified version of @espascarello and @adeneo answers, with a fallback parameter:

_x000D_
_x000D_
const getImageOrFallback = (path, fallback) => {_x000D_
  return new Promise(resolve => {_x000D_
    const img = new Image();_x000D_
    img.src = path;_x000D_
    img.onload = () => resolve(path);_x000D_
    img.onerror = () => resolve(fallback);_x000D_
  });_x000D_
};_x000D_
_x000D_
// Usage:_x000D_
_x000D_
const link = getImageOrFallback(_x000D_
  'https://www.fillmurray.com/640/360',_x000D_
  'https://via.placeholder.com/150'_x000D_
  ).then(result => console.log(result) || result)_x000D_
_x000D_
// It can be also implemented using the async / await API.
_x000D_
_x000D_
_x000D_

Note: I may personally like the fetch solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if your file doesn't exist. This, on the other hand, will do the job.

Bootstrap 4: Multilevel Dropdown Inside Navigation

I found this multidrop-down menu which work great in all device.

Also, have hover style

It supports multi-level submenus with bootstrap 4.

_x000D_
_x000D_
$( document ).ready( function () {_x000D_
    $( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
        var $el = $( this );_x000D_
        var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
        $( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
        if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
            $el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
        }_x000D_
        $( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
        return false;_x000D_
    } );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
    color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
    padding: 10px 15px;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
    background: transparent;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
    transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
    </button>_x000D_
    <a class="navbar-brand" href="#">Navbar</a>_x000D_
    <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
        <ul class="navbar-nav">_x000D_
            <li class="nav-item active">_x000D_
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Features</a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Pricing</a>_x000D_
            </li>_x000D_
            <li class="nav-item dropdown">_x000D_
                <a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
                    <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
                    <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
                    <li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
                        <ul class="dropdown-menu">_x000D_
                            <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
                            <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                        </ul>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

I like Keith Hill's answer except it has a bug that prevents it from recursing past two levels. These commands manifest the bug:

New-Item level1/level2/level3/level4/foobar.txt -Force -ItemType file
cd level1
GetFiles . xyz | % { $_.fullname }

With Hill's original code you get this:

...\level1\level2
...\level1\level2\level3

Here is a corrected, and slightly refactored, version:

function GetFiles($path = $pwd, [string[]]$exclude)
{
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        $item
        if (Test-Path $item.FullName -PathType Container)
        {
            GetFiles $item.FullName $exclude
        }
    }
} 

With that bug fix in place you get this corrected output:

...\level1\level2
...\level1\level2\level3
...\level1\level2\level3\level4
...\level1\level2\level3\level4\foobar.txt

I also like ajk's answer for conciseness though, as he points out, it is less efficient. The reason it is less efficient, by the way, is because Hill's algorithm stops traversing a subtree when it finds a prune target while ajk's continues. But ajk's answer also suffers from a flaw, one I call the ancestor trap. Consider a path such as this that includes the same path component (i.e. subdir2) twice:

\usr\testdir\subdir2\child\grandchild\subdir2\doc

Set your location somewhere in between, e.g. cd \usr\testdir\subdir2\child, then run ajk's algorithm to filter out the lower subdir2 and you will get no output at all, i.e. it filters out everything because of the presence of subdir2 higher in the path. This is a corner case, though, and not likely to be hit often, so I would not rule out ajk's solution due to this one issue.

Nonetheless, I offer here a third alternative, one that does not have either of the above two bugs. Here is the basic algorithm, complete with a convenience definition for the path or paths to prune--you need only modify $excludeList to your own set of targets to use it:

$excludeList = @("stuff","bin","obj*")
Get-ChildItem -Recurse | % {
    $pathParts = $_.FullName.substring($pwd.path.Length + 1).split("\");
    if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $_ }
}

My algorithm is reasonably concise but, like ajk's, it is less efficient than Hill's (for the same reason: it does not stop traversing subtrees at prune targets). However, my code has an important advantage over Hill's--it can pipeline! It is therefore amenable to fit into a filter chain to make a custom version of Get-ChildItem while Hill's recursive algorithm, through no fault of its own, cannot. ajk's algorithm can be adapted to pipeline use as well, but specifying the item or items to exclude is not as clean, being embedded in a regular expression rather than a simple list of items that I have used.

I have packaged my tree pruning code into an enhanced version of Get-ChildItem. Aside from my rather unimaginative name--Get-EnhancedChildItem--I am excited about it and have included it in my open source Powershell library. It includes several other new capabilities besides tree pruning. Furthermore, the code is designed to be extensible: if you want to add a new filtering capability, it is straightforward to do. Essentially, Get-ChildItem is called first, and pipelined into each successive filter that you activate via command parameters. Thus something like this...

Get-EnhancedChildItem –Recurse –Force –Svn
    –Exclude *.txt –ExcludeTree doc*,man -FullName -Verbose 

... is converted internally into this:

Get-ChildItem | FilterExcludeTree | FilterSvn | FilterFullName

Each filter must conform to certain rules: accepting FileInfo and DirectoryInfo objects as inputs, generating the same as outputs, and using stdin and stdout so it may be inserted in a pipeline. Here is the same code refactored to fit these rules:

filter FilterExcludeTree()
{
  $target = $_
  Coalesce-Args $Path "." | % {
    $canonicalPath = (Get-Item $_).FullName
    if ($target.FullName.StartsWith($canonicalPath)) {
      $pathParts = $target.FullName.substring($canonicalPath.Length + 1).split("\");
      if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $target }
    }
  }
} 

The only additional piece here is the Coalesce-Args function (found in this post by Keith Dahlby), which merely sends the current directory down the pipe in the event that the invocation did not specify any paths.

Because this answer is getting somewhat lengthy, rather than go into further detail about this filter, I refer the interested reader to my recently published article on Simple-Talk.com entitled Practical PowerShell: Pruning File Trees and Extending Cmdlets where I discuss Get-EnhancedChildItem at even greater length. One last thing I will mention, though, is another function in my open source library, New-FileTree, that lets you generate a dummy file tree for testing purposes so you can exercise any of the above algorithms. And when you are experimenting with any of these, I recommend piping to % { $_.fullname } as I did in the very first code fragment for more useful output to examine.

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

Executing multiple SQL queries in one statement with PHP

You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.

The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.

Finally, I would suggest either using PDO or some other method.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I was facing the same issue, here is line from error

File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 260, in __getitem__

So i solve the issue by updating "npyio.py" file. In npyio.py line 196 assigning value to allow_pickle so i update this line as

self.allow_pickle = True

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

How to cast a double to an int in Java by rounding it down?

(int)99.99999

It will be 99. Casting a double to an int does not round, it'll discard the fraction part.

How to create named and latest tag in Docker?

You can have multiple tags when building the image:

$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .

Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t

Remove all whitespaces from NSString

stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle.

1) If you need to remove only a given character (say the space character) from your string, use:

[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]

2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet then joining the words again in one string:

NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:@""];

Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the stringByReplacingOccurrencesOfString:withString:. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method.

Where are shared preferences stored?

I just tried to get path of shared preferences below like this.This is work for me.

File f = getDatabasePath("MyPrefsFile.xml");

if (f != null)
    Log.i("TAG", f.getAbsolutePath());

Cannot install packages using node package manager in Ubuntu

You can also install Nodejs using NVM or Nodejs Version Manager There are a lot of benefits to using a version manager. One of them being you don't have to worry about this issue.


Instructions:


sudo apt-get update
sudo apt-get install build-essential libssl-dev

Once the prerequisite packages are installed, you can pull down the nvm installation script from the project's GitHub page. The version number may be different, but in general, you can download and install it with the following syntax:

curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | sh

This will download the script and run it. It will install the software into a subdirectory of your home directory at ~/.nvm. It will also add the necessary lines to your ~/.profile file to use the file.

To gain access to the nvm functionality, you'll need to log out and log back in again, or you can source the ~/.profile file so that your current session knows about the changes:

source ~/.profile

Now that you have nvm installed, you can install isolated Node.js versions.

To find out the versions of Node.js that are available for installation, you can type:

nvm ls-remote
. . .

v0.11.10
v0.11.11
v0.11.12
v0.11.13
v0.11.14

As you can see, the newest version at the time of this writing is v0.11.14. You can install that by typing:

nvm install 0.11.14

Usually, nvm will switch to use the most recently installed version. You can explicitly tell nvm to use the version we just downloaded by typing:

nvm use 0.11.14

When you install Node.js using nvm, the executable is called node. You can see the version currently being used by the shell by typing:

node -v

The comeplete tutorial can be found here

Can attributes be added dynamically in C#?

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

What is the scope of variables in JavaScript?

A very common issue not described yet that front-end coders often run into is the scope that is visible to an inline event handler in the HTML - for example, with

<button onclick="foo()"></button>

The scope of the variables that an on* attribute can reference must be either:

  • global (working inline handlers almost always reference global variables)
  • a property of the document (eg, querySelector as a standalone variable will point to document.querySelector; rare)
  • a property of the element the handler is attached to (like above; rare)

Otherwise, you'll get a ReferenceError when the handler is invoked. So, for example, if the inline handler references a function which is defined inside window.onload or $(function() {, the reference will fail, because the inline handler may only reference variables in the global scope, and the function is not global:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  function foo() {_x000D_
    console.log('foo running');_x000D_
  }_x000D_
});
_x000D_
<button onclick="foo()">click</button>
_x000D_
_x000D_
_x000D_

Properties of the document and properties of the element the handler is attached to may also be referenced as standalone variables inside inline handlers because inline handlers are invoked inside of two with blocks, one for the document, one for the element. The scope chain of variables inside these handlers is extremely unintuitive, and a working event handler will probably require a function to be global (and unnecessary global pollution should probably be avoided).

Since the scope chain inside inline handlers is so weird, and since inline handlers require global pollution to work, and since inline handlers sometimes require ugly string escaping when passing arguments, it's probably easier to avoid them. Instead, attach event handlers using Javascript (like with addEventListener), rather than with HTML markup.

_x000D_
_x000D_
function foo() {_x000D_
  console.log('foo running');_x000D_
}_x000D_
document.querySelector('.my-button').addEventListener('click', foo);
_x000D_
<button class="my-button">click</button>
_x000D_
_x000D_
_x000D_


On a different note, unlike normal <script> tags, which run on the top level, code inside ES6 modules runs in its own private scope. A variable defined at the top of a normal <script> tag is global, so you can reference it in other <script> tags, like this:

_x000D_
_x000D_
<script>_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
console.log(foo);_x000D_
</script>
_x000D_
_x000D_
_x000D_

But the top level of an ES6 module is not global. A variable declared at the top of an ES6 module will only be visible inside that module, unless the variable is explicitly exported, or unless it's assigned to a property of the global object.

_x000D_
_x000D_
<script type="module">_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
// Can't access foo here, because the other script is a module_x000D_
console.log(typeof foo);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The top level of an ES6 module is similar to that of the inside of an IIFE on the top level in a normal <script>. The module can reference any variables which are global, and nothing can reference anything inside the module unless the module is explicitly designed for it.

How to increase apache timeout directive in .htaccess?

This solution is for Litespeed Server (Apache as well)

Add the following code in .htaccess

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Litespeed reference

How to embed images in email

Here is how to get the code for an embedded image without worrying about any files or base64 statements or mimes (it's still base64, but you don't have to do anything to get it). I originally posted this same answer in this thread, but it may be valuable to repeat it in this one, too.

To do this, you need Mozilla Thunderbird, you can fetch the html code for an image like this:

  1. Copy a bitmap to clipboard.
  2. Start a new email message.
  3. Paste the image. (don't save it as a draft!!!)
  4. Double-click on it to get to the image settings dialogue.
  5. Look for the "image location" property.
  6. Fetch the code and wrap it in an image tag, like this:

You should end up with a string of text something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaIAAAGcCAIAAAAUGTPlAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAPbklEQVR4nO3d2ZbixhJAUeku//8vcx/oxphBaMgpIvd+c7uqmqakQ6QkxHq73RaA3tZ13fNlJ5K1yhzQy860fbS/XTIHtHOla9/8jJjMARXV6No332omc0BhLdP27r1pMgeU0bduz16yJnPAVeME7uG5bDIHxTzv7bn3rAG79u7xK/in7+OArNY14QwRom7v/tf7AUASQROw07qu4f6Bjwcsc1BLuC58FDFwD/dHbtEKtWwvWl/aMeAKN27dXpjmoIyLnRqtKaM9ntPWdTXNQRWHRrmhjPzYzjHNQXnnJrsR+jLCYyjONAej6Ht4LmXg7kxzUMahTAx1wiH0udQ9ZA6G0Ct8uQN3Z9EKBeyPxThvCJshcHcJ348CFx29ou1jLz7cDmikC+Xmadxi0Qo/XS/C+8EvjWvJohX+42gCtr9+56DX0myNW0xzsMeJNHw7falx7Znm4Lyj1ThxmK9gFuds3GKagxdfPzblr+c/afWgCoj1aMtyphVevZ8uKNKIc2ds93zjTzM3brFohXc1Xvs7zhOTN24xzcFOvWKR7P5OXTg2ByRnmoO9ak9GxXdGo9yyLLfbzTQHQ9C4ekxzcECNdtTYBzXu7v7cmubggOJJMmc0IHPQTaXGGeXuHk+v6+agg3pDnMa9M83BAW3eDsF1z0+yzMFe4zfOKPeRzEFT9UqkcQ8vryUyB7sUjEiNHmncBqcg4LfiEbn/wPd7nzhsd937c2iagx9aLjPP/V1GuW2mOdhSqiCPEaPSYMjdx3FY5uCr6wV53+ue/+Tjz19Xb8EsTObgsyuNu9KpQ99rlHv27amTOfjgXD6O1q3U7dfZJnPwqvjndVX6URL5bOOpkzn4j0PtuB44h+GK2H4aXVACf3z7AOlvNj7qsNAj2mKU2880B8tybaG6ffmbea22358M6XcAZRv381uuM8o97HliTXNpeRfRTlcWqvu/t8jVcOp2jszNwkWnH51uXMviqNs3OzdpmcvJjrHH4G8g9UssReYmYqB7diIiTqEOZf/GLHNhXD/WpnEPA6ZkwIc0skMbs+vmYjh6xx5F2zBUUNa/ej+QSI5u3qa5WQjf3ThBGeeRpCdzgW0fa7v/r8ddats9rIGNUJYRHkNoJzZmmQtMvA7p3pfuDyCBc9u8zGVmv7rzPORw+nXdKYgYTvyC7dt3ngdMc2FcuQR/5xVzyd4fJnCZXNkaTXOBbezGRa59DZ2J0A+eFxdfcWUuNjvzR56WTK6vKmQuocl38sn/+ckUOXIic+HZq595NjIpdXRY5kLauOvZuaNyH78r3CkIjcuk4ObnTOu83qMQrmtkVXZTNM0lcW/WnnOvWd8rnu9fNK3iL7emuTx+7uduasL4amyHpjmWReMYQ6XtUObQOJKTudlpHIOotyk6NjeiZO8thW21t3CZG87H95ZW2g72/1jlpZIG25JFa1TXN47Tjfv4J3BCm9dLmYuheFaMY/R1u92abYQyF4MqkUnj7VnmZpQymin/Ufm0HOIeZG44tTeCIp9jPWBTHC4cXJfA3dU6hUcpz3vvxo1Jdkr56xa4wXXf6mQugG+lO7p7p/ld61ogI2x1rpsLpt41dCGujBO4EEbbeGQuntOl21j/FvxbKhG42h6/7tNP9VAbzLOxNmW++XYLzCI7/+12G/PuwdLWTPffdVUyF0OvHb7bqTGBa2WGArighK80Lr0ZGrfIXBT1NsfbX5V+/lEa18w4v/TanIKY1M9NvP0+IHAtzdO4xbG5cC62YMxft8C1NOY2UJVpbgrDbtkC19iwW0JVjs3lN+yWrXGNDbsl1GaaowOBa2/axi0yl96hjbvBRcIC197MgbuzaGVZlmVd128BKhgmjWtP4xbTXG7bm/j+6Ny/8soOI3BdaNydzM2oZXQErguBe+a6uUgOJePjb7bxZXca14Wd+oVjc7PYOPp26IdU+mJK0bh3MpfT9dupX6RxXWjcR47NZdalNQLXhcBtkLmEvt0ms4jtuwprXBfNGhfiTvrvZC6Mo9d/NCZwvexszaFb5P/8CbE4NkcBcXeA6E407v0/T4vyezfNxTDy9jTyY0ts/0TmF2Sa4xK7UBfXD4qV+rCk6z+kAZnjpCIX4nHO9Wf+RKGiRO2dd0EEoCZs2LMLf/sAzP0ePyFiMUxzENueV8GXNk3VuEXmxmeU46eql0lGb9ziTCvwUabXV9Mc5Hf0urnrx/KGYpobWqZXVEJocKP89kxzEN6JDH3MWdaXVdPcuLJuczS2Z0Pa+Jroo9wiczC57QgmaNwic8MyylHExoY0zzbm2BzEVm/gyjHKLaa5Mc3zMstFVUuU4MLgO5mDqH7Wp/h95d7/xut362zAW/eHY5RjfPduRLmK2DQHHBbrxdgpiLHE2nrgxZgbsGkOKPY+ijEXraa5gYz5SsgMTmx7YxbtI5kDluXUXe8v3q2zGWdaR2GUYxzJsmCaA14le9E1zQ0h2VZFGjn6YJoDvsrxAixzwJYEH8jrujngt3Vd39/gFWVJ69jcEKK/WhLIx13+9BYYIiAy15/G0dLpz6Iu9QPbs2iFuTyWnzs9f3HQl2SnIGA6QWt1msxBErfbrfb68f3nj79iXWQOcnjkZmfsigx0IRq3OAUxgtlWEJS1vQvP8PmEPzkFAVHtidTja2Z+NTXN9Tfz9sc5p3fbOYc7metP5tiv1A77batLGQSZG4LSsa3GfhroLucXOdMKQ2twmcizlK+4TkEM4Xa7pdy8OK3XVGWao6KUmxcnNBvf5tnkHJsbi5kuqCvzeN99MOKNlY6SuXFJXiDv92Lb+S00IHMxSN7I7ESDk7nY5K87e9D4nIIITOO607gQZC4qjYOdXDcXksZ1Z44LxDQXj8Z1p3GxyBwco3HhyFwwRrm+NC4imYO9NC4omYNdNC4umYvEirUXjQtN5sLQuF40LjrXzcFXApeDaS4Go1x7GpeGzMEHGpeJRSv8h8DlI3Pwh8BlJXMBODBXm8Dl5tgcs9O49GRudEa5qjRuBhatTErg5iFzTEfgZiNzQ7NiLUvg5iRzTEHgZiZzJCdwONM6LivW6zSOxTRHVgLHg2mOhDSOZ6a5QVmxnqBufCRzZCBwbLBoJTyNY9tqExmQFes5NmY+Ms2Rx7quXiF4J3Nko3S8kDkSUjqeydxw7KJFeBp5kDkgOZkjLQMddzIHJCdzYzGAQHEyByQnc0ByMkda3vvFncwNxIE5qEHmgORkjpysWHmQOSA5mSMhoxzPZA5ITubIxijHC5kjFY3jncwBycncKFwbfJ1Rjo9kjiQ0jm9kjgw0jg0yByT3T+8HAFf9HOVejnsa/WZjmhuC8w+nHW0cE5I5Ajs3lwnfbGSOqKw92UnmCOlK4/RxNk5BkNztdju3Sn3+LmUMzTRHPKejc7vddn7vSxkdzgtN5vqzCx1isOIomSOSE40r9Sri1SgumSOMjo0797czCJkjhsaNE7VMnGklgJaN+/iNqheazDG6Nol5r5u0pSFzjK7qsf9vP1zjMpE5ZrSdTo1LRuaYyJ7BUOPycaYV/qVxKckc/KFxWckcLIvGpSZzoHHJyRws67p6y2pizrTCH4/SvQx3PjEnOtMcvFr/+vZ/Gz8eLjLNwVeKloPM8cd9LTbVjr1n+fnxCVnX1dI1EItWluVph7f37uFZikXmOhtweppnH/ber0lYtPJhTz79aVilbJ/r7Ev4wnGIobPuO/DGBtDmsbn1ObXJXGcjZ+6h7IMsvsldfHh2gfQsWqe2cw+/eBK2dkcmPEfMIaa5zoY6BBbdxpO5ncJkzwMvTHPk8XOs+/YFz38iefm4oIRsPp44fvnP7ideaEnm5pV4bNnzT9uOHZnIHPkdHdAMdMnIXE92p2YOPdWmvGRkblK59+T9Ucv9PHAnc8xiZ/uELx8XlDCLb/3StfRMcySkXDyTuRlNWIEJ/8k8WLSSk67xYJoDkpO56RhzmI3MAcnJ3FyMckxI5oDkZG4iRjnmJHNAcjIHJCdzQHIyByQnc7Nw/oFpyRyQnMwByclcNz4IAtqQuSk4MMfMZA5ITuaA5GQuPytWJidzQHIyByQnc8lZsYLMAcnJHJCczGVmxQqLzPXinV7QjMylZZSDO5kDkpO5nIxy8CBzQHIyByQnc0ByMgckJ3MJOf8Az2SuA9cGQ0syByQnc9lYscILmQOSkzkgOZkDkpO51qqeZnVgDt7JHJCczAHJyVweVqzwkcwByclcU/XOPxjl4BuZA5KTOSA5mcvAihU2yByQnMy1U+n8g1EOtskckJzMAcnJXGxWrPCTzAHJyVwjNc4/GOVgD5kDkpM5IDmZi8qKFXaSOSA5mQvJKAf7yVwLVT/mBtgmc0ByMhePFSscInNAcjIXjFEOjpK56px/gL5kDkhO5uoqO8pZscIJMgckJ3NhGOXgHJmryMkHGIHMAcnJXAxWrHCazNVixQqDkLkAjHJwhcwByclcFQVXrEY5uEjmgORkbmhGObhO5oDkZG5cRjkoQubKc8UcDEXmBmWUg1JkrjCjHIxG5kZklIOCZA5ITuZKsmKFAclcMaUaZ8UKZcncWDQOipO5MixXYVgyNxCjHNQgcwUY5WBkMjcKoxxUInNXFRnlNA7qkTkgOZnrzygHVcncJU4+wPhk7jxH5SAEmQOSk7mTjHIQhcwBycncGc48QCAy140VK7Qhc4c5KgexyFwHGgctydwx10c5jYPGZA5ITuYOMMpBRDK3l8ZBUDK3i8ZBXDIHJCdzvxnlIDSZ+0HjIDqZ2+K9q5CAzH3lTV2Qg8wBycncZ0Y5SEPmPtA4yETmXmkcJCNz5WkcDEXm/sNVcpCPzP1L4yAlmftD4yArmVsWjYPUZM47uiC52TPn8hFIb+rMaRzMYN7MaRxMYtLMaRzMY8bMaRxMZbrMaRzMZq7MaRxM6J/eD6CRUhfHaRyEM8U0p3Ews/yZ0ziYXOZFa8F3cWkcxJV2mtM44C7nNGehCjxky5whDniRJ3Nl76ekcZBGhswJHLAhduaK3xFT4yCfwGdaNQ7YI+Q0J3DAfsEyV+NzGzQOcguTuUofTKNxkF6AzAkccMW4mav3uYICB1MZMXNVPzhV42A2Y2VO4IDiRsmcwAGV9Mxc1bTdCRzQJ3MCBzTTOnO1A6duwIsWmWswuy0CB3xRJXNtuvYgcMCGYplrnLY7gQN+upq5LnVbBA7Y7VjmekXtmcABh+zKXPe6SRtw2mvmuhftQdqAIv5kbpC6SRtQXP+6SRtQ1XqvjCvdgKzW9+L42FMgk/8DDsgw4HlIEQ0AAAAASUVORK5CYII=" alt="" height="211" width="213">

You can wrap this up into a string variable and place this absolutely anywhere that you would present an html email message - even in your email signatures. The advantage is that there are no attachments, and there are no links. (this code will display a lizard)

A picture is worth a thousand words: enter image description here

Incidentally, I did write a program to do all of this for you. It's called BaseImage, and it will create the image code as well as the html for you. Please don't consider this self-promotion; I'm just sharing a solution.

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

When do I need to do "git pull", before or after "git add, git commit"?

Best way for me is:

  1. create new branch, checkout to it
  2. create or modify files, git add, git commit
  3. back to master branch and do pull from remote (to get latest master changes)
  4. merge newly created branch with master
  5. remove newly created branch
  6. push master to remote

Or you can push newly created branch on remote and merge there (if you do it this way, at the end you need to pull from remote master)

Get last 5 characters in a string

I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:

Dim sMyString, sLast5 As String

sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)

If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.

Can't import javax.servlet.annotation.WebServlet

I had the same issue, it turns that I had my project configured as many of you stated above, yet the problem persisted, so I went deeper and came across that I was using Apache Tomcat 6 as my Runtime Server, so the fix was simple, I just upgraded the project to use Apache Tomcat 7 and that's all, finally the IDE recognized javax.servlet.annotation.WebServlet annotation.

PHP XML Extension: Not installed

In Centos

 sudo yum install php-xml

and restart apache

sudo service httpd restart

Installing ADB on macOS

Option 3 - Using MacPorts

Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:

  1. Install the Android SDK:

    sudo port install android
    
  2. Run the SDK manager:

    sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. As @brismuth suggested, uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

    echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

Forcing to download a file using PHP

A previous answer on this page describes how to use .htaccess to force all files of a certain type to download. However, the solution does not work with all file types across all browsers. This is a more reliable way:

<FilesMatch "\.(?i:csv)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

You might need to flush your browser cache to see this working correctly.

Debugging with command-line parameters in Visual Studio

Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.

What is phtml, and when should I use a .phtml extension rather than .php?

You can choose any extension in the world if you setup Apache correctly. You could use .html to do PHP if you set up in your Apache config.

In conclusion, extension has nothing to do with the app or website itself. You can use the one you want, but normaly, use .php (to not reinvent the wheel)

But in 2019, you should use routing and forgot about extension at the end.

I recommend you using Laravel.

In answer to @KingCrunch: True, Apache not use it by default but you can easily use it if you change config. But this it not recommended since everybody know that it not really an option.

I already saw .html files that executed PHP using the html extension.

C# - Substring: index and length must refer to a location within the string

Try This:

 int positionOfJPG=url.IndexOf(".jpg");
 string newString = url.Substring(18, url.Length - positionOfJPG);

spark submit add multiple jars in classpath

I was trying to connect to mysql from the python code that was executed using spark-submit.

I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars, --driver-class-path, etc, but none worked.

Solution

Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/

As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

install this https://www.microsoft.com/en-us/download/details.aspx?id=13255

install the 32 bit version no matter whether you are 64 bit and enable the 32 bit apps in the application pool

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

Nginx no-www to www and www to no-www

This solution comes from my personal experience. We used several Amazon S3 buckets and one server for redirecting non-www to www domain names to match S3 "Host" header policy.

I used the following configuration for nginx server:

server {
    listen 80;
    server_name ~^(?!www\.)(?<domain>.+)$;
    return 301 $scheme://www.$domain$request_uri;
}

This matches all domain names pointed to the server starting with whatever but www. and redirects to www.<domain>. In the same manner you can do opposite redirect from www to non-www.

Verify host key with pysftp

Connect to the server first with a Windows ssh client that uses the known_hosts file. PuTTy stores the data in the windows registry,however OpenSSH uses the known_hosts file, and will add entries in there after you connect. Default location for the file is %USERPROFILE%.ssh. I hope this helps

How to get the first day of the current week and month?

The first day of week can be determined with help of java.util.Calendar as follows:

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();

The first day of month can be determined as follows:

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();

Pretty verbose, yes.


Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:

DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();

and

DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();

How can I set the initial value of Select2 when using AJAX?

The issue of being forced to trigger('change') drove me nuts, as I had custom code in the change trigger, which should only trigger when the user changes the option in the dropdown. IMO, change should not be triggered when setting an init value at the start.

I dug deep and found the following: https://github.com/select2/select2/issues/3620

Example:

$dropDown.val(1).trigger('change.select2');

"use database_name" command in PostgreSQL

You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"

user_name=# CREATE DATABASE testdatabase; 
user_name=# \c testdatabase 

At this point you might see the following output

You are now connected to database "testdatabase" as user "user_name".
testdatabase=#

Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

private ViewPager viewPager;
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

Regex to check whether a string contains only numbers

If the numbers aren't supposed to be absurdly huge, maybe use:

new RegExp(
    '^' +                           // No leading content.
    '[-+]?' +                       // Optional sign.
    '(?:[0-9]{0,30}\\.)?' +         // Optionally 0-30 decimal digits of mantissa.
    '[0-9]{1,30}' +                 // 1-30 decimal digits of integer or fraction.
    '(?:[Ee][-+]?[1-2]?[0-9])?' +   // Optional exponent 0-29 for scientific notation.
    '$'                             // No trailing content.
)

This tries to avoid some scenarios, just in case:

  • Overflowing any buffers the original string might get passed to.
  • Slowness or oddities caused by denormal numbers like 1E-323.
  • Passing Infinity when a finite number is expected (try 1E309 or -1E309).

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

How do I capture the output into a variable from an external process in PowerShell?

I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.

The raw result I got with:

$rawOutput = (cmd /c <command> 2`>`&1)

Array String Declaration

You are not initializing your String[]. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String> and then convert to a String[] (in case you do not know the length):

String[] title = {
        "Abundance",
        "Anxiety",
        "Bruxism",
        "Discipline",
        "Drug Addiction"
    };
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();

for(int i=0;i<title.length;i++) {
    mStrings.add(urlbase + title[i].toLowerCase() + imgSel);

    System.out.println(mStrings[i]);
}

String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array

Html encode in PHP

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

Android AlertDialog Single Button

Kotlin?

  val dialogBuilder = AlertDialog.Builder(this.context)
  dialogBuilder.setTitle("Alert")
               .setMessage(message)
               .setPositiveButton("OK", null)
               .create()
               .show()

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

Given URL is not permitted by the application configuration

  • Go to Facebook for developers dashboard
  • Click My Apps and select your App from the dropdown.
    (If you haven't already created any app select "Add a New App" to create a new app).
  • Go to App Setting > Basic Tab and then click "Add Platform" at bottom section.
  • Select "Website" and the add the website to log in as the Site URL(e.g. mywebsite.com)
  • If you are testing in local, you can even just give the localhost URL of your app.
    eg. http://localhost:8080/myfbsampleapp
  • Save changes and you can now access Facebook information from http://localhost:8080/myfbsampleapp

Select rows with same id but different value in another column

You can simply achieve it by

SELECT *
FROM test
WHERE ARIDNR IN
    (SELECT ARIDNR FROM test
     GROUP BY ARIDNR
     HAVING COUNT(*) > 1)
GROUP BY ARIDNR, LIEFNR;

Thanks.

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

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

Errors: Data path ".builders['app-shell']" should have required property 'class'

I was also coming across this issue and for me when doing more updates more issues occurred.

What worked for me in the end was more or less to remove angular cli and re install it with these steps:

npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli

this helped me out source: how to uninstall angular/cli

Module not found: Error: Can't resolve 'core-js/es6'

I found possible answer. You have core-js version 3.0, and this version doesn't have separate folders for ES6 and ES7; that's why the application cannot find correct paths.

To resolve this error, you can downgrade the core-js version to 2.5.7. This version produces correct catalogs structure, with separate ES6 and ES7 folders.

To downgrade the version, simply run:

npm i -S [email protected]

In my case, with Angular, this works ok.

Appending to an existing string

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

HTML table with fixed headers and a fixed column?

I know you can do it for MSIE and this limited example seems to work for firefox (not sure how extensible the technique is).

In SQL, how can you "group by" in ranges?

An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:

LowerLimit   UpperLimit   Range 
0              9          '0-9'
10            19          '10-19'
20            29          '20-29'
30            39          '30-39'

And a query that looks like this:

Select
   Range as [Score Range],
   Count(*) as [Number of Occurences]
from
   Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
group by Range

This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!

Copying a HashMap in Java

If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.

The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.

This question is the perfect definition for the application of the deep copy approach.

First, if you have a simple HashMap<Integer, List<T>> map then we just create a workaround like this. Creating a new instance of the List<T>.

public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
    HashMap<Integer, List<T>> copy = new HashMap<>();
    for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
        copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    return copy;
}

This one uses Stream.collect() method to create the clone map, but uses the same idea as the previous method.

public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
    return original
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}   

But, if the instances inside T are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.

To solve that this deep copy implementations will do the work.

public class DeepClone
{
    public static void main(String[] args)
    {
        Map<Long, Item> itemMap = Stream.of(
                entry(0L, new Item(2558584)),
                entry(1L, new Item(254243232)),
                entry(2L, new Item(986786)),
                entry(3L, new Item(672542)),
                entry(4L, new Item(4846)),
                entry(5L, new Item(76867467)),
                entry(6L, new Item(986786)),
                entry(7L, new Item(7969768)),
                entry(8L, new Item(68868486)),
                entry(9L, new Item(923)),
                entry(10L, new Item(986786)),
                entry(11L, new Item(549768)),
                entry(12L, new Item(796168)),
                entry(13L, new Item(868421)),
                entry(14L, new Item(923)),
                entry(15L, new Item(986786)),
                entry(16L, new Item(549768)),
                entry(17L, new Item(4846)),
                entry(18L, new Item(4846)),
                entry(19L, new Item(76867467)),
                entry(20L, new Item(986786)),
                entry(21L, new Item(7969768)),
                entry(22L, new Item(923)),
                entry(23L, new Item(4846)),
                entry(24L, new Item(986786)),
                entry(25L, new Item(549768))
        ).collect(entriesToMap());


        Map<Long, Item> clone = DeepClone.deepClone(itemMap);
        clone.remove(1L);
        clone.remove(2L);

        System.out.println(itemMap);
        System.out.println(clone);
    }

    private DeepClone() {}

    public static <T> T deepClone(final T input)
    {
        if (input == null) return null;

        if (input instanceof Map<?, ?>) {
            return (T) deepCloneMap((Map<?, ?>) input);
        } else if (input instanceof Collection<?>) {
            return (T) deepCloneCollection((Collection<?>) input);
        } else if (input instanceof Object[]) {
            return (T) deepCloneObjectArray((Object[]) input);
        } else if (input.getClass().isArray()) {
            return (T) clonePrimitiveArray((Object) input);
        }

        return input;
    }

    private static Object clonePrimitiveArray(final Object input)
    {
        final int length = Array.getLength(input);
        final Object output = Array.newInstance(input.getClass().getComponentType(), length);
        System.arraycopy(input, 0, output, 0, length);
        return output;
    }

    private static <E> E[] deepCloneObjectArray(final E[] input)
    {
        final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
        for (int i = 0; i < input.length; i++) {
            clone[i] = deepClone(input[i]);
        }

        return clone;
    }

    private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
    {
        Collection<E> clone;
        if (input instanceof LinkedList<?>) {
            clone = new LinkedList<>();
        } else if (input instanceof SortedSet<?>) {
            clone = new TreeSet<>();
        } else if (input instanceof Set) {
            clone = new HashSet<>();
        } else {
            clone = new ArrayList<>();
        }

        for (E item : input) {
            clone.add(deepClone(item));
        }

        return clone;
    }

    private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
    {
        Map<K, V> clone;
        if (map instanceof LinkedHashMap<?, ?>) {
            clone = new LinkedHashMap<>();
        } else if (map instanceof TreeMap<?, ?>) {
            clone = new TreeMap<>();
        } else {
            clone = new HashMap<>();
        }

        for (Map.Entry<K, V> entry : map.entrySet()) {
            clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
        }

        return clone;
    }
}

What is the best way to programmatically detect porn images?

I shall not today attempt further to define the kinds of material I understand to be embraced within that shorthand description ["hard-core pornography"]; and perhaps I could never succeed in intelligibly doing so. But I know it when I see it, and the motion picture involved in this case is not that.

United States Supreme Court Justice Potter Stewart, 1964

How should I cast in VB.NET?

MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)

When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.

One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.

How to place and center text in an SVG rectangle

One way to insert text inside a rectangle is to insert a foreign object, wich is a DIV, inside rect object.

This way, the text will respct the limits of the DIV.

_x000D_
_x000D_
var g = d3.select("svg");_x000D_
     _x000D_
g.append("rect")_x000D_
.attr("x", 0)_x000D_
.attr("y", 0)_x000D_
.attr("width","100%")_x000D_
.attr("height","100%")_x000D_
.attr("fill","#000");_x000D_
_x000D_
_x000D_
var fo = g.append("foreignObject")_x000D_
 .attr("width","100%");_x000D_
_x000D_
fo.append("xhtml:div")_x000D_
  .attr("style","width:80%;color:#FFF;margin-right: auto;margin-left: auto;margin-top:40px")_x000D_
  .text("Mussum Ipsum, cacilds vidis litro abertis Mussum Ipsum, cacilds vidis litro abertis Mussum Ipsum, cacilds vidis litro abertis");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.js"></script>_x000D_
<svg width="200" height="200"></svg>
_x000D_
_x000D_
_x000D_

Split string using a newline delimiter with Python

If you want to split only by newlines, you can use str.splitlines():

Example:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

With str.split() your case also works:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

However if you have spaces (or tabs) it will fail:

>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']

Using css transform property in jQuery

$(".oSlider-rotate").slider({
     min: 10,
     max: 74,
     step: .01,
     value: 24,
     slide: function(e,ui){
                 $('.user-text').css('transform', 'scale(' + ui.value + ')')

            }                
  });

This will solve the issue

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

AngularJS view not updating on model change

Do not use $scope.$apply() angular already uses it and it can result in this error

$rootScope:inprog Action Already In Progress

if you use twice, use $timeout or interval

File inside jar is not visible for spring

I was having an issue recursively loading resources in my Spring app, and found that the issue was I should be using resource.getInputStream. Here's an example showing how to recursively read in all files in config/myfiles that are json files.

Example.java

private String myFilesResourceUrl = "config/myfiles/**/";
private String myFilesResourceExtension = "json";

ResourceLoader rl = new ResourceLoader();

// Recursively get resources that match. 
// Big note: If you decide to iterate over these, 
// use resource.GetResourceAsStream to load the contents
// or use the `readFileResource` of the ResourceLoader class.
Resource[] resources = rl.getResourcesInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

// Recursively get resource and their contents that match. 
// This loads all the files into memory, so maybe use the same approach 
// as this method, if need be.
Map<Resource,String> contents = rl.getResourceContentsInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

ResourceLoader.java

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StreamUtils;

public class ResourceLoader {
  public Resource[] getResourcesInResourceFolder(String folder, String extension) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
      String resourceUrl = folder + "/*." + extension;
      Resource[] resources = resolver.getResources(resourceUrl);
      return resources;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public String readResource(Resource resource) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
      return StreamUtils.copyToString(stream, Charset.defaultCharset());
    }
  }

  public Map<Resource, String> getResourceContentsInResourceFolder(
      String folder, String extension) {
    Resource[] resources = getResourcesInResourceFolder(folder, extension);

    HashMap<Resource, String> result = new HashMap<>();
    for (var resource : resources) {
      try {
        String contents = readResource(resource);
        result.put(resource, contents);
      } catch (IOException e) {
        throw new RuntimeException("Could not load resource=" + resource + ", e=" + e);
      }
    }
    return result;
  }
}

HTTP POST Returns Error: 417 "Expectation Failed."

If you are using "HttpClient", and you don't want to use global configuration to affect all you program you can use:

 HttpClientHandler httpClientHandler = new HttpClientHandler();
 httpClient.DefaultRequestHeaders.ExpectContinue = false;

I you are using "WebClient" I think you can try to remove this header by calling:

 var client = new WebClient();
 client.Headers.Remove(HttpRequestHeader.Expect);

How to insert 1000 rows at a time

Simplest way.

Just stop execution in 10 sec.

Create table SQL_test  ( ID INT IDENTITY(1,1), UserName varchar(100)) 
while 1=1 
insert into SQL_test values ('TEST') 

#1214 - The used table type doesn't support FULLTEXT indexes

Only MyISAM allows for FULLTEXT, as seen here.

Try this:

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Equivalent to 'app.config' for a library (DLL)

I am currently creating plugins for a retail software brand, which are actually .net class libraries. As a requirement, each plugin needs to be configured using a config file. After a bit of research and testing, I compiled the following class. It does the job flawlessly. Note that I haven't implemented local exception handling in my case because, I catch exceptions at a higher level.

Some tweaking maybe needed to get the decimal point right, in case of decimals and doubles, but it works fine for my CultureInfo...

static class Settings
{
    static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
    static Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(uri.Path);
    static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
    static NumberFormatInfo nfi = new NumberFormatInfo() 
    { 
        NumberGroupSeparator = "", 
        CurrencyDecimalSeparator = "." 
    };

    public static T Setting<T>(string name)
    {
        return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
    }
}

App.Config file sample

<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />

Usage:

  somebooleanvar = Settings.Setting<bool>("Enabled");
  somestringlvar = Settings.Setting<string>("ExportPath");
  someintvar =     Settings.Setting<int>("Seconds");
  somedoublevar =  Settings.Setting<double>("Ratio");

Credits to Shadow Wizard & MattC

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

However, the Loop approach is more readable and therefore more maintainable.

Is it possible to set an object to null?

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Example of what you can't do which you are asking:

Cat c;
c = NULL;//Compiling error

Example of what you can do:

Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;

PHP header(Location: ...): Force URL change in address bar

you may want to put a break; after your location:

header("HTTP/1.1 301 Moved Permanently");
header('Location:  '.  $YourArrayName["YourURL"]  );
break;

animating addClass/removeClass with jQuery

You just need the jQuery UI effects-core (13KB), to enable the duration of the adding (just like Omar Tariq it pointed out)

"Gradle Version 2.10 is required." Error

For those who uses ionic, go to
[project name]/platforms/android/cordova/lib/builders/GradleBuilder.js

on line 164 you will see the following:
var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.13-all.zip';

This line is used to create your gradle-wrapper.properties, so any changes to the gradle-wrapper.properties wont matter. All you need to do is change the url to the latest version, sync the gradle and the problem is solved.

Just want to change the gradle version in the Android studio, go to File>settings>project and change the gradle version. After you apply, it will sync the project and you are ready to build.

How to convert a selection to lowercase or uppercase in Sublime Text

For others needing a key binding:

{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }