Programs & Examples On #Customization

Modifying the default state of an application to suit a user's preferences or to address the unique requirements of a particular objective.

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

how do I use an enum value on a switch statement in C++

You can use an enumerated value just like an integer:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

How to handle an IF STATEMENT in a Mustache template?

In general, you use the # syntax:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}

The goal is to move as much logic as possible out of the template (which makes sense).

How to check whether dynamically attached event listener exists or not?

I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event) and getEvents(Node elm) which you can utilize. Be aware that it modifies the EventTarget prototype method add/RemoveEventListener, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...

More info at GitHub

Live Demo

Script:

var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();

PostgreSQL column 'foo' does not exist

I also ran into this error when I was using Dapper and forgot to input a parameterized value.

To fix I had to ensure that the object passed in as a parameter had properties matching the parameterised values in the SQL string.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

How do I run a single test using Jest?

Here is my take:

./node_modules/.bin/jest --config test/jest-unit-config.json --runInBand src/components/OpenForm/OpenForm.spec.js -t 'show expanded'

Notes:

  • ./node_modules/.bin/... is a wonderful way, to access the locally installed Jest (or Mocha or...) binary that came with the locally installed package. (Yes, in your npm scripts you can jest with nothing before, but this is handy on command line... (that's also a good start for your debugging config, whichever IDE you are using...)
  • Your project might not have a set of configuration options. But if it does (peek into the scripts in package.json), this is, what you need.
  • --runInBand – as said, don't know about your configuration, but if you concentrate on developing/fixing a single test, you rather do not want to deal with web workers...
  • Yes, you can give the whole, explicit path to your file
  • Optionally, you can use -t to not run all tests in that file, but only a single one (here: the one, that has something with ‘show expanded’ in its name). Same effect can be achieved by glueing .only() into that file.

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

Merge PDF files

A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):

import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
    for file in files:
        filepath = subdir + os.sep + file
        # you can have multiple endswith
        if filepath.endswith((".pdf", ".PDF")):
            file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)

for k, v in file_dict.items():
    print(k, v)
    merger.append(v)

merger.write("combined_result.pdf")

The term "Add-Migration" is not recognized

These are the steps I followed and it solved the problem

1)Upgraded my Power shell from version 2 to 3

2)Closed the PM Console

3)Restarted Visual Studio

4)Ran the below command in PM Console dotnet restore

5)Add-Migration InitialMigration

It worked !!!

Remote debugging a Java application

I'd like to emphasize that order of arguments is important.

For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar command opens debugger port,

but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 command doesn't.

How to go from one page to another page using javascript?

Verifying that a user is an admin in javascript leads to trouble because javascript code is visible to anyone. The server is the one who should tell the difference between an admin and a regular user AFTER the login process and then generate the new page accordingly.

Maybe that's not what you are trying to do so to answer your question:

window.location.href="<the page you are going to>";

Find JavaScript function definition in Chrome

Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

LINQ .Any VS .Exists - What's the difference?

As a continuation on Matas' answer on benchmarking.

TL/DR: Exists() and Any() are equally fast.

First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.

The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.

static void Main(string[] args)
    {
        Console.WriteLine("Generating list...");
        List<string> list = GenerateTestList(1000000);
        var s = string.Empty;

        Stopwatch sw;
        Stopwatch sw2;
        List<long> existsTimes = new List<long>();
        List<long> anyTimes = new List<long>();

        Console.WriteLine("Executing...");
        for (int j = 0; j < 1000; j++)
        {
            sw = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw.Stop();
                existsTimes.Add(sw.ElapsedTicks);
            }
        }

        for (int j = 0; j < 1000; j++)
        {
            sw2 = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw2.Stop();
                anyTimes.Add(sw2.ElapsedTicks);
            }
        }

        long existsFastest = existsTimes.Min();
        long anyFastest = anyTimes.Min();

        Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
        Console.WriteLine("Benchmark finished. Press any key.");
        Console.ReadKey();
    }

    public static List<string> GenerateTestList(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            Random r = new Random();
            int it = r.Next(0, 100);
            list.Add(new string('s', it));
        }
        return list;
    }

After executing the above code 4 times (which in turn do 1 000 Exists() and Any() on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.

Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks

Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks

Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks

Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks

There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists() and Any() instead, that slight difference would disappear more or less.

How can I run PowerShell with the .NET 4 runtime?

If you only need to execute a single command, script block, or script file in .NET 4, try using Activation Configuration Files from .NET 4 to start only a single instance of PowerShell using version 4 of the CLR.

Full details:

http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/

An example PowerShell module:

https://gist.github.com/882528

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

Java - Access is denied java.io.FileNotFoundException

Make sure that the directory exists, you have permission to access it and add the file to the path to write the log:

File file = new File("D:/Data/" + item.getFileName());

Copying a local file from Windows to a remote server using scp

Drive letters can be used in the target like

scp some_file user@host:/c/temp

where c is the drive letter. It's treated like a directory.

Maybe this works on the source, too.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

I was also getting the same issue I tried multiple IPs like my public IP and localhost default IP 127.0.0.1 in windows and default gateway but same response. but I forget to check by

C:> ipconfig

ipconfig cleanly say what is my actual IP address of that adapter with which I have connected like I was connected with Wifi adapter my IP address will show me as:

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::69fa:9475:431e:fad7%11
   IPv4 Address. . . . . . . . . . . : 192.168.15.92

I hope this will help you.

Hex-encoded String to Byte Array

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.

The apache commons-codec has a class for that, Hex.

String s = "9B7D2C34A366BF890C730641E6CECF6F";    
byte[] bytes = Hex.decodeHex(s.toCharArray());

jQuery select element in parent window

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

How do I get logs from all pods of a Kubernetes replication controller?

Another solution that I would consider is using K9S which is a great kube administration tool.

After installation, the usage is very straightforward:

 k9s -n my-namespace --context the_context_name_in_kubeconfig

(If kubeconfig is not in the default location add KUBECONFIG=path/to/kubeconfig prefix).

The default view will list all pods as a list:

enter image description here

We can change the view to other Kube controllers like replica set (question asked for replication controllers so notice they are deprecated), deployments, cron jobs, etc' by entering a colon : and start typing the desired controller - as we can see K9S provides autocompletion for us:

enter image description here

And we can see all replica sets in the current namespace:

enter image description here

We can just choose the desired replica set by clicking enter and then we'll see the list of all pods which are related to this replica set - we can then press on 'l' to view logs of each pod.

So, unlike in the case of stern, we still need to go on each pod and view its logs but I think it is very convenient with K9S - we first view all pods of a related controller and then investigate logs of each pod by simply navigating with enter, l and escape.

How to create composite primary key in SQL Server 2008

For MSSQL Server 2012

CREATE TABLE usrgroup(
  usr_id int FOREIGN KEY REFERENCES users(id),
  grp_id int FOREIGN KEY REFERENCES groups(id),

  PRIMARY KEY (usr_id, grp_id)
)

UPDATE

I should add !

If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:

CREATE TABLE usrgroup(
  usr_id int,
  grp_id int,

  CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
  CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),

  CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)

Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.

I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.

window.close() doesn't work - Scripts may close only the windows that were opened by it

I searched for many pages of the web through of the Google and here on the Stack Overflow, but nothing suggested resolved my problem.

After many attempts, I've changed my way of to test that controller. Then I have discovered that the problem occurs always which I reopened the page through of the Ctrl + Shift + T shortcut in Chrome. So the page ran, but without a parent window reference, and because this can't be closed.

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Android ListView headers

What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library

https://github.com/emilsjolander/StickyListHeaders

Convert the date to long in millis [do not include the time] and make it as the header Id.

@Override
public long getHeaderId(int position) {
    return <date in millis>;
}

How to get directory size in PHP

Thanks to Jonathan Sampson, Adam Pierce and Janith Chinthana I did this one checking for most performant way to get the directory size. Should work on Windows and Linux Hosts.

static function getTotalSize($dir)
{
    $dir = rtrim(str_replace('\\', '/', $dir), '/');

    if (is_dir($dir) === true) {
        $totalSize = 0;
        $os        = strtoupper(substr(PHP_OS, 0, 3));
        // If on a Unix Host (Linux, Mac OS)
        if ($os !== 'WIN') {
            $io = popen('/usr/bin/du -sb ' . $dir, 'r');
            if ($io !== false) {
                $totalSize = intval(fgets($io, 80));
                pclose($io);
                return $totalSize;
            }
        }
        // If on a Windows Host (WIN32, WINNT, Windows)
        if ($os === 'WIN' && extension_loaded('com_dotnet')) {
            $obj = new \COM('scripting.filesystemobject');
            if (is_object($obj)) {
                $ref       = $obj->getfolder($dir);
                $totalSize = $ref->size;
                $obj       = null;
                return $totalSize;
            }
        }
        // If System calls did't work, use slower PHP 5
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
        foreach ($files as $file) {
            $totalSize += $file->getSize();
        }
        return $totalSize;
    } else if (is_file($dir) === true) {
        return filesize($dir);
    }
}

How to display special characters in PHP

You can have a mix of PHP and HTML in your PHP files... just do something like this...

<?php
$string = htmlentities("Résumé");
?>

<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>

That should output Résumé just how you want it to.

If you don't have short tags enabled, replace the <?= $string ?> with <?php echo $string; ?>

require(vendor/autoload.php): failed to open stream

Change the auto_prepend_file property on php.ini

; Automatically add files before PHP document. 
;http://php.net/auto-prepend-file 
auto_prepend_file =

How to set the default value for radio buttons in AngularJS?

In Angular 2 this is how we can set the default value for radio button:

HTML:

<label class="form-check-label">
          <input type="radio" class="form-check-input" name="gender" 
          [(ngModel)]="gender" id="optionsRadios1" value="male">
          Male
</label>

In the Component Class set the value of 'gender' variable equal to the value of radio button:

gender = 'male';

Number of processors/cores in command line

When someone asks for "the number of processors/cores" there are 2 answers being requested. The number of "processors" would be the physical number installed in sockets on the machine.

The number of "cores" would be physical cores. Hyperthreaded (virtual) cores would not be included (at least to my mind). As someone who writes a lot of programs with thread pools, you really need to know the count of physical cores vs cores/hyperthreads. That said, you can modify the following script to get the answers that you need.

#!/bin/bash

MODEL=`cat /cpu/procinfo | grep "model name" | sort | uniq`
ALL=`cat /proc/cpuinfo | grep "bogo" | wc -l`
PHYSICAL=`cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l`
CORES=`cat /proc/cpuinfo | grep "cpu cores" | sort | uniq | cut -d':' -f2`
PHY_CORES=$(($PHYSICAL * $CORES))
echo "Type $MODEL"
echo "Processors $PHYSICAL"
echo "Physical cores $PHY_CORES"
echo "Including hyperthreading cores $ALL"

The result on a machine with 2 model Xeon X5650 physical processors each with 6 physical cores that also support hyperthreading:

Type model name : Intel(R) Xeon(R) CPU           X5650  @ 2.67GHz
Processors 2
Physical cores 12
Including hyperthreading cores 24

On a machine with 2 mdeol Xeon E5472 processors each with 4 physical cores that doesn't support hyperthreading

Type model name : Intel(R) Xeon(R) CPU           E5472  @ 3.00GHz
Processors 2
Physical cores 8
Including hyperthreading cores 8

How to make an HTTP request + basic auth in Swift

go plain for SWIFT 3 and APACHE simple Auth:

func urlSession(_ session: URLSession, task: URLSessionTask,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    let credential = URLCredential(user: "test",
                                   password: "test",
                                   persistence: .none)

    completionHandler(.useCredential, credential)


}

Iterate over object attributes in python

in general put a __iter__ method in your class and iterate through the object attributes or put this mixin class in your class.

class IterMixin(object):
    def __iter__(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

Your class:

>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}

Display last git commit comment

git log -1 will display the latest commit message or git log -1 --oneline if you only want the sha1 and associated commit message to be displayed.

Foreign Key naming scheme

Try using upper-cased Version 4 UUID with first octet replaced by FK and '_' (underscore) instead of '-' (dash).

E.g.

  • FK_4VPO_K4S2_A6M1_RQLEYLT1VQYV
  • FK_1786_45A6_A17C_F158C0FB343E
  • FK_45A5_4CFA_84B0_E18906927B53

Rationale is the following

  • Strict generation algorithm => uniform names;
  • Key length is less than 30 characters, which is naming length limitation in Oracle (before 12c);
  • If your entity name changes you don't need to rename your FK like in entity-name based approach (if DB supports table rename operator);
  • One would seldom use foreign key constraint's name. E.g. DB tool usually shows what the constraint applies to. No need to be afraid of cryptic look, because you can avoid using it for "decryption".

How to stop C++ console application from exiting immediately?

If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.

Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.

On select change, get data attribute value

Try the following:

$('select').change(function(){
  alert($(this).children('option:selected').data('id'));
});

Your change subscriber subscribes to the change event of the select, so the this parameter is the select element. You need to find the selected child to get the data-id from.

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

TCPDF not render all CSS properties

Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul

All the HTML attributes must be enclosed in double-quotes

How to get all of the immediate subdirectories in Python

I have to mention the path.py library, which I use very often.

Fetching the immediate subdirectories become as simple as that:

my_dir.dirs()

The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

Char array in a struct - incompatible assignment?

You can try in this way. I had applied this in my case.

#include<stdio.h>

struct name
{

  char first[20];

  char last[30];

};

//globally

// struct name sara={"Sara","Black"};

int main()

 {

//locally

struct name sara={"Sara","Black"};


printf("%s",sara.first);

printf("%s",sara.last);

}

Best way to convert strings to symbols in hash

http://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys

hash = { 'name' => 'Rob', 'age' => '28' }
hash.symbolize_keys
# => { name: "Rob", age: "28" }

How can I format a decimal to always show 2 decimal places?

If you're using this for currency, and also want the value to be seperated by ,'s you can use

$ {:,.f2}.format(currency_value).

e.g.:

currency_value = 1234.50

$ {:,.f2}.format(currency_value) --> $ 1,234.50

Here is a bit of code I wrote some time ago:

print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))

> At the end of year   1  total paid is         $ 43,806.36
> At the end of year   2  total paid is         $ 87,612.72
> At the end of year   3  total paid is         $ 131,419.08
> At the end of year   4  total paid is         $ 175,225.44
> At the end of year   5  total paid is         $ 219,031.80   <-- Note .80 and not .8
> At the end of year   6  total paid is         $ 262,838.16
> At the end of year   7  total paid is         $ 306,644.52
> At the end of year   8  total paid is         $ 350,450.88
> At the end of year   9  total paid is         $ 394,257.24
> At the end of year  10  total paid is         $ 438,063.60   <-- Note .60 and not .6
> At the end of year  11  total paid is         $ 481,869.96
> At the end of year  12  total paid is         $ 525,676.32
> At the end of year  13  total paid is         $ 569,482.68
> At the end of year  14  total paid is         $ 613,289.04
> At the end of year  15  total paid is         $ 657,095.40   <-- Note .40 and not .4  
> At the end of year  16  total paid is         $ 700,901.76
> At the end of year  17  total paid is         $ 744,708.12
> At the end of year  18  total paid is         $ 788,514.48
> At the end of year  19  total paid is         $ 832,320.84
> At the end of year  20  total paid is         $ 876,127.20   <-- Note .20 and not .2

Connect to external server by using phpMyAdmin

In the config file, change the "host" variable to point to the external server. The config file is called config.inc.php and it will be in the main phpMyAdmin folder. There should be a line like this:

$cfg['Servers'][$i]['host'] = 'localhost';

Just change localhost to your server's IP address.

Note: you may have to configure the external server to allow remote connections, but I've done this several times on shared hosting so it should be fine.

Uninstall old versions of Ruby gems

gem cleanup uses system commands. Installed gems are just directories in the filesystem. If you want to batch delete, use rm -R.

  1. gem environment and note the value of GEM PATHS
  2. cd <your-gem-paths>/gems
  3. ls -1 |grep rjb- |xargs rm -R

Hide keyboard in react-native

Using keyboardShouldPersistTaps in the ScrollView you can pass in "handled", which deals with the issues that people are saying comes with using the ScrollView. This is what the documentation says about using 'handled': the keyboard will not dismiss automatically when the tap was handled by a children, (or captured by an ancestor). Here is where it's referenced.

Transfer data from one HTML file to another

Try this code: In testing.html

function testJS() {
    var b = document.getElementById('name').value,
        url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);

    document.location.href = url;
}

And in next.html:

window.onload = function () {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}

Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc. Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.

PS. i'm an non-native english speaker, will you please correct my message, if necessary

Read a plain text file with php

<?php

$fh = fopen('filename.txt','r');
while ($line = fgets($fh)) {
  // <... Do your work with the line ...>
  // echo($line);
}
fclose($fh);
?>

This will give you a line by line read.. read the notes at php.net/fgets regarding the end of line issues with Macs.

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.

StartDate  
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))

End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))  

I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.

How did I do?

What is the naming convention in Python for variable and function names?

Typically, one follow the conventions used in the language's standard library.

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

Use Python's json module, or simplejson if you don't have python 2.6 or higher.

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

Highlight a word with jQuery

Try highlight: JavaScript text highlighting jQuery plugin. ! Warning - The source code available on this page contains a crypto currency mining script, either use the code below or remove the mining script from the download on the website. !

/*

highlight v4

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:[email protected]>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

Also try the "updated" version of the original script.

/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrance of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('#content').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('#content').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrance of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);

    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);

    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};

Recursively add the entire folder to a repository

I simply used this:

git add app/src/release/*

You simply need to specify the folder to add and then use * to add everything that is inside recursively.

Scrolling to element using webdriver?

It's not a direct answer on question (its not about Actions), but it also allow you to scroll easily to required element:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

This actually intend to return you coordinates (x, y) of element on page, but also scroll down right to target element

Calculating distance between two points, using latitude longitude?

Slightly upgraded answer from @David George:

public static double distance(double lat1, double lat2, double lon1,
                              double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}

public static double distanceBetweenLocations(Location l1, Location l2) {
    if(l1.hasAltitude() && l2.hasAltitude()) {
        return distance(l1.getLatitude(), l2.getLatitude(), l1.getLongitude(), l2.getLongitude(), l1.getAltitude(), l2.getAltitude());
    }
    return l1.distanceTo(l2);
}

distance function is the same, but I've created I small wrapper function, which takes 2 Location objects. Thanks to this, I only use distance function if both of locations actually have altitude, because sometimes they don't. And it can lead to strange results (if location doesn't know its altitude 0 will be returned). In this case, I fall back to classic distanceTo function.

Append data frames together in a for loop

Here are some tidyverse and custom function options that might work depending on your needs:

library(tidyverse)

# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
 data_frame(x = rnorm(5), y = runif(5)) %>% 
    filter(x < y) %>% 
    mutate(x_plus_y = x + y) %>% 
    mutate(i = i)
}

df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
       x      y x_plus_y     i
   <dbl>  <dbl>    <dbl> <int>
1 -0.973 0.673    -0.300     1
2 -0.553 0.0463   -0.507     1
3  0.250 0.716     0.967     2
4 -0.745 0.0640   -0.681     2
5 -0.736 0.228    -0.508     2
6 -0.365 0.496     0.131     3

You could do something similar if you had a directory of files that needed to be combined:

dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)

combine_files <- function(path, file){
  read_csv(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.csv$') %>% 
  map_df(~combine_files(dir_path, .))

# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
  readxl::read_xlsx(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.xlsx$') %>% 
  map_df(~combine_xl_files(dir_path, .))

How to compile without warnings being treated as errors?

-Wall and -Werror compiler options can cause it, please check if those are used in compiler settings.

Creating a 3D sphere in Opengl using Visual C++

In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.

glutSolidSphere is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?

#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>

// your framework of choice here

class SolidSphere
{
protected:
    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;

public:
    SolidSphere(float radius, unsigned int rings, unsigned int sectors)
    {
        float const R = 1./(float)(rings-1);
        float const S = 1./(float)(sectors-1);
        int r, s;

        vertices.resize(rings * sectors * 3);
        normals.resize(rings * sectors * 3);
        texcoords.resize(rings * sectors * 2);
        std::vector<GLfloat>::iterator v = vertices.begin();
        std::vector<GLfloat>::iterator n = normals.begin();
        std::vector<GLfloat>::iterator t = texcoords.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                float const y = sin( -M_PI_2 + M_PI * r * R );
                float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
                float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

                *t++ = s*S;
                *t++ = r*R;

                *v++ = x * radius;
                *v++ = y * radius;
                *v++ = z * radius;

                *n++ = x;
                *n++ = y;
                *n++ = z;
        }

        indices.resize(rings * sectors * 4);
        std::vector<GLushort>::iterator i = indices.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                *i++ = r * sectors + s;
                *i++ = r * sectors + (s+1);
                *i++ = (r+1) * sectors + (s+1);
                *i++ = (r+1) * sectors + s;
        }
    }

    void draw(GLfloat x, GLfloat y, GLfloat z)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x,y,z);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
        glNormalPointer(GL_FLOAT, 0, &normals[0]);
        glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
        glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
        glPopMatrix();
    }
};

SolidSphere sphere(1, 12, 24);

void display()
{
    int const win_width  = …; // retrieve window dimensions from
    int const win_height = …; // framework of choice here
    float const win_aspect = (float)win_width / (float)win_height;

    glViewport(0, 0, win_width, win_height);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, win_aspect, 1, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

#ifdef DRAW_WIREFRAME
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    sphere.draw(0, 0, -5);

    swapBuffers();
}

int main(int argc, char *argv[])
{
    // initialize and register your framework of choice here
    return 0;
}

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

Java logical operator short-circuiting

boolean a = (x < z) && (x == x);

This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).

& is a bitwise operator, but also a boolean AND operator which does not short-circuit.

You can test them by something as follows (see how many times the method is called in each case):

public static boolean getFalse() {
    System.out.println("Method");
    return false;
}

public static void main(String[] args) {
    if(getFalse() && getFalse()) { }        
    System.out.println("=============================");        
    if(getFalse() & getFalse()) { }
}

The project type is not supported by this installation

You could also try to run the following command:

devenv /ResetSkipPkgs

Using NOT operator in IF conditions

No, there is absolutely nothing wrong with using the ! operator in if..then..else statements.

The naming of variables, and in your example, methods is what is important. If you are using:

if(!isPerson()) { ... } // Nothing wrong with this

However:

if(!balloons()) { ... } // method is named badly

It all comes down to readability. Always aim for what is the most readable and you won't go wrong. Always try to keep your code continuous as well, for instance, look at Bill the Lizards answer.

Android: How to handle right to left swipe gestures

import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener

/**
 * Detects left and right swipes across a view.
 */
class OnSwipeTouchListener(context: Context, onSwipeCallBack: OnSwipeCallBack?) : OnTouchListener {

    private var gestureDetector : GestureDetector
    private var onSwipeCallBack: OnSwipeCallBack?=null

    init {

        gestureDetector = GestureDetector(context, GestureListener())
        this.onSwipeCallBack = onSwipeCallBack!!
    }
    companion object {

        private val SWIPE_DISTANCE_THRESHOLD = 100
        private val SWIPE_VELOCITY_THRESHOLD = 100
    }

   /* fun onSwipeLeft() {}

    fun onSwipeRight() {}*/

    override fun onTouch(v: View, event: MotionEvent): Boolean {


        return gestureDetector.onTouchEvent(event)
    }

    private inner class GestureListener : SimpleOnGestureListener() {

        override fun onDown(e: MotionEvent): Boolean {
            return true
        }

        override fun onFling(eve1: MotionEvent?, eve2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
            try {
                if(eve1 != null&& eve2!= null) {
                    val distanceX = eve2?.x - eve1?.x
                    val distanceY = eve2?.y - eve1?.y
                    if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (distanceX > 0)
                            onSwipeCallBack!!.onSwipeLeftCallback()
                        else
                            onSwipeCallBack!!.onSwipeRightCallback()
                        return true
                    }
                }
            }catch (exception:Exception){
                exception.printStackTrace()
            }

            return false
        }


    }
}

Linux: copy and create destination dir if it does not exist

Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }

Remove directory which is not empty

I wish there was a way to do this without additional modules for something so minuscule and common, but this is the best I could come up with.

Update: Should now work on Windows (tested Windows 10), and should also work on Linux/Unix/BSD/Mac systems.

const
    execSync = require("child_process").execSync,
    fs = require("fs"),
    os = require("os");

let removeDirCmd, theDir;

removeDirCmd = os.platform() === 'win32' ? "rmdir /s /q " : "rm -rf ";

theDir = __dirname + "/../web-ui/css/";

// WARNING: Do not specify a single file as the windows rmdir command will error.
if (fs.existsSync(theDir)) {
    console.log(' removing the ' + theDir + ' directory.');
    execSync(removeDirCmd + '"' + theDir + '"', function (err) {
        console.log(err);
    });
}

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

Your command is wrong.

Linux

java -- version

macOS

java -version

You can't use those commands other way around.

How to validate phone numbers using regex

As there is no language tag with this post, I'm gonna give a regex solution used within python.

The expression itself:

1[\s./-]?\(?[\d]+\)?[\s./-]?[\d]+[-/.]?[\d]+\s?[\d]+

When used within python:

import re

phonelist ="1-234-567-8901,1-234-567-8901 1234,1-234-567-8901 1234,1 (234) 567-8901,1.234.567.8901,1/234/567/8901,12345678901"

phonenumber = '\n'.join([phone for phone in re.findall(r'1[\s./-]?\(?[\d]+\)?[\s./-]?[\d]+[-/.]?[\d]+\s?[\d]+' ,phonelist)])
print(phonenumber)

Output:

1-234-567-8901
1-234-567-8901 1234
1-234-567-8901 1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

How can I undo a `git commit` locally and on a remote after `git push`

Generally, make an "inverse" commit, using:

git revert 364705c

then send it to the remote as usual:

git push

This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.

How to bring back "Browser mode" in IE11?

Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:

  • Internet Explorer 6
  • Internet Explorer 7
  • Internet Explorer 11 /!\ Unsupported Version (can't use it; big whoop, I have the browser)

Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.

Firefox used to be supported, but I don't see it now. Might be hiding.

I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.

I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.

Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.

Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

How do I change the owner of a SQL Server database?

Here is a way to change the owner on ALL DBS (excluding System)

EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
 exec sp_changedbowner ''sa''
END
'

Diff files present in two different directories

In practice the question often arises together with some constraints. In that case following solution template may come in handy.

cd dir1
find . \( -name '*.txt' -o -iname '*.md' \) | xargs -i diff -u '{}' 'dir2/{}'

what is the unsigned datatype?

According to C17 6.7.2 §2:

Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers

— void
— char
— signed char
— unsigned char
— short, signed short, short int, or signed short int
— unsigned short, or unsigned short int
— int, signed, or signed int
— unsigned, or unsigned int
— long, signed long, long int, or signed long int
— unsigned long, or unsigned long int
— long long, signed long long, long long int, or signed long long int
— unsigned long long, or unsigned long long int
— float
— double
— long double
— _Bool
— float _Complex
— double _Complex
— long double _Complex
— atomic type specifier
— struct or union specifier
— enum specifier
— typedef name

So in case of unsigned int we can either write unsigned or unsigned int, or if we are feeling crazy, int unsigned. The latter since the standard is stupid enough to allow "...may occur in any order, possibly intermixed". This is a known flaw of the language.

Proper C code uses unsigned int.

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

Comments in Markdown

You can do this (YAML block):

~~~
# This is a
# multiline
# comment
...

I tried with latex output only, please confirm for others.

Clear the entire history stack and start a new activity on Android

Try this:

Intent logout_intent = new Intent(DashboardActivity.this, LoginActivity.class);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(logout_intent);
finish();

JavaScript listener, "keypress" doesn't detect backspace?

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

JavaScript: function returning an object

You can simply do it like this with an object literal:

function makeGamePlayer(name,totalScore,gamesPlayed) {
    return {
        name: name,
        totalscore: totalScore,
        gamesPlayed: gamesPlayed
    };
}

Remove duplicates from a list of objects based on property in Java 8

If order does not matter and when it's more performant to run in parallel, Collect to a Map and then get values:

employee.stream().collect(Collectors.toConcurrentMap(Employee::getId, Function.identity(), (p, q) -> p)).values()

Solution to "subquery returns more than 1 row" error

Adding my answer, because it elaborates the idea that you can SELECT multiple columns from the table from which you subquery.

Here I needed the the most recently cast cote and it's associated information.

I first tried simply to SELECT the max(votedate) along with vote, itemid, userid etc., but while the query would return the max votedate, it would also return the a random row for the other information. Hard to see among a bunch of 1s and 0s.

This worked well:

$query = "  
    SELECT t1.itemid, t1.itemtext, t2.vote, t2.votedate, t2.userid 
    FROM
        (
        SELECT itemid, itemtext FROM oc_item ) t1
    LEFT JOIN 
        (
        SELECT vote, votedate, itemid,userid FROM oc_votes
        WHERE votedate IN 
        (select max(votedate) FROM oc_votes group by itemid)
        AND userid=:userid) t2
    ON (t1.itemid = t2.itemid)
    order by itemid ASC
";

The subquery in the WHERE clause WHERE votedate IN (select max(votedate) FROM oc_votes group by itemid) returns one record - the record with the max vote date.

How to extract a value from a string using regex and a shell?

It seems that you are asking multiple things. To answer them:

  • Yes, it is ok to extract data from a string using regular expressions, that's what they're there for
  • You get errors, which one and what shell tool do you use?
  • You can extract the numbers by catching them in capturing parentheses:

    .*(\d+) rofl.*
    

    and using $1 to get the string out (.* is for "the rest before and after on the same line)

With sed as example, the idea becomes this to replace all strings in a file with only the matching number:

sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName

or:

echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'

How to remove trailing whitespaces with sed?

For those who look for efficiency (many files to process, or huge files), using the + repetition operator instead of * makes the command more than twice faster.

With GNU sed:

sed -Ei 's/[ \t]+$//' "$1"
sed -i 's/[ \t]\+$//' "$1"   # The same without extended regex

I also quickly benchmarked something else: using [ \t] instead of [[:space:]] also significantly speeds up the process (GNU sed v4.4):

sed -Ei 's/[ \t]+$//' "$1"

real    0m0,335s
user    0m0,133s
sys 0m0,193s

sed -Ei 's/[[:space:]]+$//' "$1"

real    0m0,838s
user    0m0,630s
sys 0m0,207s

sed -Ei 's/[ \t]*$//' "$1"

real    0m0,882s
user    0m0,657s
sys 0m0,227s

sed -Ei 's/[[:space:]]*$//' "$1"

real    0m1,711s
user    0m1,423s
sys 0m0,283s

Convert Pandas DataFrame to JSON format

use this formula to convert a pandas DataFrame to a list of dictionaries :

import json
json_list = json.loads(json.dumps(list(DataFrame.T.to_dict().values())))

How to check if the user can go back in browser history or not

var fallbackUrl = "home.php";
if(history.back() === undefined)
    window.location.href = fallbackUrl;

How to output something in PowerShell

You can use any of these in your scenario since they write to the default streams (output and error). If you were piping output to another commandlet you would want to use Write-Output, which will eventually terminate in Write-Host.

This article describes the different output options: PowerShell O is for Output

Changing the cursor in WPF sometimes works, sometimes doesn't

One way we do this in our application is using IDisposable and then with using(){} blocks to ensure the cursor is reset when done.

public class OverrideCursor : IDisposable
{

  public OverrideCursor(Cursor changeToCursor)
  {
    Mouse.OverrideCursor = changeToCursor;
  }

  #region IDisposable Members

  public void Dispose()
  {
    Mouse.OverrideCursor = null;
  }

  #endregion
}

and then in your code:

using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
  // Do work...
}

The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.

Update

To prevent the cursor flickering you can do:

public class OverrideCursor : IDisposable
{
  static Stack<Cursor> s_Stack = new Stack<Cursor>();

  public OverrideCursor(Cursor changeToCursor)
  {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
      Mouse.OverrideCursor = changeToCursor;
  }

  public void Dispose()
  {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
      Mouse.OverrideCursor = cursor;
  }

}

Remove carriage return in Unix

cat input.csv | sed 's/\r/\n/g' > output.csv

worked for me

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

Why doesn't file_get_contents work?

If it is a local file, you have to wrap it in htmlspecialchars like so:

    $myfile = htmlspecialchars(file_get_contents($file_name));

Then it works

Finding the last index of an array

With C# 8:

int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

What is InputStream & Output Stream? Why and when do we use them?

From the Java Tutorial:

A stream is a sequence of data.

A program uses an input stream to read data from a source, one item at a time:

enter image description here

A program uses an output stream to write data to a destination, one item at time:

enter image description here

The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.

Sample code from oracle tutorial:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

This program uses byte streams to copy xanadu.txt file to outagain.txt , by writing one byte at a time

Have a look at this SE question to know more details about advanced Character streams, which are wrappers on top of Byte Streams :

byte stream and character stream

jQuery - Add active class and remove active from other element on click

$(document).ready(function() {
    $(".tab").click(function () {
        if(!$(this).hasClass('active'))
        {
            $(".tab.active").removeClass("active");
            $(this).addClass("active");        
        }
    });
});

Convert datetime to valid JavaScript date

You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:

   moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want 

   Output: 28-Apr-1993

Hope it will help you :)

Better way to right align text in HTML Table

Looking through your exact question to your implied problem:

Step 1: Use the class as you described (or, if you must, use inline styles).

Step 2: Turn on GZIP compression.

Works wonders ;)

This way GZIP removes the redundancy for you (over the wire, anyways) and your source remains standards compliant.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

Creating a selector from a method name with parameters

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);

-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here

-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

Loop inside React JSX

Maybe the standard of today maximum developer, use a structure like this:

 let data = [
  {
    id: 1,
    name: "name1"
  },
  {
    id: 2,
    name: "name2"
  },
  {
    id: 3,
    name: "name3"
  },
  {
    id: 100,
    name: "another name"
  }
];

export const Row = data => {
  return (
    <tr key={data.id}>
      <td>{data.id}</td>
      <td>{data.name}</td>
    </tr>
  );
};

function App() {
  return (
    <table>
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>{data.map(item => Row(item))}</tbody>
    </table>
  );
}

In the JSX, write your JavaScript action inside HTML or any code here, {data.map(item => Row(item))}, use single curly braces and inside a map function. Get to know more about map.

And also see the following output here.

jQuery Screen Resolution Height Adjustment

var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});

What is a correct MIME type for .docx, .pptx, etc.?

To load a .docx file:

    if let htmlFile = Bundle.main.path(forResource: "fileName", ofType: "docx") {
        let url = URL(fileURLWithPath: htmlFile)
        do{
            let data = try Data(contentsOf: url)
            self.webView.load(data, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", textEncodingName: "UTF-8", baseURL: url)
        }catch{
            print("errrr")
        }
    }

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How can I declare and define multiple variables in one line using C++?

int column(0), row(0), index(0);

Note that this form will work with custom types too, especially when their constructors take more than one argument.

Converting Float to Dollars and Cents

you said that:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

Python 3.1.1 string to hex

In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

Optionally convert the string back to bytes:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'

What is .htaccess file?

It's not part of PHP; it's part of Apache.

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

.htaccess files provide a way to make configuration changes on a per-directory basis.

Essentially, it allows you to take directives that would normally be put in Apache's main configuration files, and put them in a directory-specific configuration file instead. They're mostly used in cases where you don't have access to the main configuration files (e.g. a shared host).

Maven : error in opening zip file when running maven

I just have this error. You can delete the files and run the compiling command again:

$ sudo rm /Users/Chaklader/.m2/repository/org/apache/poi/poi/3.17/poi-3.17.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.7.5/jackson-databind-2.7.5.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.7.5/jackson-core-2.7.5.jar

Now, run the command for the clean compile:

$ mvn -U clean compile

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

android lollipop toolbar: how to hide/show the toolbar while scrolling?

There is an Android library called Android Design Support Library that's a handy library where you can find of all of those Material fancy design things that the Material documentation presents without telling you how to do them.

It's well presented in this Android Blog post. The "Collapsing Toolbar" in particular is what you're looking for.

Android EditText for password with android:hint

If you set

android:inputType="textPassword"

this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use

android:password="true"

property which allows you to enter any type of password without any restriction.

If you want to provide hint use

android:hint="hint text goes here"

example:

android:hint="password"

CSS Cell Margin

You can't single out individual columns in a cell in that manner. In my opinion, your best option is to add a style='padding-left:10px' on the second column and apply the styles on an internal div or element. This way you can achieve the illusion of a greater space.

Java string split with "." (dot)

The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0];

I hope this helps

How to convert a std::string to const char* or char*?

Just see this:

string str1("stackoverflow");
const char * str2 = str1.c_str();

However, note that this will return a const char *.

For a char *, use strcpy to copy it into another char array.

Shortcut to create properties in Visual Studio?

After typing "prop" + Tab + Tab as suggested by Amra, you can immediately type the property's type (which will replace the default int), type another tab and type the property name (which will replace the default MyProperty). Finish by pressing Enter.

GLYPHICONS - bootstrap icon font hex value

Do you mean these hex values?

.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...

You can find these in glyphicons.css here:

http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css

(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Vue.js toggle class on click

If you don't need to access the toggle from outside the element, this code works without a data variable:

<a @click="e => e.target.classList.toggle('active')"></a>

List of all special characters that need to be escaped in a regex

According to the String Literals / Metacharacters documentation page, they are:

<([{\^-=$!|]})?*+.>

Also it would be cool to have that list refereed somewhere in code, but I don't know where that could be...

set option "selected" attribute from dynamic created option

// Get <select> object
var sel = $('country');

// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }

// Select index 
sel.options.selectedIndex = i;

Begitu loh.

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

How to select a schema in postgres when using psql?

key word :

SET search_path TO

example :

SET search_path TO your_schema_name;

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

Neatest way to remove linebreaks in Perl

Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one.

sub clean {

    my $text = shift;

    $text =~ s/\n//g;
    $text =~ s/\r//g;

    return $text;
}

It may not be fancy but this method has been working flawless for me for years.

Get device token for push notification

Get device token in Swift 3

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    print("Device token: \(deviceTokenString)")

}

How to change the color of progressbar in C# .NET 3.5?

I just put this into a static class.

  const int WM_USER = 0x400;
  const int PBM_SETSTATE = WM_USER + 16;
  const int PBM_GETSTATE = WM_USER + 17;

  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
  static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

  public enum ProgressBarStateEnum : int
  {
   Normal = 1,
   Error = 2,
   Paused = 3,
  }

  public static ProgressBarStateEnum GetState(this ProgressBar pBar)
  {
   return (ProgressBarStateEnum)(int)SendMessage(pBar.Handle, PBM_GETSTATE, IntPtr.Zero, IntPtr.Zero);
  }

  public static void SetState(this ProgressBar pBar, ProgressBarStateEnum state)
  {
   SendMessage(pBar.Handle, PBM_SETSTATE, (IntPtr)state, IntPtr.Zero);
  } 

Hope it helps,

Marc

Java Package Does Not Exist Error

You need to have org/name dirs at /usr/share/stuff and place your org.name package sources at this dir.

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

New features in java 7

Java SE 7 Features and Enhancements from JDK 7 Release Notes

This is the Java 7 new features summary from the OpenJDK 7 features page:

vm  JSR 292: Support for dynamically-typed languages (InvokeDynamic)
        Strict class-file checking
lang    JSR 334: Small language enhancements (Project Coin)
core    Upgrade class-loader architecture
        Method to close a URLClassLoader
        Concurrency and collections updates (jsr166y)
i18n    Unicode 6.0
        Locale enhancement
        Separate user locale and user-interface locale
ionet   JSR 203: More new I/O APIs for the Java platform (NIO.2)
        NIO.2 filesystem provider for zip/jar archives
        SCTP (Stream Control Transmission Protocol)
        SDP (Sockets Direct Protocol)
        Use the Windows Vista IPv6 stack
        TLS 1.2
sec     Elliptic-curve cryptography (ECC)
jdbc    JDBC 4.1
client  XRender pipeline for Java 2D
        Create new platform APIs for 6u10 graphics features
        Nimbus look-and-feel for Swing
        Swing JLayer component
        Gervill sound synthesizer [NEW]
web     Update the XML stack
mgmt    Enhanced MBeans [UPDATED]

Code examples for new features in Java 1.7

Try-with-resources statement

this:

BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {
   br.close();
}

becomes:

try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();
}

You can declare more than one resource to close:

try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
{
 // code
}

Underscores in numeric literals

int one_million = 1_000_000;

Strings in switch

String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

Binary literals

int binary = 0b1001_1001;

Improved Type Inference for Generic Instance Creation

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

becomes:

Map<String, List<String>> anagrams = new HashMap<>();

Multiple exception catching

this:

} catch (FirstException ex) {
     logger.error(ex);
     throw ex;
} catch (SecondException ex) {
     logger.error(ex);
     throw ex;
}

becomes:

} catch (FirstException | SecondException ex) {
     logger.error(ex);
    throw ex;
}

SafeVarargs

this:

@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List<String>... lists){
    for(List<String> list : lists){
        System.out.println(list);
    }
}

becomes:

@SafeVarargs
public static void printAll(List<String>... lists){
    for(List<String> list : lists){
        System.out.println(list);
    }
}

How to pull remote branch from somebody else's repo

The following is a nice expedient solution that works with GitHub for checking out the PR branch from another user's fork. You need to know the pull request ID (which GitHub displays along with the PR title).

Example:

Fixing your insecure code #8
alice wants to merge 1 commit into your_repo:master from her_repo:branch

git checkout -b <branch>
git pull origin pull/8/head

Substitute your remote if different from origin.
Substitute 8 with the correct pull request ID.

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

How to parse JSON data with jQuery / JavaScript?

Use that code.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

How to sum a variable by group

using cast instead of recast (note 'Frequency' is now 'value')

df  <- data.frame(Category = c("First","First","First","Second","Third","Third","Second")
                  , value = c(10,15,5,2,14,20,3))

install.packages("reshape")

result<-cast(df, Category ~ . ,fun.aggregate=sum)

to get:

Category (all)
First     30
Second    5
Third     34

Iterating over a 2 dimensional python list

same way you did the fill in, but reverse the indexes:

>>> for j in range(columns):
...     for i in range(rows):
...        print mylist[i][j],
... 
0,0 1,0 2,0 0,1 1,1 2,1
>>> 

How to run a python script from IDLE interactive shell?

In a python console, one can try the following 2 ways.

under the same work directory,

1. >> import helloworld

# if you have a variable x, you can print it in the IDLE.

>> helloworld.x

# if you have a function func, you can also call it like this.

>> helloworld.func()

2. >> runfile("./helloworld.py")

How to render a DateTime in a specific format in ASP.NET MVC 3?

You could decorate your view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
               ApplyFormatInEditMode = true)]
public DateTime MyDateTime { get; set; }

and in your view:

@Html.EditorFor(x => x.MyDate)

or, for displaying the value,

@Html.DisplayFor(x => x.MyDate)

Another possibility, which I don't recommend, is to use a weakly typed helper:

@Html.TextBox("MyDate", Model.MyDate.ToLongDateString())

What is the difference between a static method and a non-static method?

- First we must know that the diff bet static and non static methods 
is differ from static and non static variables : 

- this code explain static method - non static method and what is the diff 

    public class MyClass {
        static {
            System.out.println("this is static routine ... ");

        }
          public static void foo(){
            System.out.println("this is static method ");
        }

        public void blabla(){

         System.out.println("this is non static method ");
        }

        public static void main(String[] args) {

           /* ***************************************************************************  
            * 1- in static method you can implement the method inside its class like :  *       
            * you don't have to make an object of this class to implement this method   *      
            * MyClass.foo();          // this is correct                                *     
            * MyClass.blabla();       // this is not correct because any non static     *
            * method you must make an object from the class to access it like this :    *            
            * MyClass m = new MyClass();                                                *     
            * m.blabla();                                                               *    
            * ***************************************************************************/

            // access static method without make an object 
            MyClass.foo();

            MyClass m = new MyClass();
            // access non static method via make object 
            m.blabla();
            /* 
              access static method make a warning but the code run ok 
               because you don't have to make an object from MyClass 
               you can easily call it MyClass.foo(); 
            */
            m.foo();
        }    
    }
    /* output of the code */
    /*
    this is static routine ... 
    this is static method 
    this is non static method 
    this is static method
    */

 - this code explain static method - non static Variables and what is the diff 


     public class Myclass2 {

                // you can declare static variable here : 
                // or you can write  int callCount = 0; 
                // make the same thing 
                //static int callCount = 0; = int callCount = 0;
                static int callCount = 0;    

                public void method() {
                    /********************************************************************* 
                    Can i declare a static variable inside static member function in Java?
                    - no you can't 
                    static int callCount = 0;  // error                                                   
                    ***********************************************************************/
                /* static variable */
                callCount++;
                System.out.println("Calls in method (1) : " + callCount);
                }

                public void method2() {
                int callCount2 = 0 ; 
                /* non static variable */   
                callCount2++;
                System.out.println("Calls in method (2) : " + callCount2);
                }


            public static void main(String[] args) {
             Myclass2 m = new Myclass2();
             /* method (1) calls */
             m.method(); 
             m.method();
             m.method();
             /* method (2) calls */
             m.method2();
             m.method2();
             m.method2();
            }

        }
        // output 

        // Calls in method (1) : 1
        // Calls in method (1) : 2
        // Calls in method (1) : 3
        // Calls in method (2) : 1
        // Calls in method (2) : 1
        // Calls in method (2) : 1 

Python function pointer

modname, funcname = myvar.rsplit('.', 1)
getattr(sys.modules[modname], funcname)(parameter1, parameter2)

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

How to resolve git's "not something we can merge" error

We got this error because we had a comma (,) in the branch name. We deleted the local branch, then re-checked it under a new name without the comma. We were able to merge it successfully.

Going through a text file line by line in C

To read a line from a file, you should use the fgets function: It reads a string from the specified file up to either a newline character or EOF.

The use of sscanf in your code would not work at all, as you use filename as your format string for reading from line into a constant string literal %s.

The reason for SEGV is that you write into the non-allocated memory pointed to by line.

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

Test if a command outputs an empty string

Here's a solution for more extreme cases:

if [ `command | head -c1 | wc -c` -gt 0 ]; then ...; fi

This will work

  • for all Bourne shells;
  • if the command output is all zeroes;
  • efficiently regardless of output size;

however,

  • the command or its subprocesses will be killed once anything is output.

Closing Excel Application Process in C# after Data Access

Think of this, it kills the process:

System.Diagnostics.Process[] process=System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
    if (!string.IsNullOrEmpty(p.ProcessName))
    {
        try
        {
            p.Kill();
        }
        catch { }
    }
}

Also, did you try just close it normally?

myWorkbook.SaveAs(@"C:/pape.xltx", missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excelBook.Close(null, null, null);                 // close your workbook
excelApp.Quit();                                   // exit excel application
excel = null;                                      // set to NULL

What is the proper way to comment functions in Python?

The correct way to do it is to provide a docstring. That way, help(add) will also spit out your comment.

def add(self):
    """Create a new user.
    Line 2 of comment...
    And so on... 
    """

That's three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn't need to be multiline and double quotes can be replaced by single quotes.

See: PEP 257

CSS width of a <span> tag

You could explicitly set the display property to "block" so it behaves like a block level element, but in that case you should probably just use a div instead.

<span style="display:block; background-color:red; width:100px;"></span>

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

Forward declaring an enum in C++

You can wrap the enum in a struct, adding in some constructors and type conversions, and forward declare the struct instead.

#define ENUM_CLASS(NAME, TYPE, VALUES...) \
struct NAME { \
    enum e { VALUES }; \
    explicit NAME(TYPE v) : val(v) {} \
    NAME(e v) : val(v) {} \
    operator e() const { return e(val); } \
    private:\
        TYPE val; \
}

This appears to work: http://ideone.com/TYtP2

Tomcat 8 Maven Plugin for Java 8

An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:

<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.1.1</version>
</plugin>

Version 7.1.1 wraps a Tomcat 8.5.41

Can I use complex HTML with Twitter Bootstrap's Tooltip?

This parameter is just about whether you are going to use complex html into the tooltip. Set it to true and then hit the html into the title attribute of the tag.

See this fiddle here - I've set the html attribute to true through the data-html="true" in the <a> tag and then just added in the html ad hoc as an example.

How to convert a Title to a URL slug in jQuery?

function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

*based on https://gist.github.com/mathewbyrne/1280286

now you can transform this string:

Barack_Obama       ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`

into:

barack_obama-?????_?????

applying to your code:

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = slugify(Text);
    $("#Restaurant_Slug").val(Text);
});

Check if a process is running or not on Windows with Python

According to the ewerybody post: https://stackoverflow.com/a/29275361/7530957

Multiple problems can arise:

  • Multiple processes with the same name
  • Name of the long process

The 'ewerybody's' code will not work if the process name is long. So there is a problem with this line:

last_line.lower().startswith(process_name.lower())

Because last_line will be shorter than the process name.

So if you just want to know if a process/processes is/are active:

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    if check_output(call).splitlines()[3:]:
        return True

Instead for all the information of a process/processes

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    processes = []
    for process in check_output(call).splitlines()[3:]:
        process = process.decode()
        processes.append(process.split())
    return processes

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

Initialise numpy array of unknown length

a = np.empty(0)
for x in y:
    a = np.append(a, x)

Converting String to Double in Android

i have a similar problem. for correct formatting EditText text content to double value i use this code:

try {
        String eAm = etAmount.getText().toString();
        DecimalFormat dF = new DecimalFormat("0.00");
        Number num = dF.parse(eAm);
        mPayContext.amount = num.doubleValue();
    } catch (Exception e) {
        mPayContext.amount = 0.0d;
    }

this is independet from current phone locale and return correct double value.

hope it's help;

Is there a way to create multiline comments in Python?

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 - Comment/uncomment
  • Ctrl + 4 - Comment a block of code
  • Ctrl + 5 - Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

What's the actual use of 'fail' in JUnit test case?

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

How to check if JavaScript object is JSON

The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof

function isJson(obj) {
    var t = typeof obj;
    return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}

How do I set up Visual Studio Code to compile C++ code?

The basic problem here is that building and linking a C++ program depends heavily on the build system in use. You will need to support the following distinct tasks, using some combination of plugins and custom code:

  1. General C++ language support for the editor. This is usually done using ms-vscode.cpptools, which most people expect to also handle a lot of other stuff, like build support. Let me save you some time: it doesn't. However, you will probably want it anyway.

  2. Build, clean, and rebuild tasks. This is where your choice of build system becomes a huge deal. You will find plugins for things like CMake and Autoconf (god help you), but if you're using something like Meson and Ninja, you are going to have to write some helper scripts, and configure a custom "tasks.json" file to handle these. Microsoft has totally changed everything about that file over the last few versions, right down to what it is supposed to be called and the places (yes, placeS) it can go, to say nothing of completely changing the format. Worse, they've SORT OF kept backward compatibility, to be sure to use the "version" key to specify which variant you want. See details here:

https://code.visualstudio.com/docs/editor/tasks

...but note conflicts with:

https://code.visualstudio.com/docs/languages/cpp

WARNING: IN ALL OF THE ANSWERS BELOW, ANYTHING THAT BEGINS WITH A "VERSION" TAG BELOW 2.0.0 IS OBSOLETE.

Here's the closest thing I've got at the moment. Note that I kick most of the heavy lifting off to scripts, this doesn't really give me any menu entries I can live with, and there isn't any good way to select between debug and release without just making another three explicit entries in here. With all that said, here is what I can tolerate as my .vscode/tasks.json file at the moment:

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
    {
        "label": "build project",
        "type": "shell",
        "command": "buildscripts/build-debug.sh",
        "args": [],

        "group": {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            // Reveal the output only if unrecognized errors occur.
            "echo": true,
            "focus": false,
            "reveal": "always",
            "panel": "shared"
        },

        // Use the standard MS compiler pattern to detect errors, warnings and infos
        "options": {
            "cwd": "${workspaceRoot}"
        },
        "problemMatcher": {
            "owner": "cpp",
            "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
            "pattern": {
                "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                "file": 1,
                "line": 2,
                "column": 3,
                "severity": 4,
                "message": 5
            }
        }
    },
    {
        "label": "rebuild project",
        "type": "shell",
        "command": "buildscripts/rebuild-debug.sh",
        "args": [],
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            // Reveal the output only if unrecognized errors occur.
            "echo": true,
            "focus": false,
            "reveal": "always",
            "panel": "shared"
        },

        // Use the standard MS compiler pattern to detect errors, warnings and infos
        "options": {
            "cwd": "${workspaceRoot}"
        },
        "problemMatcher": {
            "owner": "cpp",
            "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
            "pattern": {
                "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                "file": 1,
                "line": 2,
                "column": 3,
                "severity": 4,
                "message": 5
            }
        }
    },
    {
        "label": "clean project",
        "type": "shell",
        "command": "buildscripts/clean-debug.sh",
        "args": [],

        "group": {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            // Reveal the output only if unrecognized errors occur.
            "echo": true,
            "focus": false,
            "reveal": "always",
            "panel": "shared"
        },

        // Use the standard MS compiler pattern to detect errors, warnings and infos
        "options": {
            "cwd": "${workspaceRoot}"
        },
        "problemMatcher": {
            "owner": "cpp",
            "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
            "pattern": {
                "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                "file": 1,
                "line": 2,
                "column": 3,
                "severity": 4,
                "message": 5
            }
        }
    }
]

}

Note that, in theory, this file is supposed to work if you put it in the workspace root, so that you aren't stuck checking files in hidden directories (.vscode) into your revision control system. I have yet to see that actually work; test it, but if it fails, put it in .vscode. Either way, the IDE will bitch if it isn't there anyway. (Yes, at the moment, this means I have been forced to check .vscode into subversion, which I'm not happy about.) Note that my build scripts (not shown) simply create (or recreate) a DEBUG directory using, in my case, meson, and build inside it (using, in my case, ninja).

  1. Run, debug, attach, halt. These are another set of tasks, defined in "launch.json". Or at least they used to be. Microsoft has made such a hash of the documentation, I'm not even sure anymore.

MySQL query to select events between start/end date

select * from tbl where (endDate>=@starDate and startDate<=@endDate)

attached the diagram for explanationenter image description here

storing simple data in DB StartDate =10/01/2020 and endDate=20/01/2020. user can provide @startDate(d1) and @endDate(d2) to search.

here 6 scenarios can happen depicted by the 4 red lines (match data) 2 green lines (no match data).

so by conclusion from the image, to get data from DB by providing d1,d2. ED must be greater than d1(@startDate) and SD must be less than d2(@endDate).

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

Redirecting to authentication dialog - "An error occurred. Please try again later"

If you're the app developer, you may see a more specific error message, but generally that message means one of two things:

  1. Your server returned a HTTP error code (usually 5xx)
  2. You tried to send the user, after login, to a URL not allowed by your app configuration (though as an Admin of the app, you should see a more specific error message and Facebook error code in this case)

Getting the text that follows after the regex match

You can do this with "just the regular expression" as you asked for in a comment:

(?<=sentence).*

(?<=sentence) is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence without making that text itself part of the match. Consequently, (?<=sentence).* will match any text after sentence.

This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4}) is legal, but (?<=sentence\s*) isn't.

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

How to get the selected item of a combo box to a string variable in c#

SelectedText = this.combobox.SelectionBoxItem.ToString();

How to use UIScrollView in Storyboard

Here's how to setup a scrollview using Xcode 11

1 - Add scrollview and set top,bottom,leading and trailing constraints

enter image description here

2 - Add a Content View to the scrollview, drag a connection to the Content Layout Guide and select Leading, Top, Bottom and Trailing. Make sure to set its' values to 0 or the constants you want.

enter image description here

3 - Drag from the Content View to the Frame Layout Guide and select Equal Widths

enter image description here

4 - Set a height constraint constant to the Content View

Update Item to Revision vs Revert to Revision

Update to revision will only update files of your workingcopy to your choosen revision. But you cannot continue to work on this revision, as SVN will complain that your workingcopy is out of date.

revert to this revision will undo all changes in your working copy which were made after the selected revision (in your example rev. 96,97,98,99,100) Your working copy is now in modified state.

The file content of both scenarions is same, however in first case you have an unmodified working copy and you cannot commit your changes(as your workingcopy is not pointing to HEAD rev 100) in second case you have a modified working copy pointing to head and you can continue to work and commit

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

how to use javascript Object.defineProperty

Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...

How can I add private key to the distribution certificate?

Yes, the error you are getting means that there is not a private key on your Mac associated with the distribution certificate you are trying to use to sign the app.

There are two possible solutions, depending on whether the computer who requested the distribution certificate is available or not.

If the computer who requested the distribution certificate is available (or there is a backup of the distribution assets somewhere)

  1. From the computer where the distribution asset was generated, open Xcode.
  2. Click on Window, Organizer.
  3. Expand the Teams section.
  4. Select your team, select the certificate of "iOS Distribution" type, click Export and follow the instructions.
  5. Save the exported file and go to your computer.
  6. Repeat steps 1-3.
  7. Click Import and select the file you exported before.

If the computer where the distribution profile was created is not accessible anymore (and there is not a backup)

You have to revoke the certificate and create a new one.

You may need to ask your team admin or agent to give you some privileges in order to generate distribution certificates. Once you have enough privileges, follow these steps (accurate as of 15-May-2013):

  1. Go to this webpage: https://developer.apple.com/devcenter/ios/index.action
  2. Click on "Member Center" and enter your iOS developer credentials.
  3. Click on "Certificates, Identifiers & Profiles".
  4. Click on "Certificates" under the "iOS Apps" section.
  5. Expand the Certificates section on the left, select Distribution, and click on your distribution certificate.
  6. Click Revoke and follow the instructions.
  7. Click on the plus sign to add a new certificate.
  8. Select "App Store and Ad Hoc" option, and click Continue.
  9. Follow the steps printed in the webpage. That involves opening the Keychain application on your Mac and generate a Certificate Signing Request from there. Click Continue.
  10. Upload the .csr file and click Continue.
  11. A certificate is generated for distribution. Download it and double click it to integrate it in your keychain.

Reopen Xcode and check your project configuration to see if you can now select an "iPhone Distribution" certificate (i.e. it's not grayed out).

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I would do something like the following:

INSERT INTO cache VALUES (key, generation)
ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.

Multiple radio button groups in one form

in input field make name same like

<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >

How do I generate random number for each row in a TSQL Select?

The Rand() function will generate the same random number, if used in a table SELECT query. Same applies if you use a seed to the Rand function. An alternative way to do it, is using this:

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [RandomNumber]

Got the information from here, which explains the problem very well.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I know the question is already answered but still I'm posting with thought that may someone run into this kind of problem.

In my case problem is i'm loading my application to phone which refer layouts from res/layout/ folder and values for @dimens from res/values/dimens here it's font_22 which it's trying to access and it's define in res/values-xlarge/dimens.

I'm actually updating UI of existing project.

I ran into this problem because I'm using IDE Eclipse where I ctrl+space for hint while writing xml for layout folder it displays all values from values as well as values-xlarge folder regardless of for which folder I'm writing.

I also know that the values in both files should be same to mapped for different screens.

Hope this may help someone run into this kind of silly problem.

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

date format yyyy-MM-ddTHH:mm:ssZ

One option could be converting DateTime to ToUniversalTime() before converting to string using "o" format. For example,

var dt = DateTime.Now.ToUniversalTime();
Console.WriteLine(dt.ToString("o"));

It will output:

2016-01-31T20:16:01.9092348Z

jQuery append and remove dynamic table row

Change ID to class :

$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');

$(".remCF").on('click',function(){
            $(this).parent().parent().remove();
        });

http://jsfiddle.net/7BHDm/1/

Submit button not working in Bootstrap form

  • If you put type=submit it is a Submit Button
  • if you put type=button it is just a button, It does not submit your form inputs.

and also you don't want to use both of these

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

How to edit the size of the submit button on a form?

just use style attribute with height and width option

<input type="submit" id="search" value="Search"  style="height:50px; width:50px" />

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces