Programs & Examples On #Static cast

A C++ cast operator to convert from one type to another, using only information about the static type of the object being cast

Why use static_cast<int>(x) instead of (int)x?

In short:

  1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
  2. static_cast<>() can be spotted easily anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
  3. Intentions are conveyed much better using C++ casts.

More Explanation:

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

Read more on:
What is the difference between static_cast<> and C style casting
and
Regular cast vs. static_cast vs. dynamic_cast

What is the difference between static_cast<> and C style casting?

A great post explaining different casts in C/C++, and what C-style cast really does: https://anteru.net/blog/2007/12/18/200/index.html

C-Style casting, using the (type)variable syntax. The worst ever invented. This tries to do the following casts, in this order: (see also C++ Standard, 5.4 expr.cast paragraph 5)

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_castfollowed by const_cast

Error : Index was outside the bounds of the array.

//if i input 9 it should go to 8?

You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).

How do I export an Android Studio project?

It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).

Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.

Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

One reason can be that the IEnumerable may contain an unknown number of items. Some implementations produce the list of items as you iterate over it (see yield for samples). That does not work very well with accessing items using an index. which would require you to know that there are at least that many items in the list.

How to find which version of Oracle is installed on a Linux server (In terminal)

Enter in sqlplus (you'll see the version number)

# su - oracle

oracle# sqlplus

OR

echo $ORAHOME

Will give you the path where Oracle installed and path will include version number.

OR

Connect to Oracle DB and run

select * from v$version where banner like 'oracle%';

How to resize image (Bitmap) to a given size?

You can scale bitmaps by using canvas.drawBitmap with providing matrix, for example:

public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
        Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
        canvas.drawBitmap(bitmap, m, new Paint());

        return output;
    }

What is a clean, Pythonic way to have multiple constructors in Python?

One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.

The @classmethod approach can be modified to provide an alternative constructor which does not invoke the default constructor (__init__). Instead, an instance is created using __new__.

This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code.

Example:

class MyClass(set):

    def __init__(self, filename):
        self._value = load_from_file(filename)

    @classmethod
    def from_somewhere(cls, somename):
        obj = cls.__new__(cls)  # Does not call __init__
        super(MyClass, obj).__init__()  # Don't forget to call any polymorphic base class initializers
        obj._value = load_from_somewhere(somename)
        return obj

Connect over ssh using a .pem file

chmod 400 mykey.pem

ssh -i mykey.pem [email protected]

Will connect you over ssh using a .pem file to any server.

How do I drop a function if it already exists?

I usually shy away from queries from sys* type tables, vendors tend to change these between releases, major or otherwise. What I have always done is to issue the DROP FUNCTION <name> statement and not worry about any SQL error that might come back. I consider that standard procedure in the DBA realm.

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

How do I reference tables in Excel using VBA?

A "table" in Excel is indeed known as a ListObject.

The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName).

If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject.

NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.

Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...

Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next

    If (Not ParentWorksheet Is Nothing) Then
        Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
    Else
        Set GetListObject = Application.Range(ListObjectName).ListObject
    End If

On Error GoTo 0 'Or your error handler

    If (Not GetListObject Is Nothing) Then
        'Success
    ElseIf (Not ParentWorksheet Is Nothing) Then
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
    Else
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
    End If

End Function

Also some good ListObject info here.

What is the difference between UTF-8 and ISO-8859-1?

Wikipedia explains both reasonably well: UTF-8 vs Latin-1 (ISO-8859-1). Former is a variable-length encoding, latter single-byte fixed length encoding. Latin-1 encodes just the first 256 code points of the Unicode character set, whereas UTF-8 can be used to encode all code points. At physical encoding level, only codepoints 0 - 127 get encoded identically; code points 128 - 255 differ by becoming 2-byte sequence with UTF-8 whereas they are single bytes with Latin-1.

Virtual network interface in Mac OS X

Replying in particular to:

You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).

This can be achieved using a Tun/Tap device as suggested by psv141, and manipulating the /Library/Preferences/SystemConfiguration/preferences.plist file to add a NetworkService based on either a tun or tap interface. Mac OS X will not allow the creation of a NetworkService based on a virtual network interface, but one can directly manipulate the preferences.plist file to add the NetworkService by hand. Basically you would open the preferences.plist file in Xcode (or edit the XML directly, but Xcode is likely to be more fool-proof), and copy the configuration from an existing Ethernet interface. The place to create the new NetworkService is under "NetworkServices", and if your Mac has an Ethernet device the NetworkService profile will also be under this property entry. The Ethernet entry can be copied pretty much verbatim, the only fields you would actually be changing are:

  • UUID
  • UserDefinedName
  • IPv4 configuration and set the interface to your tun or tap device (i.e. tun0 or tap0).
  • DNS server if needed.

Then you would also manipulate the particular Location you want this NetworkService for (remember Mac OS X can configure all network interfaces dependent on your "Location"). The default location UUID can be obtained in the root of the PropertyList as the key "CurrentSet". After figuring out which location (or set) you want, expand the Set property, and add entries under Global/IPv4/ServiceOrder with the UUID of the new NetworkService. Also under the Set property you need to expand the Service property and add the UUID here as a dictionary with one String entry with key __LINK__ and value as the UUID (use the other interfaces as an example).

After you have modified your preferences.plist file, just reboot, and the NetworkService will be available under SystemPreferences->Network. Note that we have mimicked an Ethernet device so Mac OS X layer of networking will note that "a cable is unplugged" and will not let you activate the interface through the GUI. However, since the underlying device is a tun/tap device and it has an IP address, the interface will become active and the proper routing will be added at the BSD level.

As a reference this is used to do special routing magic.

In case you got this far and are having trouble, you have to create the tun/tap device by opening one of the devices under /dev/. You can use any program to do this, but I'm a fan of good-old-fashioned C myself:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
   int fd = open("/dev/tun0", O_RDONLY);
   if (fd < 0)
   {
      printf("Failed to open tun/tap device. Are you root? Are the drivers installed?\n");
      return -1;
   }
   while (1)
   {
      sleep(100000);
   }
   return 0;
}

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

db.T.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

which is a more simplified version of incorporating the two pipelines $project and $match:

db.T.aggregate([
    {
        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
            ...
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

With MongoDB 3.4 and newer:

db.T.aggregate([
    {
        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

How to compare two date values with jQuery

just use the jQuery datepicker UI library and convert both your strings into date format, then you can easily compare. following link might be useful

https://stackoverflow.com/questions/2974496/jquery-javascript-convert-date-string-to-date

cheers..!!

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

Connecting an input stream to an outputstream

In case you are into functional this is a function written in Scala showing how you could copy an input stream to an output stream using only vals (and not vars).

def copyInputToOutputFunctional(inputStream: InputStream, outputStream: OutputStream,bufferSize: Int) {
  val buffer = new Array[Byte](bufferSize);
  def recurse() {
    val len = inputStream.read(buffer);
    if (len > 0) {
      outputStream.write(buffer.take(len));
      recurse();
    }
  }
  recurse();
}

Note that this is not recommended to use in a java application with little memory available because with a recursive function you could easily get a stack overflow exception error

Why am I getting an OPTIONS request instead of a GET request?

I don't believe jQuery will just naturally do a JSONP request when given a URL like that. It will, however, do a JSONP request when you tell it what argument to use for a callback:

$.get("http://metaward.com/import/http://metaward.com/u/ptarjan?jsoncallback=?", function(data) {
     alert(data);
});

It's entirely up to the receiving script to make use of that argument (which doesn't have to be called "jsoncallback"), so in this case the function will never be called. But, since you stated you just want the script at metaward.com to execute, that would make it.

Setting TIME_WAIT TCP

A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).

The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).

So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.

That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.

That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

How do you change video src using jQuery?

JQUERY

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
  var videoID = 'videoclip';_x000D_
  var sourceID = 'mp4video';_x000D_
  var newmp4 = 'media/video2.mp4';_x000D_
  var newposter = 'media/video-poster2.jpg';_x000D_
 _x000D_
  $('#videolink1').click(function(event) {_x000D_
    $('#'+videoID).get(0).pause();_x000D_
    $('#'+sourceID).attr('src', newmp4);_x000D_
    $('#'+videoID).get(0).load();_x000D_
     //$('#'+videoID).attr('poster', newposter); //Change video poster_x000D_
    $('#'+videoID).get(0).play();_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

Page Redirect after X seconds wait using JavaScript

It looks you are almost there. Try:

if(error == true){

    // Your application has indicated there's an error
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "https://www.google.co.in";

    }, 5000);

}

PowerShell script to check the status of a URL

$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')

$response = $request.GetResponse()

$response.StatusCode

$response.Close()

Creating a very simple 1 username/password login in php

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in

How to join two JavaScript Objects, without using JQUERY

1)

var merged = {};
for(key in obj1)
    merged[key] = obj1[key];
for(key in obj2)
    merged[key] = obj2[key];

2)

var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);

OR

Object.keys(obj1)
    .concat(Object.keys(obj2))
    .forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);

3) Simplest way:

var merged = {};
Object.assign(merged, obj1, obj2);

Measuring execution time of a function in C++

#include <iostream>
#include <chrono>

void function()
{
    // code here;
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration<<"/n";
    return 0;
}

This Worked for me.


Note:

The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for std::chrono::steady_clock or std::chrono::system_clock, but which one it is depends on the library or configuration. When it is a system_clock, it is not monotonic (e.g., the time can go backwards).

For example, for gcc's libstdc++ it is system_clock, for MSVC it is steady_clock, and for clang's libc++ it depends on configuration.

Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.

How to check if a specified key exists in a given S3 bucket using Java

Break your path into bucket and object. Testing the bucket using the method doesBucketExist, Testing the object using the size of the listing (0 in case not exist). So this code will do:

String bucket = ...;
String objectInBucket = ...;
AmazonS3 s3 = new AmazonS3Client(...);
return s3.doesBucketExist(bucket) 
       && !s3.listObjects(bucket, objectInBucket).getObjectSummaries().isEmpty();

Need to perform Wildcard (*,?, etc) search on a string using Regex

public class Wildcard
{
    private readonly string _pattern;

    public Wildcard(string pattern)
    {
        _pattern = pattern;
    }

    public static bool Match(string value, string pattern)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end);
    }

    public static bool Match(string value, string pattern, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end, toLowerTable);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end, char[] toLowerTable)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end);
    }

    public bool IsMatch(string str, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str, ref int start, ref int end)
    {
        if (_pattern.Length == 0) return false;
        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;
                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (str[si] == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && str[si] != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }

    public bool IsMatch(string str, ref int start, ref int end, char[] toLowerTable)
    {
        if (_pattern.Length == 0) return false;

        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;

                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    char c = toLowerTable[str[si]];
                    if (c == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && c != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    continue;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }
}

Use:

var ismatch2 = Wildcard.Match("xmlfsdfsd", "xml*");

how to get docker-compose to use the latest image from repository

I've seen this occur in our 7-8 docker production system. Another solution that worked for me in production was to run

docker-compose down
docker-compose up -d

this removes the containers and seems to make 'up' create new ones from the latest image.

This doesn't yet solve my dream of down+up per EACH changed container (serially, less down time), but it works to force 'up' to update the containers.

How to generate .NET 4.0 classes from xsd?

The command that worked in my case was:

xsd /c your.xsd 

jQuery click events firing multiple times

In my case I had loaded the same *.js file on the page twice in a <script> tag, so both files were attaching event handlers to the element. I removed the duplicate declaration and that fixed the problem.

How to make <input type="file"/> accept only these types?

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif, or a notation like image/* that refers to all image types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

How to print object array in JavaScript?

you can use console.log() to print object

console.log(my_object_array);

in case you have big object and want to print some of its values then you can use this custom function to print array in console

this.print = function (data,bpoint=0) {
    var c = 0;
    for(var k=0; k<data.length; k++){
        c++;
        console.log(c+'  '+data[k]);
        if(k!=0 && bpoint === k)break;  
    }
}

usage

print(array);   // to print entire obj array

or

print(array,50);  // 50 value to print only 

how to display a javascript var in html body

<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";

function docWrite(variable) {
    document.write(variable);
}
</script>
</head>

<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>

<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>

You can shorten document.write but can't avoid <script> tag

CSS body background image fixed to full screen even when zooming in/out

Here is the simple code for full page background image when zooming you just apply the width:100% in style/css thats it

position:absolute; width:100%;

MySQL root password change

For the current latest mysql version (8.0.16), none of these answers worked for me.

After looking at several different answers and combining them together, this is what I ended up using that worked:

update user set authentication_string='test' where user='root';

Hope this helps.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

To replace nan in different columns with different ways:

   replacement= {'column_A': 0, 'column_B': -999, 'column_C': -99999}
   df.fillna(value=replacement)

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

Return from lambda forEach() in java

If you want to return a boolean value, then you can use something like this (much faster than filter):

players.stream().anyMatch(player -> player.getName().contains(name));

Removing time from a Date object?

String substring(int startIndex, int endIndex)

In other words you know your string will be 10 characers long so you would do:

FinalDate = date.substring(0,9);

How to display Toast in Android?

 Toast toast=Toast.makeText(getApplicationContext(),"Hello", Toast.LENGTH_SHORT);
 toast.setGravity(Gravity.CENTER, 0, 0); // last two args are X and Y are used for setting position
 toast.setDuration(10000);//you can even use milliseconds to display toast
 toast.show();**//showing the toast is important**

WPF Data Binding and Validation Rules Best Practices

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

If you are running puppet it may set /proc/sys/kernel/modules_disabled to 1, inhibiting further module loading. When the machine is reboot, it gets set back to 0, allowing for changes, such as loading the iptables modules. After a certain amount of time puppet will set it back to 1 to protect the system from kernel root kits. Therefore, whatever modules that we are going to need should be loaded during or shortly after boot time.

How to add an extra language input to Android?

I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.

Maven : error in opening zip file when running maven

Accidently I found a simple workaroud to this issue. Running Maven with -X option forces it to try other servers to download source code. Instead of trash HTML inside some jar files there is correct content.

mvn clean install -X > d:\log.txt

And in the log file you find messages like these:

Downloading: https://repository.apache.org/content/groups/public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
[DEBUG] Writing resolution tracking file D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar.lastUpdated
Downloading: http://maven.wso2.org/nexus/content/groups/wso2-public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar

You see, Maven switched repository.apache.org to maven.wso2.org when it encountered a download problem. So the following error is now gone:

[ERROR] error: error reading D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar; error in opening zip file

How to assign the output of a Bash command to a variable?

In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

#!/bin/bash
until [ "$PWD" = "/" ]; do
  echo "$PWD"
  ls && cd .. && ls 
done

Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

In the general case, as other answers have mentioned already:

  • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
  • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

Render basic HTML view?

try this. it works for me.

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

app.get('/', function(req, res){
  res.render("index.html");
});

SQL: Return "true" if list of records exists?

If you have the IDs stored in a temp table (which can be done by some C# function or simple SQL) then the problem becomes easy and doable in SQL.

select "all exist"
where (select case  when count(distinct t.id) = (select count(distinct id) from #products) then "true" else "false" end
    from ProductTable t, #products p
    where t.id = p.id) = "true"

This will return "all exists" when all the products in #products exist in the target table (ProductTable) and will not return a row if the above is not true.

If you are not willing to write to a temp table, then you need to feed in some parameter for the number of products you are attempting to find, and replace the temp table with an 'in'; clause so the subquery looks like this:

SELECT "All Exist"
WHERE(
        SELECT case when count(distinct t.id) = @ProductCount then "true" else "false" 
        FROM ProductTable t 
        WHERE t.id in (1,100,10,20) -- example IDs
) = "true"

How to pass arguments to addEventListener listener function?

Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop

for (var key in catalog){
    document.getElementById(key).my_id = key
    document.getElementById(key).addEventListener('click', function(e) {
        editorContent.loadCatalogEntry(e.srcElement.my_id)
    }, false);
}

It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers

I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D

GZIPInputStream reading line by line

BufferedReader in = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));

String content;

while ((content = in.readLine()) != null)

   System.out.println(content);

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

Update values from one column in same table to another in SQL Server

You put select query before update queries, so you just see initial data. Put select * from stuff; to the end of list.

MySQL convert date string to Unix timestamp

From http://www.epochconverter.com/

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())

My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:

http://www.epochconverter.com/programming/mysql-from-unixtime.php

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

How should a model be structured in MVC?

Disclaimer: the following is a description of how I understand MVC-like patterns in the context of PHP-based web applications. All the external links that are used in the content are there to explain terms and concepts, and not to imply my own credibility on the subject.

The first thing that I must clear up is: the model is a layer.

Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which briefly describes how they are different.

What a model is NOT:

The model is not a class or any single object. It is a very common mistake to make (I did too, though the original answer was written when I began to learn otherwise), because most frameworks perpetuate this misconception.

Neither is it an Object-Relational Mapping technique (ORM) nor an abstraction of database tables. Anyone who tells you otherwise is most likely trying to 'sell' another brand-new ORM or a whole framework.

What a model is:

In proper MVC adaptation, the M contains all the domain business logic and the Model Layer is mostly made from three types of structures:

  • Domain Objects

    A domain object is a logical container of purely domain information; it usually represents a logical entity in the problem domain space. Commonly referred to as business logic.

    This would be where you define how to validate data before sending an invoice, or to compute the total cost of an order. At the same time, Domain Objects are completely unaware of storage - neither from where (SQL database, REST API, text file, etc.) nor even if they get saved or retrieved.

  • Data Mappers

    These objects are only responsible for the storage. If you store information in a database, this would be where the SQL lives. Or maybe you use an XML file to store data, and your Data Mappers are parsing from and to XML files.

  • Services

    You can think of them as "higher level Domain Objects", but instead of business logic, Services are responsible for interaction between Domain Objects and Mappers. These structures end up creating a "public" interface for interacting with the domain business logic. You can avoid them, but at the penalty of leaking some domain logic into Controllers.

    There is a related answer to this subject in the ACL implementation question - it might be useful.

The communication between the model layer and other parts of the MVC triad should happen only through Services. The clear separation has a few additional benefits:

  • it helps to enforce the single responsibility principle (SRP)
  • provides additional 'wiggle room' in case the logic changes
  • keeps the controller as simple as possible
  • gives a clear blueprint, if you ever need an external API

 

How to interact with a model?

Prerequisites: watch lectures "Global State and Singletons" and "Don't Look For Things!" from the Clean Code Talks.

Gaining access to service instances

For both the View and Controller instances (what you could call: "UI layer") to have access these services, there are two general approaches:

  1. You can inject the required services in the constructors of your views and controllers directly, preferably using a DI container.
  2. Using a factory for services as a mandatory dependency for all of your views and controllers.

As you might suspect, the DI container is a lot more elegant solution (while not being the easiest for a beginner). The two libraries, that I recommend considering for this functionality would be Syfmony's standalone DependencyInjection component or Auryn.

Both the solutions using a factory and a DI container would let you also share the instances of various servers to be shared between the selected controller and view for a given request-response cycle.

Alteration of model's state

Now that you can access to the model layer in the controllers, you need to start actually using them:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $identity = $this->identification->findIdentityByEmailAddress($email);
    $this->identification->loginWithPassword(
        $identity,
        $request->get('password')
    );
}

Your controllers have a very clear task: take the user input and, based on this input, change the current state of business logic. In this example the states that are changed between are "anonymous user" and "logged in user".

Controller is not responsible for validating user's input, because that is part of business rules and controller is definitely not calling SQL queries, like what you would see here or here (please don't hate on them, they are misguided, not evil).

Showing user the state-change.

Ok, user has logged in (or failed). Now what? Said user is still unaware of it. So you need to actually produce a response and that is the responsibility of a view.

public function postLogin()
{
    $path = '/login';
    if ($this->identification->isUserLoggedIn()) {
        $path = '/dashboard';
    }
    return new RedirectResponse($path); 
}

In this case, the view produced one of two possible responses, based on the current state of model layer. For a different use-case you would have the view picking different templates to render, based on something like "current selected of article" .

The presentation layer can actually get quite elaborate, as described here: Understanding MVC Views in PHP.

But I am just making a REST API!

Of course, there are situations, when this is a overkill.

MVC is just a concrete solution for Separation of Concerns principle. MVC separates user interface from the business logic, and it in the UI it separated handling of user input and the presentation. This is crucial. While often people describe it as a "triad", it's not actually made up from three independent parts. The structure is more like this:

MVC separation

It means, that, when your presentation layer's logic is close to none-existent, the pragmatic approach is to keep them as single layer. It also can substantially simplify some aspects of model layer.

Using this approach the login example (for an API) can be written as:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $data = [
        'status' => 'ok',
    ];
    try {
        $identity = $this->identification->findIdentityByEmailAddress($email);
        $token = $this->identification->loginWithPassword(
            $identity,
            $request->get('password')
        );
    } catch (FailedIdentification $exception) {
        $data = [
            'status' => 'error',
            'message' => 'Login failed!',
        ]
    }

    return new JsonResponse($data);
}

While this is not sustainable, when you have complicate logic for rendering a response body, this simplification is very useful for more trivial scenarios. But be warned, this approach will become a nightmare, when attempting to use in large codebases with complex presentation logic.

 

How to build the model?

Since there is not a single "Model" class (as explained above), you really do not "build the model". Instead you start from making Services, which are able to perform certain methods. And then implement Domain Objects and Mappers.

An example of a service method:

In the both approaches above there was this login method for the identification service. What would it actually look like. I am using a slightly modified version of the same functionality from a library, that I wrote .. because I am lazy:

public function loginWithPassword(Identity $identity, string $password): string
{
    if ($identity->matchPassword($password) === false) {
        $this->logWrongPasswordNotice($identity, [
            'email' => $identity->getEmailAddress(),
            'key' => $password, // this is the wrong password
        ]);

        throw new PasswordMismatch;
    }

    $identity->setPassword($password);
    $this->updateIdentityOnUse($identity);
    $cookie = $this->createCookieIdentity($identity);

    $this->logger->info('login successful', [
        'input' => [
            'email' => $identity->getEmailAddress(),
        ],
        'user' => [
            'account' => $identity->getAccountId(),
            'identity' => $identity->getId(),
        ],
    ]);

    return $cookie->getToken();
}

As you can see, at this level of abstraction, there is no indication of where the data was fetched from. It might be a database, but it also might be just a mock object for testing purposes. Even the data mappers, that are actually used for it, are hidden away in the private methods of this service.

private function changeIdentityStatus(Entity\Identity $identity, int $status)
{
    $identity->setStatus($status);
    $identity->setLastUsed(time());
    $mapper = $this->mapperFactory->create(Mapper\Identity::class);
    $mapper->store($identity);
}

Ways of creating mappers

To implement an abstraction of persistence, on the most flexible approaches is to create custom data mappers.

Mapper diagram

From: PoEAA book

In practice they are implemented for interaction with specific classes or superclasses. Lets say you have Customer and Admin in your code (both inheriting from a User superclass). Both would probably end up having a separate matching mapper, since they contain different fields. But you will also end up with shared and commonly used operations. For example: updating the "last seen online" time. And instead of making the existing mappers more convoluted, the more pragmatic approach is to have a general "User Mapper", which only update that timestamp.

Some additional comments:

  1. Database tables and model

    While sometimes there is a direct 1:1:1 relationship between a database table, Domain Object, and Mapper, in larger projects it might be less common than you expect:

    • Information used by a single Domain Object might be mapped from different tables, while the object itself has no persistence in the database.

      Example: if you are generating a monthly report. This would collect information from different of tables, but there is no magical MonthlyReport table in the database.

    • A single Mapper can affect multiple tables.

      Example: when you are storing data from the User object, this Domain Object could contain collection of other domain objects - Group instances. If you alter them and store the User, the Data Mapper will have to update and/or insert entries in multiple tables.

    • Data from a single Domain Object is stored in more than one table.

      Example: in large systems (think: a medium-sized social network), it might be pragmatic to store user authentication data and often-accessed data separately from larger chunks of content, which is rarely required. In that case you might still have a single User class, but the information it contains would depend of whether full details were fetched.

    • For every Domain Object there can be more than one mapper

      Example: you have a news site with a shared codebased for both public-facing and the management software. But, while both interfaces use the same Article class, the management needs a lot more info populated in it. In this case you would have two separate mappers: "internal" and "external". Each performing different queries, or even use different databases (as in master or slave).

  2. A view is not a template

    View instances in MVC (if you are not using the MVP variation of the pattern) are responsible for the presentational logic. This means that each View will usually juggle at least a few templates. It acquires data from the Model Layer and then, based on the received information, chooses a template and sets values.

    One of the benefits you gain from this is re-usability. If you create a ListView class, then, with well-written code, you can have the same class handing the presentation of user-list and comments below an article. Because they both have the same presentation logic. You just switch templates.

    You can use either native PHP templates or use some third-party templating engine. There also might be some third-party libraries, which are able to fully replace View instances.

  3. What about the old version of the answer?

    The only major change is that, what is called Model in the old version, is actually a Service. The rest of the "library analogy" keeps up pretty well.

    The only flaw that I see is that this would be a really strange library, because it would return you information from the book, but not let you touch the book itself, because otherwise the abstraction would start to "leak". I might have to think of a more fitting analogy.

  4. What is the relationship between View and Controller instances?

    The MVC structure is composed of two layers: ui and model. The main structures in the UI layer are views and controller.

    When you are dealing with websites that use MVC design pattern, the best way is to have 1:1 relation between views and controllers. Each view represents a whole page in your website and it has a dedicated controller to handle all the incoming requests for that particular view.

    For example, to represent an opened article, you would have \Application\Controller\Document and \Application\View\Document. This would contain all the main functionality for UI layer, when it comes to dealing with articles (of course you might have some XHR components that are not directly related to articles).

Replace non-numeric with empty string

How about an extension method that doesn't use regex.

If you do stick to one of the Regex options at least use RegexOptions.Compiled in the static variable.

public static string ToDigitsOnly(this string input)
{
    return new String(input.Where(char.IsDigit).ToArray());
}

This builds on Usman Zafar's answer converted to a method group.

Nginx 403 forbidden for all files

One permission requirement that is often overlooked is a user needs x permissions in every parent directory of a file to access that file. Check the permissions on /, /home, /home/demo, etc. for www-data x access. My guess is that /home is probably 770 and www-data can't chdir through it to get to any subdir. If it is, try chmod o+x /home (or whatever dir is denying the request).

EDIT: To easily display all the permissions on a path, you can use namei -om /path/to/check

Android Studio doesn't recognize my device

I am sorry that i bothered you all. The problem was my device is cloned in different places in device manager. It was gone when I tried to update driver for my phone in "Other devices" list, and before i have been updating it in wrong sections. Thank you all.

Invalid default value for 'dateAdded'

I solved mine by changing DATE to DATETIME

Python subprocess/Popen with a modified environment

you might use my_env.get("PATH", '') instead of my_env["PATH"] in case PATH somehow not defined in the original environment, but other than that it looks fine.

resize font to fit in a div (on one line)

@Clovis Six thank for your answer. It prove very usefull to me. A pity I cannot thanks you more than just a vote up.

Note: I have to change the "$J(" for "$(" for it to work on my config.

evendo, this out of the scope of this question and not in the use of SO, I extended your code to make it work for multi-line box with max-height.

  /**
   * Adjust the font-size of the text so it fits the container
   *
   * support multi-line, based on css 'max-height'.
   * 
   * @param minSize     Minimum font size?
   * @param maxSize     Maximum font size?
   */
  $.fn.autoTextSize_UseMaxHeight = function(minSize, maxSize) {
    var _self = this,
        _width = _self.innerWidth(),
        _boxHeight = parseInt(_self.css('max-height')),
        _textHeight = parseInt(_self.getTextHeight(_width)),
        _fontSize = parseInt(_self.css('font-size'));

    while (_boxHeight < _textHeight || (maxSize && _fontSize > parseInt(maxSize))) {
      if (minSize && _fontSize <= parseInt(minSize)) break;

      _fontSize--;
      _self.css('font-size', _fontSize + 'px');

      _textHeight = parseInt(_self.getTextHeight(_width));
    }
  };

PS: I know this should be a comment, but comments don't let me post code properly.

Send email using the GMail SMTP server from a PHP page

Using Swift mailer, it is quite easy to send a mail through Gmail credentials:

<?php
require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
  ->setUsername('GMAIL_USERNAME')
  ->setPassword('GMAIL_PASSWORD');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('[email protected]' => 'ABC'))
  ->setTo(array('[email protected]'))
  ->setBody('This is a test mail.');

$result = $mailer->send($message);
?>

HTTP authentication logout via PHP

Method that works nicely in Safari. Also works in Firefox and Opera, but with a warning.

Location: http://[email protected]/

This tells browser to open URL with new username, overriding previous one.

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

How to access the php.ini file in godaddy shared hosting linux

I had this exact problem with my GoDaddy account.

I am running the Linux hosting with cPanel

follow these steps and you should be fine if you are running the same hosting as me:

first, go to you Manage Your Hosting -> Manage

then you will see a section called Files, click on File Manager

you can select the Document Root for: yourwebsite.com then click GO

this should bring you right away in the public_html folder

in that folder, you can add a file (by clicking the +File in top left corner), call it phpinfo.php

right click that new file, and select edit :

right this in it and save changes:

<?php phpinfo(); ?>

it the same public_html folder, add another file called php.ini

edit this one too, right those lines:

max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M

now, go back to your Manage Your Hosting -> Manage, look for PHP Process

click Kill Process, this will allows a refresh with your new settings. you are good to go

side note: you can see your new settings by navigating to yourwebiste.com/phpinfo.php

What is a 'multi-part identifier' and why can't it be bound?

Mine was putting the schema on the table Alias by mistake:

SELECT * FROM schema.CustomerOrders co
WHERE schema.co.ID = 1  -- oops!

Excel VBA - How to Redim a 2D array?

Here ya go.

Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

How can I install Python's pip3 on my Mac?

I also encountered the same problem but brew install python3 does not work properly to install pip3.

brre will throw the warning The post-install step did not complete successfully.

It has to do with homebrew does not have permission to /usr/local

Create the directory if not exist

sudo mkdir lib 
sudo mkdir Frameworks

Give the permissions inside /usr/local to homebrew so it can access them:

sudo chown -R $(whoami) $(brew --prefix)/*

Now ostinstall python3

brew postinstall python3

This will give you a successful installation

What are .tpl files? PHP, web design

Other possibilities for .tpl: HTML::SimpleTemplate, example:

Hello $name

, and Template Toolkit, example:

Hello [% world %]!

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

Create JSON object dynamically via JavaScript (Without concate strings)

Perhaps this information will help you.

_x000D_
_x000D_
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
  "firstName": firstName,_x000D_
  "lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
_x000D_
_x000D_

How do you truncate all tables in a database using TSQL?

This is one way to do it... there are likely 10 others that are better/more efficient, but it sounds like this is done very infrequently, so here goes...

get a list of the tables from sysobjects, then loop over those with a cursor, calling sp_execsql('truncate table ' + @table_name) for each iteration.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

What is setContentView(R.layout.main)?

public void onCreate(Bundle savedinstanceState) {
            super.onCreate(savedinstanceState);

            Button testButon = new Button(this);

            setContentView(testButon);

            show();

}

JQuery addclass to selected div, remove class if another div is selected

In this mode you can find all element which has class active and remove it

try this

$(document).ready(function() {
        $(this.attr('id')).click(function () {
           $(document).find('.active').removeClass('active');
           var DivId = $(this).attr('id');
           alert(DivId);
           $(this).addClass('active');
        });
  });

How to discover number of *logical* cores on Mac OS X?

On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu section, ie:

sysctl -a | grep machdep.cpu

In particular, for processors with HyperThreading (HT), you'll see the total enumerated CPU count (logical_per_package) as double that of the physical core count (cores_per_package).

sysctl -a | grep machdep.cpu  | grep per_package

How do I load the contents of a text file into a javascript variable?

If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

Getting data posted in between two dates

This worked great for me

$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');

How to read a specific line using the specific line number from a file in Java?

In Java 8,

For small files:

String line = Files.readAllLines(Paths.get("file.txt")).get(n);

For large files:

String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    line = lines.skip(n).findFirst().get();
}

In Java 7

String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    for (int i = 0; i < n; i++)
        br.readLine();
    line = br.readLine();
}

Source: Reading nth line from file

Is there a constraint that restricts my generic method to numeric types?

Unfortunately .NET doesn't provide a way to do that natively.

To address this issue I created the OSS library Genumerics which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.

sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, and BigInteger

The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.

Here's an example of the code usage.

public static T Sum(T[] items)
{
    T sum = Number.Zero<T>();
    foreach (T item in items)
    {
        sum = Number.Add(sum, item);
    }
    return sum;
}
public static T SumAlt(T[] items)
{
    // implicit conversion to Number<T>
    Number<T> sum = Number.Zero<T>();
    foreach (T item in items)
    {
        // operator support
        sum += item;
    }
    // implicit conversion to T
    return sum;
}

How to save a plot into a PDF file without a large margin around

Axes sizing in MATLAB can be a bit tricky sometimes. You are correct to suspect the paper sizing properties as one part of the problem. Another is the automatic margins MATLAB calculates. Fortunately, there are settable axes properties that allow you to circumvent these margins. You can reset the margins to be just big enough for axis labels using a combination of the Position and TightInset properties which are explained here. Try this:

>> h = figure;
>> axes;
>> set(h, 'InvertHardcopy', 'off');
>> saveas(h, 'WithMargins.pdf');

and you'll get a PDF that looks like: MATLAB plot with auto-margins but now do this:

>> tightInset = get(gca, 'TightInset');
>> position(1) = tightInset(1);
>> position(2) = tightInset(2);
>> position(3) = 1 - tightInset(1) - tightInset(3);
>> position(4) = 1 - tightInset(2) - tightInset(4);
>> set(gca, 'Position', position);
>> saveas(h, 'WithoutMargins.pdf');

and you'll get: MATLAB plot with auto-margins removed

Replace all whitespace with a line break/paragraph mark to make a word list

The portable way to do this is:

sed -e 's/[ \t][ \t]*/\
/g'

That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)

With GNU sed you can use \n in the substitution, and \s in the regex:

sed -e 's/\s\s*/\n/g'

GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +:

sed -r -e 's/\s+/\n/g'

If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.

Calling class staticmethod within the class body?

This is the way I prefer:

class Klass(object):

    @staticmethod
    def stat_func():
        return 42

    _ANS = stat_func.__func__()

    def method(self):
        return self.__class__.stat_func() + self.__class__._ANS

I prefer this solution to Klass.stat_func, because of the DRY principle. Reminds me of the reason why there is a new super() in Python 3 :)

But I agree with the others, usually the best choice is to define a module level function.

For instance with @staticmethod function, the recursion might not look very good (You would need to break DRY principle by calling Klass.stat_func inside Klass.stat_func). That's because you don't have reference to self inside static method. With module level function, everything will look OK.

Count number of days between two dates

To get the number of days difference by two dates:

(start.to_date...end.to_date).count - 1
or 
(end.to_date - start.to_date).to_i

What jar should I include to use javax.persistence package in a hibernate based application?

In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.

Add a dependency with API classes for full JavaEE profile:

<properties>
    <javaee-api.version>7.0</javaee-api.version>
    <hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>

<depencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee-api.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Also add dependency with particular JPA provider like antonycc suggested:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate-entitymanager.version}</version>
</dependency>

Note <scope>provided</scope> in API dependency section: this means that corresponding jar will not be exported into artifact's lib/, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Swift 4 & iOs 11+

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, handler in

        handler(true)
        // handle deletion here
    }

    let more = UIContextualAction(style: .normal, title: "More") { _, _, handler in

        handler(true)
        // handle more here
    }

    return UISwipeActionsConfiguration(actions: [delete, more])
}

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How to remove all characters after a specific character in python?

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

Output: "This is a test"

How to pass command line arguments to a shell alias?

You actually can't do what you want with Bash aliases, since aliases are static. Instead, use the function you have created.

Look here for more information: http://www.mactips.org/archives/2008/01/01/increase-productivity-with-bash-aliases-and-functions/. (Yes I know it's mactips.org, but it's about Bash, so don't worry.)

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Dropping Unique constraint from MySQL table

If you want to remove unique constraints from mysql database table, use alter table with drop index.

Example:

create table unique_constraints(unid int,activity_name varchar(100),CONSTRAINT activty_uqniue UNIQUE(activity_name),primary key (unid));

alter table unique_constraints drop index activty_uqniue;

Where activty_uqniue is UNIQUE constraint for activity_name column.

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

How to interpolate variables in strings in JavaScript, without concatenation?

Create a method similar to String.format() of Java

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

use

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'

What is the non-jQuery equivalent of '$(document).ready()'?

This works perfectly, from ECMA

document.addEventListener("DOMContentLoaded", function() {
  // code...
});

The window.onload doesn't equal to JQuery $(document).ready because $(document).ready waits only to the DOM tree while window.onload check all elements including external assets and images.

EDIT: Added IE8 and older equivalent, thanks to Jan Derk's observation. You may read the source of this code on MDN at this link:

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "interactive") {
        // Initialize your application or run some code.
    }
}

There are other options apart from "interactive". See the MDN link for details.

Can I change the color of Font Awesome's icon color?

With reference to @ClarkeyBoy answer, below code works fine, if using latest version of Font-Awesome icons or if you using fa classes

.fa.icon-white {
    color: white;
}

And, then add icon-white to existing class

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

ASP.NET MVC ActionLink and post method

Use this link inside Ajax.BeginForm

@Html.ActionLink(
    "Save", 
    "SaveAction", 
    null, 
    null, 
    onclick = "$(this).parents('form').attr('action', $(this).attr('href'));$(this).parents('form').submit();return false;" })

;)

How to convert Set<String> to String[]?

Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.

String[] GPXFILES1 = myset.toArray(String[]::new);

If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

String[] GPXFILES1 = myset.toArray(new String[0]);

Convert a python 'type' object to a string

>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

what do you mean by convert into a string? you can define your own repr and str_ methods:

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

or i dont know..please add explainations ;)

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.

Apple Mac image on Amazon EC2?

Can you run OS X on an Amazon EC2 instance?

There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:

Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)

To find more, search for "Mac OS X hosting" and you'll find more options.

How do I execute a program from Python? os.system fails due to spaces in path

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

Can't connect to localhost on SQL Server Express 2012 / 2016

After doing the steps which were mentioned by @Ravindra Bagale, Try this step. Server name: localhost\{Instance name you were gave}

enter image description here

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

To remove the frame of the chart

for spine in plt.gca().spines.values():
  spine.set_visible(False)

I hope this could work

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

And that work form me!

I hope it could be useful for some body else!

ProgressDialog is deprecated.What is the alternate one to use?

This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. link

It's deprecated at Android O because of Google new UI standard

RunAs A different user when debugging in Visual Studio

I'm using Visual Studio 2015 and attempting to debug a website with different credentials.

(I'm currently testing a website on a development network that has a copy of the live active directory; I can "hijack" user accounts to test permissions in a safe way)

  1. Begin debugging with your normal user, ensure you can get to http://localhost:8080 as normal etc
  2. Give the other user "Full Control" access to your normal user's home directory, ie, C:\Users\Colin
  3. Make the other user an administrator on your machine. Right click Computer > Manage > Add other user to Administrator group
  4. Run Internet Explorer as the other user (Shift + Right Click Internet Explorer, Run as different user)
  5. Go to your localhost URL in that IE window

Really convenient to do some quick testing. The Full Control access is probably overkill but I develop on an isolated network. If anyone adds notes about more specific settings I'll gladly edit this post in future.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

How to launch an EXE from Web page (asp.net)

How about something like:

<a href="\\DangerServer\Downloads\MyVirusArchive.exe" 
  type="application/octet-stream">Don't download this file!</a>

Matplotlib/pyplot: How to enforce axis range?

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.

I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with

lims = xlim()
xlim([lims[1], lims[0]]) 

Ruby get object keys as array

Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.

How to replace all dots in a string using JavaScript

replaceAll(search, replaceWith) [MDN]

 ".a.b.c.".replaceAll('.', ' ')
 // result: " a b c "

 // Using RegEx. You MUST use a global RegEx.
 ".a.b.c.".replaceAll(/\./g, ' ')
 // result: " a b c "
    

replaceAll() replaces ALL occurrences of search with replaceWith.

It's actually the same as using replace() [MDN] with a global regex(*), merely replaceAll() is a bit more readable in my view.

(*) Meaning it'll match all occurrences.


Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Add floating point value to android resources/values

There is a solution:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

Format = enclosing data type:

  • float
  • boolean
  • fraction
  • integer
  • ...

and type stands for:

Type = resource type (referenced with R.XXXXX.name):

  • color
  • dimen
  • string
  • style
  • etc...

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.


Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

Basic authentication with fetch?

You are missing a space between Basic and the encoded username and password.

headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

Oracle ORA-12154: TNS: Could not resolve service name Error?

@Warren and @DCookie have covered the solution, one thing to emphasise is the use of tnsping. You can use this to prove your TNSNames is correct before attempting to connect.

Once you have set up tnsnames correctly you could use ODBC or try TOra which will use your native oracle connection. TOra or something similar (TOAD, SQL*Plus etc) will prove invaluable in debugging and improving your SQL.

Last but not least when you eventually connect with ASP.net remember that you can use the Oracle data connection libraries. See Oracle.com for a host of resources.

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

How to declare and display a variable in Oracle

Make sure that, server output is on otherwise output will not be display;

sql> set serveroutput on;

declare
  n number(10):=1;
begin
  while n<=10
 loop
   dbms_output.put_line(n);
   n:=n+1;
 end loop;
end;
/

Outout: 1 2 3 4 5 6 7 8 9 10

How to represent empty char in Java Character class

As Character is a class deriving from Object, you can assign null as "instance":

Character myChar = null;

Problem solved ;)

java.lang.IllegalArgumentException: contains a path separator

This method opens a file in the private data area of the application. You cannot open any files in subdirectories in this area or from entirely other areas using this method. So use the constructor of the FileInputStream directly to pass the path with a directory in it.

Does it matter what extension is used for SQLite database files?

Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.

How do we count rows using older versions of Hibernate (~2009)?

Here is what official hibernate docs tell us about this:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

However, it doesn't always return Integer instance, so it is better to use java.lang.Number for safety.

Node.js create folder or use existing

Good way to do this is to use mkdirp module.

$ npm install mkdirp

Use it to run function that requires the directory. Callback is called after path is created or if path did already exists. Error err is set if mkdirp failed to create directory path.

var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) { 

    // path exists unless there was an error

});

How to kill/stop a long SQL query immediately?

In my part my sql hanged up when I tried to close it while endlessly running. So what I did is I open my task manager and end task my sql query. This stop my sql and restarted it.

Iterating through array - java

You can import the lib org.apache.commons.lang.ArrayUtils

There is a static method where you can pass in an int array and a value to check for.

contains(int[] array, int valueToFind) Checks if the value is in the given array.

ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

they are two different things..

[] is declaring an Array:
given, a list of elements held by numeric index.

{} is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array". but are not arrays, in their representation.

You can read more @ This Article

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

MySql Inner Join with WHERE clause

You could only write one where clause.

 SELECT table1.f_id  FROM table1
 INNER JOIN table2
 ON table2.f_id = table1.f_id
 where table1.f_com_id = '430' AND      
 table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'

How to remove a class from elements in pure JavaScript?

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.classList.remove("hover");
});

You can patch .classList into IE9. Otherwise, you'll need to modify the .className.

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.className = el.className.replace(/\bhover\b/, "");
});

The .forEach() also needs a patch for IE8, but that's pretty common anyway.

How to convert datatype:object to float64 in python?

X = np.array(X, dtype=float)

You can use this to convert to array of float in python 3.7.6

Attach to a processes output for viewing

I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc path. So if you have a program running, whose ID is 1199, cd into it:

$ cd /proc/1199

Then look for the fd directory underneath

$ cd fd

This fd directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f the one you need - in this case, stdout):

$ tail -f 1

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

How to get duplicate items from a list using LINQ?

I was trying to solve the same with a list of objects and was having issues because I was trying to repack the list of groups into the original list. So I came up with looping through the groups to repack the original List with items that have duplicates.

public List<MediaFileInfo> GetDuplicatePictures()
{
    List<MediaFileInfo> dupes = new List<MediaFileInfo>();
    var grpDupes = from f in _fileRepo
                   group f by f.Length into grps
                   where grps.Count() >1
                   select grps;
    foreach (var item in grpDupes)
    {
        foreach (var thing in item)
        {
            dupes.Add(thing);
        }
    }
    return dupes;
}

How to import and use image in a Vue single file component?

You can also use the root shortcut like so

  <template>
   <div class="container">
    <h1>Recipes</h1>
      <img src="@/assets/burger.jpg" />
   </div>
  </template>

Although this was Nuxt, it should be same with Vue CLI.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I was getting a same error. I found out the solution that I had created the primary key in the main table as BIGINT UNSIGNED and was declaring it as a foreign key in the second table as only BIGINT.

When I declared my foreign key as BIGINT UNSIGED in second table, everything worked fine, even didn't need any indexes to be created.

So it was a datatype mismatch between the primary key and the foreign key :)

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

How can I check if two segments intersect?

Here's a solution using dot products:

# assumes line segments are stored in the format [(x0,y0),(x1,y1)]
def intersects(s0,s1):
    dx0 = s0[1][0]-s0[0][0]
    dx1 = s1[1][0]-s1[0][0]
    dy0 = s0[1][1]-s0[0][1]
    dy1 = s1[1][1]-s1[0][1]
    p0 = dy1*(s1[1][0]-s0[0][0]) - dx1*(s1[1][1]-s0[0][1])
    p1 = dy1*(s1[1][0]-s0[1][0]) - dx1*(s1[1][1]-s0[1][1])
    p2 = dy0*(s0[1][0]-s1[0][0]) - dx0*(s0[1][1]-s1[0][1])
    p3 = dy0*(s0[1][0]-s1[1][0]) - dx0*(s0[1][1]-s1[1][1])
    return (p0*p1<=0) & (p2*p3<=0)

Here's a visualization in Desmos: Line Segment Intersection

Run cURL commands from Windows console

Currently in Windows 10 build 17063 and later, cURL comes by default with windows. Then you don't need to download it and just use curl.exe.

Converting file size in bytes to human-readable string

There are lots of great answers here. But if your looking for a really simple way, and you don't mind a popular library, a great solution is filesize https://www.npmjs.com/package/filesize

It has lots of options and the usage is simple e.g.

filesize(265318); // "259.1 KB"

Taken from their excellent examples

zsh compinit: insecure directories

This morning, some packages in my system updated, and left me with this error message. I am using Ubuntu 18.04.

Apparently, something in the update changed the username and group to numbers, instead of root, as so:

# There are insecure files: /usr/share/zsh/vendor-completions/_code
# sudo ls -alh
-rw-r--r-- 1  131  142 2.6K 2019-10-10 16:28 _code

I simply changed the user and group for this file back to root and the problem went away. I did not need to change any permissions, and would caution against doing so unless the underlying cause of the problem is understood.

sudo chown root _code && sudo chgrp root _code

After switching 131 and 142 back to root, this error message from zsh went away.

How to import multiple .csv files at once?

Using purrr and including file IDs as a column:

library(tidyverse)


p <- "my/directory"
files <- list.files(p, pattern="csv", full.names=TRUE) %>%
    set_names()
merged <- files %>% map_dfr(read_csv, .id="filename")

Without set_names(), .id= will use integer indicators, instead of actual file names.

If you then want just the short filename without the full path:

merged <- merged %>% mutate(filename=basename(filename))

Nesting queries in SQL

You need to join the two tables and then filter the result in where clause:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

Parse an URL in JavaScript

Web Workers provide an utils URL for url parsing.

urllib2.HTTPError: HTTP Error 403: Forbidden

This will work in Python 3

import urllib.request

user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,} 

request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need

C# : Passing a Generic Object

It doesn't compile because T could be anything, and not everything will have the myvar field.

You could make myvar a property on ITest:

public ITest
{
    string myvar{get;}
}

and implement it on the classes as a property:

public class MyClass1 : ITest
{
    public string myvar{ get { return "hello 1"; } }
}

and then put a generic constraint on your method:

public void PrintGeneric<T>(T test) where T : ITest
{
    Console.WriteLine("Generic : " + test.myvar);
}

but in that case to be honest you are better off just passing in an ITest:

public void PrintGeneric(ITest test)
{
    Console.WriteLine("Generic : " + test.myvar);
}

Retrieve Button value with jQuery

I know this was posted a while ago, but in case anyone is searching for an answer and really wants to use a button element instead of an input element...

You can not use .attr('value') or .val() with a button in IE. IE reports both the .val() and .attr("value") as being the text label (content) of the button element instead of the actual value of the value attribute.

You can work around it by temporarily removing the button's label:

var getButtonValue = function($button) {
    var label = $button.text(); 
    $button.text('');
    var buttonValue = $button.val();
    $button.text(label);
    return buttonValue;
}

There are a few other quirks with buttons in IE. I have posted a fix for the two most common issues here.

:: (double colon) operator in Java 8

It seems its little late but here are my two cents. A lambda expression is used to create anonymous methods. It does nothing but call an existing method, but it is clearer to refer to the method directly by its name. And method reference enables us to do that using method-reference operator :: .

Consider the following simple class where each employee has a name and grade.

public class Employee {
    private String name;
    private String grade;

    public Employee(String name, String grade) {
        this.name = name;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

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

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

Suppose we have a list of employees returned by some method and we want to sort the employees by their grade. We know we can make use of anonymous class as:

    List<Employee> employeeList = getDummyEmployees();

    // Using anonymous class
    employeeList.sort(new Comparator<Employee>() {
           @Override
           public int compare(Employee e1, Employee e2) {
               return e1.getGrade().compareTo(e2.getGrade());
           }
    });

where getDummyEmployee() is some method as:

private static List<Employee> getDummyEmployees() {
        return Arrays.asList(new Employee("Carrie", "C"),
                new Employee("Fanishwar", "F"),
                new Employee("Brian", "B"),
                new Employee("Donald", "D"),
                new Employee("Adam", "A"),
                new Employee("Evan", "E")
                );
    }

Now we know that Comparator is a Functional Interface. A Functional Interface is the one with exactly one abstract method (though it may contain one or more default or static methods). Lambda expression provides implementation of @FunctionalInterface so a functional interface can have only one abstract method. We can use lambda expression as:

employeeList.sort((e1,e2) -> e1.getGrade().compareTo(e2.getGrade())); // lambda exp

It seems all good but what if the class Employee also provides similar method:

public class Employee {
    private String name;
    private String grade;
    // getter and setter
    public static int compareByGrade(Employee e1, Employee e2) {
        return e1.grade.compareTo(e2.grade);
    }
}

In this case using the method name itself will be more clear. Hence we can directly refer to method by using method reference as:

employeeList.sort(Employee::compareByGrade); // method reference

As per docs there are four kinds of method references:

+----+-------------------------------------------------------+--------------------------------------+
|    | Kind                                                  | Example                              |
+----+-------------------------------------------------------+--------------------------------------+
| 1  | Reference to a static method                          | ContainingClass::staticMethodName    |
+----+-------------------------------------------------------+--------------------------------------+
| 2  |Reference to an instance method of a particular object | containingObject::instanceMethodName | 
+----+-------------------------------------------------------+--------------------------------------+
| 3  | Reference to an instance method of an arbitrary object| ContainingType::methodName           |
|    | of a particular type                                  |                                      |  
+----+-------------------------------------------------------+--------------------------------------+
| 4  |Reference to a constructor                             | ClassName::new                       |
+------------------------------------------------------------+--------------------------------------+

How to overlay density plots in R?

ggplot2 is another graphics package that handles things like the range issue Gavin mentions in a pretty slick way. It also handles auto generating appropriate legends and just generally has a more polished feel in my opinion out of the box with less manual manipulation.

library(ggplot2)

#Sample data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
                   , lines = rep(c("a", "b"), each = 100))
#Plot.
ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)

enter image description here

Convert HTML + CSS to PDF

Try grabbing the latest nightly dompdf build - I was using an older version that was a terrible resource hog and took forever to render my pdf. After grabbing a nightly from here.

It only took a few seconds to generate the PDF - AND it was just as nicely rendered as with PrinceXML / Docraptor. Seems like they've seriously optimized the dompdf code since I last used it!

URL string format for connecting to Oracle database with JDBC

String host = <host name>
String port = <port>
String service = <service name>
String dbName = <db schema>+"."+service
String url = "jdbc:oracle:thin:@"+host+":"+"port"+"/"+dbName

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

Do the move and the modify in separate commits.

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Is there a difference between PhoneGap and Cordova commands?

Above, Abhishek mentions the command line differences specified in two URLS:

  1. PhoneGap: http://docs.phonegap.com/en/edge/guide_cli_index.md.html

  2. Cordova: http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface

One thing to point out is that, as of this post, the phonegap one looks to be almost the same as the cordova one, and is probably not an accurate image of the command line option differences. As such, I installed both on my system so I could look at the differences.

These are just a few of them. Hopefully they are brought more in sync sometime. If anyone has better information, please tell me.

  1. Adding platforms seems to be done differently between the two commands ( phonegap uses "install" command, cordova uses "platform add" command )
  2. Adding/creating projects seems to be the same between the two commands ( same command line options supported )
  3. Obviously, as has been stated, phonegap can use PhoneGap Build, so it has the corresponding options to trigger that or local builds
  4. Quite a few other significant command line differences, simply by running "cordova help" and "phonegap help" and comparing the two.

I guess my point is that the phonegap CLI documention mentioned quite often is not really for the phonegap CLI, but for the cordova CLI, at this time. Please tell me if I am missing something. Thanks.

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

How to un-commit last un-pushed git commit without losing the changes

There are a lot of ways to do so, for example:

in case you have not pushed the commit publicly yet:

git reset HEAD~1 --soft   

That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man


In case you did push publicly (on a branch called 'master'):

git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )

revert commit normally and push

git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master

now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit option:

git revert --no-commit 86b48ba (hash of the revert commit).

I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

Show SOME invisible/whitespace characters in Eclipse

Navigate to Window > Preferences > General > Editors > Text Editors

Click on the CheckBox "Show whitespace characters".

enter image description here

Thats all.!!!

INNER JOIN same table

I think the problem is in your JOIN condition.

SELECT user.user_fname,
       user.user_lname,
       parent.user_fname,
       parent.user_lname
FROM users AS user
JOIN users AS parent 
  ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]

Edit: You should probably use LEFT JOIN if there are users with no parents.

Good ways to manage a changelog using git?

A more to-the-point CHANGELOG.

git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Try this one

cd android && ./gradlew clean && ./gradlew :app:bundleRelease

passing argument to DialogFragment

So there is two ways to pass values from fragment/activity to dialog fragment:-

  1. Create dialog fragment object with make setter method and pass value/argument.

  2. Pass value/argument through bundle.

Method 1:

// Fragment or Activity 
@Override
public void onClick(View v) {
     DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
     dialog.setValue(header, body);
     dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");         
}


//  your dialog fragment
public class MyDialogFragment extends DialogFragment {
    String header; 
    String body;
    public void setValue(String header, String body) {   
          this.header = header;
          this.body = body;
    }
    // use above variable into your dialog fragment
}

Note:- This is not best way to do

Method 2:

// Fragment or Activity 
@Override
public void onClick(View v) {
     DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
     
     Bundle bundle = new Bundle();
     bundle.putString("header", "Header");
     bundle.putString("body", "Body");  
     dialog.setArguments(bundle);
     dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");         
}


//  your dialog fragment
public class MyDialogFragment extends DialogFragment {
    String header; 
    String body;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
             header = getArguments().getString("header","");
             body = getArguments().getString("body","");
        }
    }
    // use above variable into your dialog fragment
}

Note:- This is the best way to do.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

Export DataTable to Excel with Open Xml SDK in c#

I tried accepted answer and got message saying generated excel file is corrupted when trying to open. I was able to fix it by doing few modifications like adding below line end of the code.

workbookPart.Workbook.Save();

I have posted full code @ Export DataTable to Excel with Open XML in c#

Android OnClickListener - identify a button

You will learn the way to do it, in an easy way, is:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

Or, if you are working with just one clicklistener, you can do:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}

Though, I don't recommend doing it that way since you will have to add an if for each button you use. That's hard to maintain.

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
        data.push({
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]
        });
    }

jQuery.ajax({
    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {
...

Now inside php when you do this

print_r($_POST);

You will get ..

Array
(
    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
        (
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75
        )
)

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

How to make a variadic macro (variable number of arguments)

explained for g++ here, though it is part of C99 so should work for everyone

http://www.delorie.com/gnu/docs/gcc/gcc_44.html

quick example:

#define debug(format, args...) fprintf (stderr, format, args)

CardView Corner Radius

An easy way to achieve this would be:

1.Make a custom background resource (like a rectangle shape) with rounded corners.

2.set this custom background using the command -

cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);

this worked for me.

The XML layout I made with top left and bottom right radius.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>

In your case, you need to change only topLeftRadius as well as topRightRadius.

If you have a layout that overlaps with the corners of the card view and has a different color maybe, then you might need a different background resource file for the layout and in the xml set this background resource to your layout.

I tried and tested the above method. Hope this helps you.

Pandas - Plotting a stacked Bar Chart

Are you getting errors, or just not sure where to start?

%pylab inline
import pandas as pd
import matplotlib.pyplot as plt

df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)

stacked bar plot

Changing three.js background to transparent or other color

I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:

renderer.setClearColorHex( 0x000000, 1 );

in your threejs init function. Change it to:

renderer.setClearColorHex( 0xffffff, 1 );

Update: Thanks to HdN8 for the updated solution:

renderer.setClearColor( 0xffffff, 0);

Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor() function:

var renderer = new THREE.WebGLRenderer({ alpha: true });

Update #3: Mr.doob points out that since r78 you can alternatively use the code below to set your scene's background colour:

var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

Split a string into an array of strings based on a delimiter

For delphi 2010, you need to create your own split function.

function Split(const Texto, Delimitador: string): TStringArray;
var
  i: integer;
  Len: integer;
  PosStart: integer;
  PosDel: integer;
  TempText:string;
begin
  i := 0;
  SetLength(Result, 1);
  Len := Length(Delimitador);
  PosStart := 1;
  PosDel := Pos(Delimitador, Texto);
  TempText:=  Texto;
  while PosDel > 0 do
    begin
      Result[i] := Copy(TempText, PosStart, PosDel - PosStart);
      PosStart := PosDel + Len;
      TempText:=Copy(TempText, PosStart, Length(TempText));
      PosDel := Pos(Delimitador, TempText);
      PosStart := 1;
      inc(i);
      SetLength(Result, i + 1);
    end;
  Result[i] := Copy(TempText, PosStart, Length(TempText));
end;

You can refer to it as such

type
  TStringArray = array of string;
var Temp2:TStringArray;
Temp1="hello:world";
Temp2=Split(Temp1,':')

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

What is CDATA in HTML?

From http://en.wikipedia.org/wiki/CDATA:

Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>

How to change DatePicker dialog color for Android 5.0

You don't have create theme just write it in your dialog creation object

DatePickerDialog datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this, mYear, mMonth, mDay);

follow this it will give you all type date picker style it's really work

http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

How to automatically generate N "distinct" colors?

If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

Why not just evenly distribute them through the spectrum, like so:

IEnumerable<Color> CreateUniqueColors(int nColors)
{
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);
}

If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

Am I underthinking this?

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

How to repeat a string a variable number of times in C++?

Here's an example of the string "abc" repeated 3 times:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main() {
    ostringstream repeated;
    fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
    cout << "repeated: " << repeated.str() << endl;  // repeated: abcabcabc
    return 0;
}

com.jcraft.jsch.JSchException: UnknownHostKey

It is a security risk to avoid host key checking.

JSch uses HostKeyRepository interface and its default implementation KnownHosts class to manage this. You can provide an alternate implementation that allows specific keys by implementing HostKeyRepository. Or you could keep the keys that you want to allow in a file in the known_hosts format and call

jsch.setKnownHosts(knownHostsFileName);

Or with a public key String as below.

String knownHostPublicKey = "mysite.com ecdsa-sha2-nistp256 AAAAE............/3vplY";
jsch.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

see Javadoc for more details.

This would be a more secure solution.

Jsch is open source and you can download the source from here. In the examples folder, look for KnownHosts.java to know more details.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Sorting an Array of int using BubbleSort

public static void BubbleSort(int[] array){
        boolean swapped ;
        do {
            swapped = false;
            for (int i = 0; i < array.length - 1; i++) {
                if (array[i] > array[i + 1]) {
                    int temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                    swapped = true;
                }
            }
        }while (swapped);
    }

python: unhashable type error

I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c is a list of list of strings, or whatever you designed this function to work with

For example you might get this error if you passed [c] to the function instead of c

How to create a delay in Swift?

Try the following implementation in Swift 3.0

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

How do I select an entire row which has the largest ID in the table?

You could use a subselect:

SELECT row 
FROM table 
WHERE id=(
    SELECT max(id) FROM table
    )

Note that if the value of max(id) is not unique, multiple rows are returned.

If you only want one such row, use @MichaelMior's answer,

SELECT row from table ORDER BY id DESC LIMIT 1

Batch file to delete files older than N days

ROBOCOPY works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, move the files to the trash!!!

This is is a few lines of my backup batch file for example:

SET FilesToClean1=C:\Users\pauls12\Temp
SET FilesToClean2=C:\Users\pauls12\Desktop\1616 - Champlain\Engineering\CAD\Backups

SET RecycleBin=C:\$Recycle.Bin\S-1-5-21-1480896384-1411656790-2242726676-748474

robocopy "%FilesToClean1%" "%RecycleBin%" /mov /MINLAD:15 /XA:SH /NC /NDL /NJH /NS /NP /NJS
robocopy "%FilesToClean2%" "%RecycleBin%" /mov /MINLAD:30 /XA:SH /NC /NDL /NJH /NS /NP /NJS

It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.

This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.

Cheers!