Programs & Examples On #P4python

p4python is a Python interface to Perforce.

jQuery .val change doesn't change input value

to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426

http://api.jquery.com/val/#val2

about val()

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

How to delete large data of table in SQL without log?

You can also use GO + how many times you want to execute the same query.

DELETE TOP (10000)  [TARGETDATABASE].[SCHEMA].[TARGETTABLE] 
WHERE readTime < dateadd(MONTH,-1,GETDATE());
-- how many times you want the query to repeat
GO 100

How to move div vertically down using CSS

I don't see any mention of flexbox in here, so I will illustrate:

HTML

 <div class="wrapper">
   <div class="main">top</div>
   <div class="footer">bottom</div>
 </div>

CSS

 .wrapper {
   display: flex;
   flex-direction: column;
   min-height: 100vh;
  }
 .main {
   flex: 1;
 }
 .footer {
  flex: 0;
 }

Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

use maven dependency

<dependency> 
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId> 
  <version>1.3.2</version> 
</dependency> 

or download commons-io.1.3.2.jar to your lib folder

How to Get a Sublist in C#

Would it be as easy as running a LINQ query on your List?

List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();

Simple java program of pyramid

You can try in this way.

   for(int a=5;a>0;a--){
        int b=0;
       for(b=0;b<a;b++){
           System.out.print(" ");
       }
        for (int j=b;j<5;j++){
            System.out.print(" $ ");
        }
        System.out.println("");

    }

Out put

      $ 
     $  $ 
    $  $  $ 
   $  $  $  $ 

How to solve the memory error in Python

Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError.

Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).

If that's not enough, consider converting to a sqlite3 database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.

jQuery: print_r() display equivalent?

You can also do

console.log("a = %o, b = %o", a, b);

where a and b are objects.

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

Format specifier %02x

You are actually getting the correct value out.

The way your x86 (compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.

So, given your output:

10101010

the last two hex values 10 are the Most Significant Byte (2 hex digits = 1 byte = 8 bits (for (possibly unnecessary) clarification).

So, by reversing the memory storage order of the bytes, your value is actually: 01010101.

Hope that clears it up!

How to get the mobile number of current sim card in real device?

Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

Can I set up HTML/Email Templates with ASP.NET?

Here is a simple way using the WebClient class:

public static string GetHTMLBody(string url)
{
    string htmlBody;

    using (WebClient client = new WebClient ())
    {
        htmlBody = client.DownloadString(url);
    }

    return htmlBody;
}

Then just call it like this:

string url = "http://www.yourwebsite.com";
message.Body = GetHTMLBody(url);

Of course, your CSS will need to be in-lined in order to show the styles of the webpage in the most email clients (such as Outlook). If your e-mail displays dynamic content (ex. Customer Name), then I would recommend using QueryStrings on your website to populate the data. (ex. http://www.yourwebsite.com?CustomerName=Bob)

Find by key deep in a nested array

If you're already using Underscore, use _.find()

_.find(yourList, function (item) {
    return item.id === 1;
});

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

The best way what I found is by using the table.

Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any colour.

enter image description here

Call of overloaded function is ambiguous

Use

p.setval(static_cast<const char *>(0));

or

p.setval(static_cast<unsigned int>(0));

As indicated by the error, the type of 0 is int. This can just as easily be cast to an unsigned int or a const char *. By making the cast manually, you are telling the compiler which overload you want.

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

I installed 32-bit JVM and retried it again, looks like the following does tell you JVM bitness, not OS arch:

System.getProperty("os.arch");
#
# on a 64-bit Linux box:
# "x86" when using 32-bit JVM
# "amd64" when using 64-bit JVM

This was tested against both SUN and IBM JVM (32 and 64-bit). Clearly, the system property is not just the operating system arch.

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

Ternary operator in PowerShell

$result = If ($condition) {"true"} Else {"false"}

Everything else is incidental complexity and thus to be avoided.

For use in or as an expression, not just an assignment, wrap it in $(), thus:

write-host  $(If ($condition) {"true"} Else {"false"}) 

How do I create and read a value from cookie?

Here are functions you can use for creating and retrieving cookies.

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

ARM compilation error, VFP registers used by executable, not object file

I encountered the issue using Atollic for ARM on STM32F4 (I guess it applies to all STM32 with FPU).

Using SW floating point didn't worked well for me (thus compiling correctly).

When STM32cubeMX generates code for TrueStudio (Atollic), it doesn't set an FPU unit in C/C++ build settings (not sure about generated code for other IDEs).

Set a FPU in "Target" for (under project Properties build settings):

  • Assembler
  • C Compiler
  • C Linker

Then you have the choice to Mix HW/SW fp or use HW.

Generated command lines are added with this for the intended target:

-mfloat-abi=hard -mfpu=fpv4-sp-d16

Spring @Value is not resolving to value from property file

for Sprig-boot User both PropertyPlaceholderConfigurer and the new PropertySourcesPlaceholderConfigurer added in Spring 3.1. so it's straightforward to access properties file. just inject

Note: Make sure your property must not be Static

@Value("${key.value1}")
private String value;

SQL "select where not in subquery" returns no results

Please follow the below example to understand the above topic:

Also you can visit the following link to know Anti join

select department_name,department_id from hr.departments dep
where not exists 
    (select 1 from hr.employees emp
    where emp.department_id=dep.department_id
    )
order by dep.department_name;
DEPARTMENT_NAME DEPARTMENT_ID
Benefits    160
Construction    180
Contracting 190
.......

But if we use NOT IN in that case we do not get any data.

select Department_name,department_id from hr.departments dep 
where department_id not in (select department_id from hr.employees );

no data found

This is happening as (select department_id from hr.employees) is returning a null value and the entire query is evaluated as false. We can see it if we change the SQL slightly like below and handle null values with NVL function.

select Department_name,department_id from hr.departments dep 
where department_id not in (select NVL(department_id,0) from hr.employees )

Now we are getting data:

DEPARTMENT_NAME DEPARTMENT_ID
Treasury    120
Corporate Tax   130
Control And Credit  140
Shareholder Services    150
Benefits    160
....

Again we are getting data as we have handled the null value with NVL function.

How to clear File Input

I have done something like this and it's working for me

$('#fileInput').val(null); 

You must enable the openssl extension to download files via https

PHP CLI SAPI is using different php.ini than CGI or Apache module.

Find line ;extension=php_openssl.dll in wamp/bin/php/php#.#.##/php.ini and uncomment it by removing the semicolon (;) from the beginning of the line.

How to show PIL images on the screen?

Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:

http://matplotlib.org/users/image_tutorial.html

How can I get a JavaScript stack trace when I throw an exception?

This polyfill code working in modern (2017) browsers (IE11, Opera, Chrome, FireFox, Yandex):

printStackTrace: function () {
    var err = new Error();
    var stack = err.stack || /*old opera*/ err.stacktrace || ( /*IE11*/ console.trace ? console.trace() : "no stack info");
    return stack;
}

Other answers:

function stackTrace() {
  var err = new Error();
  return err.stack;
}

not working in IE 11 !

Using arguments.callee.caller - not working in strict mode in any browser!

YouTube iframe embed - full screen

I managed to find a relatively clean straightforward way to do this. To see it working click on my webpage: http://developersfound.com/yde-portfolio.html and hover over the 'Youtube Demos' link.

Below are two snippets to show how this can be done quite easily:

I achieved this with an iFrame. Assuming this DOM is 'yde-home.html' Which is the source of your iFrame.

<!DOCTYPE html>
<html>
<head>
    <title>iFrame Container</title>
    <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
    <style type="text/css">.OBJ-1 { border:none; }</style>
    <script>
        $(document).ready(function() {
            $('#myHiddenButton').trigger('click');
        });
    </script>
</head>

<body>

    <section style="visibility: hidden;">
        <button id="myHiddenButton" onclick="$(location).attr('href', '"http://www.youtube.com/embed/wtwOZMXCe-c?version=3&amp;start=0&amp;rel=0&amp;fs=1&amp;wmode=transparent;");">View Full Screen</button>
    </section>

    <section class="main-area-inner" style="background:transparent;margin-left:auto;margin-right:auto;position:relative;width:1080px;height:720px;">
        <iframe src="http://www.youtube.com/embed/wtwOZMXCe-c?version=3&amp;start=0&amp;rel=0&amp;fs=1&amp;wmode=transparent;"
        class="OBJ-1" style="position:absolute;left:79px;top:145px;width:1080px;height:720px;">
        </iframe>
    </section>

</body>

</html>

Assume this is the DOM that loads the iFrame.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Full Screen Youtube</title>
    <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
    <script>
        $(document).ready(function() {});           
    </script>
</head>

<body>

    <iframe name="iframe-container" id="iframe-container" src="yde-home.html" style="width: 100%; height: 100%;">
        <p>Your browser does not support iFrames</p>
    </iframe>

</body>

</html>

I've also checked this against the W3c Validator and it validates a HTML5 with no errors.

It is also important to note that: Youtube embed URLs sometimes check to see if the request is coming from a server so it may be necessary to set up your test environment to listen on your external IP. So you may need to set up port forwarding on your router for this solution to work. Once you've set up port forwarding just test from the external IP instead of LocalHost. Remember that some routers need port forwarding from LocalHost/loopback but most use the same IP that you used to log into the router. For example if your router login page is 192.168.0.1, then the port forward would have to use 192.168.0.? where ? could be any unused number (you may need to experiment). From this address you would add the ports that your test environment listen from (normally 80, 81, 8080 or 8088).

Set up DNS based URL forwarding in Amazon Route53

The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.

AWS S3:

  1. Create a Bucket named with your full domain, like aws.example.com
  2. On the bucket properties, select Redirect all requests to another host name and enter your URL: https://myaccount.signin.aws.amazon.com/console/

AWS Route53:

  1. Create a record set type A. Change Alias to Yes. Click on Alias Target field and select the S3 bucket you created in the previous step.

Reference: How to redirect domains using Amazon Web Services

AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?

Sending arrays with Intent.putExtra

You are setting the extra with an array. You are then trying to get a single int.

Your code should be:

int[] arrayB = extras.getIntArray("numbers");

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

Another late answer... Here's how Microsoft uses it in their wchar.h. Notice they also disable Warning C6386:

__inline _CRT_INSECURE_DEPRECATE_MEMORY(wmemcpy_s) wchar_t * __CRTDECL
wmemcpy(_Out_opt_cap_(_N) wchar_t *_S1, _In_opt_count_(_N) const wchar_t *_S2, _In_ size_t _N)
{
    #pragma warning( push )
    #pragma warning( disable : 4996 6386 )
        return (wchar_t *)memcpy(_S1, _S2, _N*sizeof(wchar_t));
    #pragma warning( pop )
} 

FIFO based Queue implementations?

Yeah. Queue

LinkedList being the most trivial concrete implementation.

How to undo 'git reset'?

1.Use git reflog to get all references update.

2.git reset <id_of_commit_to_which_you_want_restore>

Class Not Found Exception when running JUnit test

This appears to occur because only the source code is compiling when you use mvn clean compile (I'm using maven 3.1.0 so I'm not sure if it always behaved like this).

If you run mvn test, the test code will compile as well, but then it runs the tests (which may not be immediately desirable if you're trying to run them through Eclipse.) The way around this is to add test-compile to your Maven command sequence whenever you do a mvn clean. For example, you would run mvn clean compile test-compile.

Where should my npm modules be installed on Mac OS X?

If you want to know the location of you NPM packages, you should:

which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x  1 t04435  admin    46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js

So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.

cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed

OR

npm root -g

As per @anthonygore 's comment

How to construct a REST API that takes an array of id's for the resources

If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:

api.com/users?id=id1,id2,id3,id4,id5

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

You can also add

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
/> 

under META-INF/context.xml file (This will be only at application level).

Appending a byte[] to the end of another byte[]

You need to declare out as a byte array with a length equal to the lengths of ciphertext and mac added together, and then copy ciphertext over the beginning of out and mac over the end, using arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) {
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result;
} 

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

Rails filtering array of objects by attribute value

You can filter using where

Job.includes(:attachments).where(file_type: ["logo", "image"])

Intent.putExtra List

you can do it in two ways using

  • Serializable

  • Parcelable.

This examle will show you how to implement it with serializable

class Customer implements Serializable
{
   // properties, getter setters & constructor
}

// This is your custom object
Customer customer = new Customer(name, address, zip);

Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);

// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
    Customer customer = (Customer)extras.getSerializable("customer");
    // do something with the customer
}

Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.

Look at this.. This discussion will let you know which is much better way to implement it.

Thanks.

Is it possible to use a div as content for Twitter's Popover

Why so complicated? just put this :

data-html='true'

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

How to print struct variables in console?

I recommend to use Pretty Printer Library. In that you can print any struct very easily.

  1. Install Library

    https://github.com/kr/pretty

or

go get github.com/kr/pretty

Now do like this in your code

package main

import (
fmt
github.com/kr/pretty
)

func main(){

type Project struct {
    Id int64 `json:"project_id"`
    Title string `json:"title"`
    Name string `json:"name"`
    Data Data `json:"data"`
    Commits Commits `json:"commits"`
}

fmt.Printf("%# v", pretty.Formatter(Project)) //It will print all struct details

fmt.Printf("%# v", pretty.Formatter(Project.Id)) //It will print component one by one.

}

Also you can get difference between component through this library and so more. You can also have a look on library Docs here.

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

ReactJS - Get Height of an element

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

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

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

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

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

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

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

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

Remote origin already exists on 'git push' to a new repository

The previous solutions seem to ignore origin, and they only suggest to use another name. When you just want to use git push origin, keep reading.

The problem appears because a wrong order of Git configuration is followed. You might have already added a 'git origin' to your .git configuration.

You can change the remote origin in your Git configuration with the following line:

git remote set-url origin [email protected]:username/projectname.git

This command sets a new URL for the Git repository you want to push to. Important is to fill in your own username and projectname

How to _really_ programmatically change primary and accent color in Android Lollipop?

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let's say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>
</style>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>
</style>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>
</style>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>
</style>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

load json into variable

_x000D_
_x000D_
var itens = null;_x000D_
$.getJSON("yourfile.json", function(data) {_x000D_
  itens = data;_x000D_
  itens.forEach(function(item) {_x000D_
    console.log(item);_x000D_
  });_x000D_
});_x000D_
console.log(itens);
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Android Material Design Button Styles

I've just created an android library, that allows you to easily modify the button color and the ripple color

https://github.com/xgc1986/RippleButton

<com.xgc1986.ripplebutton.widget.RippleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    android:text="Android button modified in layout"
    android:textColor="@android:color/white"
    app:buttonColor="@android:color/black"
    app:rippleColor="@android:color/white"/>

You don't need to create an style for every button you want wit a different color, allowing you to customize the colors randomly

Finding the length of a Character Array in C

There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

Setting PHP tmp dir - PHP upload not working

create php-file with:

<?php
    print shell_exec( 'whoami' );
?>

or

<?php echo exec('whoami'); ?>

try the output in your web-browser. if the output is not your user example: www-data then proceed to next step

open as root:

/etc/apache2/envvars

look for these lines:

export APACHE_RUN_USER=user-name

export APACHE_RUN_GROUP=group-name

example:

export APACHE_RUN_USER=www-data

export APACHE_RUN_GROUP=www-data

where:

username = your username that has access to the folder you are using group = group you've given read+write+execute access

change it to:

export APACHE_RUN_USER="username"

export APACHE_RUN_GROUP="group"

if your user have no access yet:

sudo chmod 775 -R "directory of folder you want to give r/w/x access"

How can I get current date in Android?

just one line code to get simple Date format :

SimpleDateFormat.getDateInstance().format(Date())

output : 18-May-2020

SimpleDateFormat.getDateTimeInstance().format(Date())

output : 18-May-2020 11:00:39 AM

SimpleDateFormat.getTimeInstance().format(Date())

output : 11:00:39 AM

Hope this answer is enough to get this Date and Time Format ... :)

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

How do I abort the execution of a Python script?

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is not a standard header. Most commonly it refers to the header for Borland's BGI API for DOS and is antiquated at best.

However it is nicely simple; there is a Win32 implementation of the BGI interface called WinBGIm. It is implemented using Win32 GDI calls - the lowest level Windows graphics interface. As it is provided as source code, it is perhaps a simple way of understanding how GDI works.

WinBGIm however is by no means cross-platform. If all you want are simple graphics primitives, most of the higher level GUI libraries such as wxWidgets and Qt support that too. There are simpler libraries suggested in the possible duplicate answers mentioned in the comments.

When do I have to use interfaces instead of abstract classes?

With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

Have a look at oracle documentation too to understand the differences in better way.

Have a look at this related SE questions with code example to understand things in better way:

How should I have explained the difference between an Interface and an Abstract class?

How to import/include a CSS file using PHP code and not HTML code?

I don't know why you would need this but to do this, you could edit your css file:-

<style type="text/css">
body{
...;
...;
}
</style>

You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit


Then edit your HTML file like this. NOTE: Make the include statement inside the tag

<html>
<head>
 <title>Sample</title>
 <?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>

Python | change text color in shell

curses will allow you to use colors properly for the type of terminal that is being used.

The 'json' native gem requires installed build tools

I have found that the error is sometimes caused by a missing library.

so If you install RDOC first by running

gem install rdoc

then install rails with:

gem install rails

then go back and install the devtools as mentioned before with:

1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install

then try installing json

which culminate with you finally being able to run

rails new project_name - without errors.

good luck

MVC 4 Data Annotations "Display" Attribute

One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text

[Display(Name = "Wild and Crazy")]
public string WildAndCrazyProperty { get; set; }

"Wild and Crazy" shows up consistently wherever you use the property in your application.

Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example

How to create a library project in Android Studio and an application project that uses the library project

Don't forget to use apply plugin: 'com.android.library' in your build.gradle instead of apply plugin: 'com.android.application'

Replace comma with newline in sed on MacOS?

This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...

$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt

... where the ^J is done by doing ctrl+v+j. Do mind the \ before the ^J.

PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...

jQuery UI Alert Dialog as a replacement for alert()

As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.

This can also be cleaned up simply by adding:

$(this).dialog('destroy').remove();

to the close method of the dialog. Example adding this line to eidylon's answer:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: function() { onCloseCallback();
                           /* Cleanup node(s) from DOM */
                           $(this).dialog('destroy').remove();
                          }
    });
}

EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs :

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

Searching for UUIDs in text with regex

@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:

[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}

Would have just commented this but not enough rep :)

Java serialization - java.io.InvalidClassException local class incompatible

For me, I forgot to add the default serial id.

private static final long serialVersionUID = 1L;

Number of regex matches

#An example for counting matched groups
import re

pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"

res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4  
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String

Android Studio: Default project directory

I have Android Studio version 3.1.2, it shows project full path when you click Build tab in bottom-left location of the studio.

enter image description here

Get current category ID of the active page

Alternative -

 $catID = the_category_ID($echo=false);

EDIT: Above function is deprecated please use get_the_category()

How to split a line into words separated by one or more spaces in bash?

If you already have your line of text in a variable $LINE, then you should be able to say

for L in $LINE; do
   echo $L;
done

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

UILabel is not auto-shrinking text to fit label size

In Swift 4 (Programmatically):

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200.0, height: 200.0))
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 0

label.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

view.addSubview(label)

How can I split a string with a string delimiter?

There is a version of string.Split that takes an array of strings and a StringSplitOptions parameter:

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

java.lang.IllegalArgumentException: View not attached to window manager

Migh below code works for you, It works for me perfectly fine:

private void viewDialog() {
    try {
        Intent vpnIntent = new Intent(context, UtilityVpnService.class);
        context.startService(vpnIntent);
        final View Dialogview = View.inflate(getBaseContext(), R.layout.alert_open_internet, null);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_DIM_BEHIND,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        windowManager.addView(Dialogview, params);

        Button btn_cancel = (Button) Dialogview.findViewById(R.id.btn_canceldialog_internetblocked);
        Button btn_okay = (Button) Dialogview.findViewById(R.id.btn_openmainactivity);
        RelativeLayout relativeLayout = (RelativeLayout) Dialogview.findViewById(R.id.rellayout_dialog);

            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (Dialogview != null) {
//                                ( (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                    windowManager.removeView(Dialogview);
                                }
                            } catch (final IllegalArgumentException e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } catch (final Exception e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } finally {
                                try {
                                    if (windowManager != null && Dialogview != null) {
//                                    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                        windowManager.removeView(Dialogview);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            //    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
//                        windowManager.removeView(Dialogview);


                        }
                    });
                }
            });
            btn_okay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //        ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                            try {
                                if (windowManager != null && Dialogview != null)
                                    windowManager.removeView(Dialogview);
                                Intent intent = new Intent(getBaseContext(), SplashActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


                                context.startActivity(intent);
                            } catch (Exception e) {
                                windowManager.removeView(Dialogview);
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        } catch (Exception e) {
            //` windowManager.removeView(Dialogview);
            e.printStackTrace();
        }
    }

Do not define your view globally if u call it from background service.

Delegation: EventEmitter or Observable in Angular

You need to use the Navigation component in the template of ObservingComponent ( dont't forget to add a selector to Navigation component .. navigation-component for ex )

<navigation-component (navchange)='onNavGhange($event)'></navigation-component>

And implement onNavGhange() in ObservingComponent

onNavGhange(event) {
  console.log(event);
}

Last thing .. you don't need the events attribute in @Componennt

events : ['navchange'], 

Reading a text file with SQL Server

Just discovered this:

SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents

It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB with:

SINGLE_NCLOB for nvarchar(max) SINGLE_BLOB for varbinary(max)

Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Checking for duplicate strings in JavaScript array

Using ES6 features

function checkIfDuplicateExists(w){
    return new Set(w).size !== w.length 
}

console.log(
    checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);

console.log(
    checkIfDuplicateExists(["a", "b", "c"]))
//false

Use of 'prototype' vs. 'this' in JavaScript?

I believe that @Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.

var A = function() {};
A.prototype = {
    _instance_var: 0,

    initialize: function(v) { this._instance_var = v; },

    x: function() {  alert(this._instance_var); }
};

EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.

CSS div element - how to show horizontal scroll bars only?

To show both:

<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: scroll; padding-bottom:10px;">      </div>

Hide X Axis:

<div style="height:250px; width:550px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;">      </div>

Hide Y Axis:

<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;">      </div>

What is the most efficient way to check if a value exists in a NumPy array?

Adding to @HYRY's answer in1d seems to be fastest for numpy. This is using numpy 1.8 and python 2.7.6.

In this test in1d was fastest, however 10 in a look cleaner:

a = arange(0,99999,3)
%timeit 10 in a
%timeit in1d(a, 10)

10000 loops, best of 3: 150 µs per loop
10000 loops, best of 3: 61.9 µs per loop

Constructing a set is slower than calling in1d, but checking if the value exists is a bit faster:

s = set(range(0, 99999, 3))
%timeit 10 in s

10000000 loops, best of 3: 47 ns per loop

Can't find @Nullable inside javax.annotation.*

JSR-305 is a "Java Specification Request" to extend the specification. @Nullable etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.

FindBugs was renamed to SpotBugs and is being developed under that name.

For maven this is the current annotation-only dependency (other integrations here):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>

If you wish to use the full plugin, refer to the documentation of SpotBugs.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

install certificate in java linux

/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password

How to read connection string in .NET Core?

You can do this with the GetConnectionString extension-method:

string conString = Microsoft
   .Extensions
   .Configuration
   .ConfigurationExtensions
   .GetConnectionString(this.Configuration, "DefaultConnection");

System.Console.WriteLine(conString);

or with a structured-class for DI:

public class SmtpConfig
{
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
}

Startup:

public IConfigurationRoot Configuration { get; }


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));

And then in the home-controller:

public class HomeController : Controller
{

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
        SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
        System.Console.WriteLine(SmtpConfig);
        return View();
    }

with this in appsettings.json:

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"Smtp": {
    "Server": "0.0.0.1",
    "User": "[email protected]",
    "Pass": "123456789",
    "Port": "25"
  }

How to launch Safari and open URL from iOS app

In SWIFT 3.0

               if let url = URL(string: "https://www.google.com") {
                 UIApplication.shared.open(url, options: [:])
               }

Could not resolve all dependencies for configuration ':classpath'

I'm using Gradle plugin 3.0.1 and saw this error. Not sure what caused this but the solution that works for me is to stop the running Gradle daemon by ./gradlew --stop.

Unfortunately MyApp has stopped. How can I solve this?

Check your Logcat message and see your Manifest file. There should be something missing like defining the Activity,User permission`, etc.

git - remote add origin vs remote set-url origin

1. git remote add origin [email protected]:User/UserRepo.git

  • This command is the second step in the command series after you initialize git into your current working repository using git init.
  • This command simply means "you are adding the location of your remote repository where you wish to push/pull your files to/from !!.."
  • Your remote repository could be anywhere on github, gitlab, bitbucket, etc.
  • Here origin is an alias/alternate name for your remote repository so that you don't have to type the entire path for remote every time and henceforth you are declaring that you will use this name(origin) to refer to your remote. This name could be anything.
  • To verify that the remote is set properly type : git remote -v

OR git remote get-url origin

2. git remote set-url origin [email protected]:User/UserRepo.git

This command means that if at any stage you wish to change the location of your repository(i.e if you made a mistake while adding the remote path using the git add command) the first time, you can easily go back & "reset(update) your current remote repository path" by using the above command.

3. git push -u remote master

This command simply pushes your files to the remote repository.Git has a concept of something known as a "branch", so by default everything is pushed to the master branch unless explicitly specified an alternate branch.

To know about the list of all branches you have in your repository type :git branch

JFrame.dispose() vs System.exit()

In addition to the above you can use the System.exit() to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code); this can help you determine for example if an error has occured during the run.

Page Redirect after X seconds wait using JavaScript

$(document).ready(function() {
    window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});

How do I get indices of N maximum values in a NumPy array?

Use:

from operator import itemgetter
from heapq import nlargest
result = nlargest(N, enumerate(your_list), itemgetter(1))

Now the result list would contain N tuples (index, value) where value is maximized.

How to subtract X days from a date using Java calendar?

I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.

Example for subtracting 5 days from the current time and getting the result as Date:

new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());

Another example for subtracting 1 hour and adding 15 minutes:

Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));

If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:

minusNano()
plusNano()
getNano()

Also, keep in mind, that Date is not as accurate as Instant.

How can I present a file for download from an MVC controller?

Use .ashx file type and use the same code

Deep copy vs Shallow Copy

Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.

What type of a copy does a copy constructor does?

It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

The minimal permissions that worked for me when running HeadObject on any object in mybucket:

        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::mybucket/*",
                "arn:aws:s3:::mybucket"
            ]
        }

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'number') {
   //whatever
}

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

The type of an array is still object. Here you really need the instanceof operator.

Update:

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

How do I create a unique constraint that also allows nulls?

For people who are using Microsoft SQL Server Manager and want to create a Unique but Nullable index you can create your unique index as you normally would then in your Index Properties for your new index, select "Filter" from the left hand panel, then enter your filter (which is your where clause). It should read something like this:

([YourColumnName] IS NOT NULL)

This works with MSSQL 2012

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

Clear dropdown using jQuery Select2

This is how I do:

$('#my_input').select2('destroy').val('').select2();

Mean filter for smoothing images in Matlab

h = fspecial('average', n);
filter2(h, img);

See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h.

Batch files: List all files in a directory with relative paths

@echo on>out.txt
@echo off
setlocal enabledelayedexpansion
set "parentfolder=%CD%"
for /r . %%g in (*.*) do (
  set "var=%%g"
  set var=!var:%parentfolder%=!
  echo !var! >> out.txt
)

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

Why shouldn't I use mysql_* functions in PHP?

The MySQL extension is the oldest of the three and was the original way that developers used to communicate with MySQL. This extension is now being deprecated in favor of the other two alternatives because of improvements made in newer releases of both PHP and MySQL.

  • MySQLi is the 'improved' extension for working with MySQL databases. It takes advantage of features that are available in newer versions of the MySQL server, exposes both a function-oriented and an object-oriented interface to the developer and a does few other nifty things.

  • PDO offers an API that consolidates most of the functionality that was previously spread across the major database access extensions, i.e. MySQL, PostgreSQL, SQLite, MSSQL, etc. The interface exposes high-level objects for the programmer to work with database connections, queries and result sets, and low-level drivers perform communication and resource handling with the database server. A lot of discussion and work is going into PDO and it’s considered the appropriate method of working with databases in modern, professional code.

Angular.js How to change an elements css class on click and to remove all others

HTML

<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>

How to set image to UIImage

Like vikingosgundo said, but keep in mind that if you use [UIImage imageNamed:image] then the image is cached and eats away memory. So unless you plan on using the same image in many places, you should load the image, with imageWithContentsOfFile: and imageWithData:

This will save you significant memory and speeds up your app.

jQuery event for images loaded

$( "img.photo" ).load(function() {

    $(".parrentDiv").css('height',$("img.photo").height());
    // very simple

}); 

How to add SHA-1 to android application

Just In case: while using the command line to generate the SHA1 fingerprint, be careful while specifying the folder path. If your User Name or android folder path has a space, you should add two double quotes as below:

keytool -list -v -keystore "C:\Users\User Name\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

How to send email to multiple address using System.Net.Mail

 string[] MultiEmails = email.Split(',');
 foreach (string ToEmail in MultiEmails)
 {
    message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
 }

Method call if not null in C#

From C# 6 onwards, you can just use:

MyEvent?.Invoke();

or:

obj?.SomeMethod();

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.

===

Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:

public static void SafeInvoke(this Action action) {
    if(action != null) action();
}

now this is valid:

Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"

In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:

var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);

but with:

public static void SafeInvoke(this EventHandler handler, object sender) {
    if(handler != null) handler(sender, EventArgs.Empty);
}

we can use simply:

SomeEvent.SafeInvoke(this); // no race condition, no null risk

Jackson serialization: ignore empty values (or null)

I was having similar problem recently with version 2.6.6.

@JsonInclude(JsonInclude.Include.NON_NULL)

Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.

I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.

So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.

How to add style from code behind?

If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:

.disabled {
    color: grey;
    text-decoration: none !important;
}

LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

What's the difference between SHA and AES encryption?

SHA and AES serve different purposes. SHA is used to generate a hash of data and AES is used to encrypt data.

Here's an example of when an SHA hash is useful to you. Say you wanted to download a DVD ISO image of some Linux distro. This is a large file and sometimes things go wrong - so you want to validate that what you downloaded is correct. What you would do is go to a trusted source (such as the offical distro download point) and they typically have the SHA hash for the ISO image available. You can now generated the comparable SHA hash (using any number of open tools) for your downloaded data. You can now compare the two hashs to make sure they match - which would validate that the image you downloaded is correct. This is especially important if you get the ISO image from an untrusted source (such as a torrent) or if you are having trouble using the ISO and want to check if the image is corrupted.

As you can see in this case the SHA has was used to validate data that was not corrupted. You have every right to see the data in the ISO.

AES, on the other hand, is used to encrypt data, or prevent people from viewing that data with knowing some secret.

AES uses a shared key which means that the same key (or a related key) is used to encrypted the data as is used to decrypt the data. For example if I encrypted an email using AES and I sent that email to you then you and I would both need to know the shared key used to encrypt and decrypt the email. This is different than algorithms that use a public key such PGP or SSL.

If you wanted to put them together you could encrypt a message using AES and then send along an SHA1 hash of the unencrypted message so that when the message was decrypted they were able to validate the data. This is a somewhat contrived example.

If you want to know more about these some Wikipedia search terms (beyond AES and SHA) you want want to try include:

Symmetric-key algorithm (for AES) Cryptographic hash function (for SHA) Public-key cryptography (for PGP and SSL)

How to programmatically tell if a Bluetooth device is connected?

Big thanks to Skylarsutton for his answer. I'm posting this as a response to his, but because I'm posting code I can't reply as a comment. I already upvoted his answer so am not looking for any points. Just paying it forward.

For some reason BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2? Here is a modification of his code. The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.

    public void onCreate() {
        //...
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(BTReceiver, filter);
    }

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};

What is a mixin, and why are they useful?

I think of them as a disciplined way of using multiple inheritance - because ultimately a mixin is just another python class that (might) follow the conventions about classes that are called mixins.

My understanding of the conventions that govern something you would call a Mixin are that a Mixin:

  • adds methods but not instance variables (class constants are OK)
  • only inherits from object (in Python)

That way it limits the potential complexity of multiple inheritance, and makes it reasonably easy to track the flow of your program by limiting where you have to look (compared to full multiple inheritance). They are similar to ruby modules.

If I want to add instance variables (with more flexibility than allowed for by single inheritance) then I tend to go for composition.

Having said that, I have seen classes called XYZMixin that do have instance variables.

The infamous java.sql.SQLException: No suitable driver found

The infamous java.sql.SQLException: No suitable driver found

This exception can have basically two causes:

1. JDBC driver is not loaded

You need to ensure that the JDBC driver is placed in server's own /lib folder.

Or, when you're actually not using a server-managed connection pool data source, but are manually fiddling around with DriverManager#getConnection() in WAR, then you need to place the JDBC driver in WAR's /WEB-INF/lib and perform ..

Class.forName("com.example.jdbc.Driver");

.. in your code before the first DriverManager#getConnection() call whereby you make sure that you do not swallow/ignore any ClassNotFoundException which can be thrown by it and continue the code flow as if nothing exceptional happened. See also Where do I have to place the JDBC driver for Tomcat's connection pool?

2. Or, JDBC URL is in wrong syntax

You need to ensure that the JDBC URL is conform the JDBC driver documentation and keep in mind that it's usually case sensitive. When the JDBC URL does not return true for Driver#acceptsURL() for any of the loaded drivers, then you will also get exactly this exception.

In case of PostgreSQL it is documented here.

With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL™, this takes one of the following forms:

  • jdbc:postgresql:database
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host:port/database

In case of MySQL it is documented here.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] » [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

In case of Oracle it is documented here.

There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.

Old syntax jdbc:oracle:thin:@[HOST][:PORT]:SID

New syntax jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE


See also:

SQL - HAVING vs. WHERE

HAVING operates on aggregates. Since COUNT is an aggregate function, you can't use it in a WHERE clause.

Here's some reading from MSDN on aggregate functions.

File inside jar is not visible for spring

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

Example.java

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

ResourceLoader rl = new ResourceLoader();

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

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

ResourceLoader.java

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

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

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

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

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

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

javascript functions to show and hide divs

You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.

<div id="upbutton"><a href="#" onclick="close2()">click to close</a></div>

Also if you want a real "button" instead of a link, you should use <input type="button"/> or <button/>.

Combine two columns of text in pandas dataframe

Use of a lamba function this time with string.format().

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': ['q1', 'q2']})
print df
df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
print df

  Quarter  Year
0      q1  2014
1      q2  2015
  Quarter  Year YearQuarter
0      q1  2014      2014q1
1      q2  2015      2015q2

This allows you to work with non-strings and reformat values as needed.

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': [1, 2]})
print df.dtypes
print df

df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}q{}'.format(x[0],x[1]), axis=1)
print df

Quarter     int64
Year       object
dtype: object
   Quarter  Year
0        1  2014
1        2  2015
   Quarter  Year YearQuarter
0        1  2014      2014q1
1        2  2015      2015q2

How do you show animated GIFs on a Windows Form (c#)

It doesn't when you start a long operation behind, because everything STOPS since you'Re in the same thread.

How do I make a checkbox required on an ASP.NET form?

If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control

public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
    private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
    protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
    {
        get
        {
            if (_ctrlToValidate == null)
                _ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;

            return _ctrlToValidate;
        }
    }

    protected override bool ControlPropertiesValid()
    {
        if (this.ControlToValidate.Length == 0)
            throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));

        if (this.CheckBoxToValidate == null)
            throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));

        return true;
    }

    protected override bool EvaluateIsValid()
    {
        return CheckBoxToValidate.Checked;
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (this.Visible && this.Enabled)
        {
            System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
            }
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
            {
                cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
            } 
        }
    }

    private string GetClientSideScript()
    {
        return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
    }
}

No newline at end of file

It's not just bad style, it can lead to unexpected behavior when using other tools on the file.

Here is test.txt:

first line
second line

There is no newline character on the last line. Let's see how many lines are in the file:

$ wc -l test.txt
1 test.txt

Maybe that's what you want, but in most cases you'd probably expect there to be 2 lines in the file.

Also, if you wanted to combine files it may not behave the way you'd expect:

$ cat test.txt test.txt
first line
second linefirst line
second line

Finally, it would make your diffs slightly more noisy if you were to add a new line. If you added a third line, it would show an edit to the second line as well as the new addition.

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

keycode and charcode

Handling key events consistently is not at all easy.

Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for keyup and keydown events.

Secondly, you get different sets of values in a keypress event to what you get in a keyup or keydown event.

I recommend this page as a useful resource. As a summary:

If you're interested in detecting a user typing a character, use the keypress event. IE bizarrely only stores the character code in keyCode while all other browsers store it in which. Some (but not all) browsers also store it in charCode and/or keyCode. An example keypress handler:

function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
}

If you're interested in detecting a non-printable key (such as a cursor key), use the keydown event. Here keyCode is always the property to use. Note that keyup events have the same properties.

function(evt) {
  evt = evt || window.event;
  var keyCode = evt.keyCode;

  // Check for left arrow key
  if (keyCode == 37) {
    alert("Left arrow");
  }
}

Java Serializable Object to Byte Array

Prepare the byte array to send:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  out.flush();
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}

Create an object from a byte array:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} finally {
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
}

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Add CultureInfo.InvariantCulture as an argument:

using System.Globalization;

...

var dateTime = new DateTime(2016,8,16);
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Will return:

"16/08/2016"

Execute a PHP script from another PHP script

On the command line:

> php yourfile.php

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */
 }

 .big {
     height: 60px;
     width: 100px;
 }
 .small {
     height: 40px;
     width: 70px;
 }

and so on.

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

Counting unique / distinct values by group in a data frame

A data.table approach

library(data.table)
DT <- data.table(myvec)

DT[, .(number_of_distinct_orders = length(unique(order_no))), by = name]

data.table v >= 1.9.5 has a built in uniqueN function now

DT[, .(number_of_distinct_orders = uniqueN(order_no)), by = name]

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

Retrieving Property name from lambda expression

static void Main(string[] args)
{
    var prop = GetPropertyInfo<MyDto>(_ => _.MyProperty);

    MyDto dto = new MyDto();
    dto.MyProperty = 666;

    var value = prop.GetValue(dto);
    // value == 666
}

class MyDto
{
    public int MyProperty { get; set; }
}

public static PropertyInfo GetPropertyInfo<TSource>(Expression<Func<TSource, object>> propertyLambda)
{
    Type type = typeof(TSource);

    var member = propertyLambda.Body as MemberExpression;
    if (member == null)
    {
        var unary = propertyLambda.Body as UnaryExpression;
        if (unary != null)
        {
            member = unary.Operand as MemberExpression;
        }
    }
    if (member == null)
    {
        throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.",
            propertyLambda.ToString()));
    }

    var propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
    {
        throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.",
            propertyLambda.ToString()));
    }

    if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
    {
        throw new ArgumentException(string.Format("Expression '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(), type));
    }

    return propInfo;
}

jQuery animated number counter from zero to value

Your thisdoesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $thisin my example):

$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });
});

Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil you can round up to 2 decimals for instance with value.toFixed(2):

step: function () {
  $this.text(this.Counter.toFixed(2));
}

when I run mockito test occurs WrongTypeOfReturnValue Exception

I'm using Scala and I've got this message where I've mistakenly shared a Mock between two Objects. So, be sure that your tests are independent of each other. The parallel test execution obviously creates some flaky situations since the objects in Scala are singleton compositions.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I was upgrading tensorflow to 1.4.0 & was hitting my head on wall as this error was not solving, but finally solved it. Guess what?

One of my python script was running, and it was using tensorflow . Package installed successfully after closing it.

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

Duplicate AssemblyVersion Attribute

I found this answer on msdn, that explains marking the file as Content and then Copy to Output = If Newer. See article below:

https://social.msdn.microsoft.com/Forums/en-US/8671bdff-9b16-4b49-ba9e-227cc4df31b2/compile-error-cs0579-duplicate-assemblyversion-attribute?forum=vsgatk

GH

FlutterError: Unable to load asset

For me,

  1. flutter clean,
  2. Restart the android studio and emulator,
  3. giving full patth in my image

    image: AssetImage(
      './lib/graphics/logo2.png'
       ),
       width: 200,
       height: 200,
     );
    

these three steps did the trick.

Build query string for System.Net.HttpClient get

Or simply using my Uri extension

Code

public static Uri AttachParameters(this Uri uri, NameValueCollection parameters)
{
    var stringBuilder = new StringBuilder();
    string str = "?";
    for (int index = 0; index < parameters.Count; ++index)
    {
        stringBuilder.Append(str + parameters.AllKeys[index] + "=" + parameters[index]);
        str = "&";
    }
    return new Uri(uri + stringBuilder.ToString());
}

Usage

Uri uri = new Uri("http://www.example.com/index.php").AttachParameters(new NameValueCollection
                                                                           {
                                                                               {"Bill", "Gates"},
                                                                               {"Steve", "Jobs"}
                                                                           });

Result

http://www.example.com/index.php?Bill=Gates&Steve=Jobs

Total number of items defined in an enum

You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

GetNames produces much the same result as GetValues but is faster.

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

How to pass data to all views in Laravel 5?

In the documentation:

Typically, you would place calls to the share method within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.

I'm agree with Marwelln, just put it in AppServiceProvider in the boot function:

public function boot() {
    View::share('youVarName', [1, 2, 3]);
}

I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

How to change the session timeout in PHP?

Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.

If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.

Convenience in relaxed environments: how and why

If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:

// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);

session_start(); // ready to go!

This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.

  • If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.

    GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.

  • If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.

Certainty in critical environments

You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.

Do this by saving the upper bound together with the rest of the session data:

session_start(); // ready to go!

$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
    // this session has worn out its welcome; kill it and start a brand new one
    session_unset();
    session_destroy();
    session_start();
}

// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;

Session id persistence

So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.

Take multiple lists into dataframe

Adding to above answers, we can create on the fly

df= pd.DataFrame()
list1 = list(range(10))
list2 = list(range(10,20))
df['list1'] = list1
df['list2'] = list2
print(df)

hope it helps !

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Pandas - Compute z-score for all columns

If you want to calculate the zscore for all of the columns, you can just use the following:

df_zscore = (df - df.mean())/df.std()

How do I discard unstaged changes in Git?

If it's almost impossible to rule out modifications of the files, have you considered ignoring them? If this statement is right and you wouldn't touch those files during your development, this command may be useful:

git update-index --assume-unchanged file_to_ignore

Node JS Error: ENOENT

You can include a different jade file into your template, that to from a different directory

views/
     layout.jade
static/
     page.jade

To include the layout file from views dir to static/page.jade

page.jade

extends ../views/layout

Fixed page header overlaps in-page anchors

Add a class with a "paddingtop" so it works ;)

<h1><a class="paddingtop">Bar</a></h1>

And for css you have:

.paddingtop { 
   padding-top: 90px; 
}

How to bind DataTable to Datagrid

I'm expecting, as Rohit Vats mentioned in his Comment too, that you have a wrong structure in your DataTable.

Try something like this:

  var t = new DataTable();

  // create column header
  foreach ( string s in identifiders ) {
    t.Columns.Add(new DataColumn(s)); // <<=== i'm expecting you don't have defined any DataColumns, haven't you?
  }

  // Add data to DataTable
  for ( int lineNumber = identifierLineNumber; lineNumber < lineCount; lineNumber++ ) {
    DataRow newRow = t.NewRow();
    for ( int column = 0; column < identifierCount; column++ ) {
      newRow[column] = fileContent.ElementAt(lineNumber)[column];
    }
    t.Rows.Add(newRow);
  }

  return t.DefaultView;

I have used this DataTable in a ValueConverter and it works like a charm with the following binding.

xaml:

 <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Path=FileContent, Converter={StaticResource dataGridConverter}}" />

So what it does, the ValueConverter transforms my bounded data (what ever it is, in my case it's a List<string[]>) into a DataTable, as the code above shows, and passes this DataTable to the DataGrid. With specified data columns the data grid can generate the needed columns and visualize them.

To say it in a nutshell, in my case the binding to a DataTable works like a charm.

Flattening a shallow list in Python

If each item in the list is a string (and any strings inside those strings use " " rather than ' '), you can use regular expressions (re module)

>>> flattener = re.compile("\'.*?\'")
>>> flattener
<_sre.SRE_Pattern object at 0x10d439ca8>
>>> stred = str(in_list)
>>> outed = flattener.findall(stred)

The above code converts in_list into a string, uses the regex to find all the substrings within quotes (i.e. each item of the list) and spits them out as a list.

Concatenating two one-dimensional NumPy arrays

Here are more approaches for doing this by using numpy.ravel(), numpy.array(), utilizing the fact that 1D arrays can be unpacked into plain elements:

# we'll utilize the concept of unpacking
In [15]: (*a, *b)
Out[15]: (1, 2, 3, 5, 6)

# using `numpy.ravel()`
In [14]: np.ravel((*a, *b))
Out[14]: array([1, 2, 3, 5, 6])

# wrap the unpacked elements in `numpy.array()`
In [16]: np.array((*a, *b))
Out[16]: array([1, 2, 3, 5, 6])

Can Javascript read the source of any web page?

<script>
    $.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('hhttps://example.com/') + '&callback=?', function (data) {
        alert(data.contents);
    });

</script>

Include jQuery and use this code to get HTML of other website. Replace example.com with your website.

This method involves an external server fetching the sites HTML & sending it to you. :)

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

UIWebView open links in Safari

In Swift you can use the following code:

extension YourViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if let url = request.url, navigationType == UIWebView.NavigationType.linkClicked {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
            return false
        }
        return true
    }

}

Make sure you check for the URL value and the navigationType.

Swift Set to Array

I created a simple extension that gives you an unsorted Array as a property of Set in Swift 4.0.

extension Set {
    var array: [Element] {
        return Array(self)
    }
}

If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.

To use this, just call

let array = set.array

CSS scrollbar style cross browser

nanoScrollerJS is simply to use. I always use them...

Browser compatibility:
  • IE7+
  • Firefox 3+
  • Chrome
  • Safari 4+
  • Opera 11.60+
Mobile browsers support:
  • iOS 5+ (iPhone, iPad and iPod Touch)
  • iOS 4 (with a polyfill)
  • Android Firefox
  • Android 2.2/2.3 native browser (with a polyfill)
  • Android Opera 11.6 (with a polyfill)

Code example from the Documentation,

  1. Markup - The following type of markup structure is needed to make the plugin work.
<div id="about" class="nano">
    <div class="nano-content"> ... content here ...  </div>
</div>

Get total size of file in bytes

public static void main(String[] args) {
        try {
            File file = new File("test.txt");
            System.out.println(file.length());
        } catch (Exception e) {
        }
    }

Determine device (iPhone, iPod Touch) with iOS

You can check GBDeviceInfo on GitHub, also available via CocoaPods. It provides simple API for detecting various properties with support of all latest devices:

  • Device family

[GBDeviceInfo deviceDetails].family == GBDeviceFamilyiPhone;

  • Device model

[GBDeviceInfo deviceDetails].model == GBDeviceModeliPhone6.

For more see Readme.

handling dbnull data in vb.net

You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.

Android: Center an image

change layout weight according you will get....

Enter this:

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0.03">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:layout_gravity="center"
        android:src="@drawable/logo" />

</LinearLayout>

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()

How to make a TextBox accept only alphabetic characters?

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) &&
         (e.KeyChar !='.'))
        { 
          e.Handled = true;
          MessageBox.Show("Only Alphabets");
        }
    }

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";

lessons is Main table and lessons_game is subtable so Right Join

Cannot set property 'innerHTML' of null

Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.

Unit testing void methods?

Try this:

[TestMethod]
public void TestSomething()
{
    try
    {
        YourMethodCall();
        Assert.IsTrue(true);
    }
    catch {
        Assert.IsTrue(false);
    }
}

How to create an integer array in Python?

If you need to initialize an array fast, you might do it by blocks instead of with a generator initializer, and it's going to be much faster. Creating a list by [0]*count is just as fast, still.

import array

def zerofill(arr, count):
    count *= arr.itemsize
    blocksize = 1024
    blocks, rest = divmod(count, blocksize)
    for _ in xrange(blocks):
        arr.fromstring("\x00"*blocksize)
    arr.fromstring("\x00"*rest)

def test_zerofill(count):
    iarr = array.array('i')
    zerofill(iarr, count)
    assert len(iarr) == count

def test_generator(count):
    iarr = array.array('i', (0 for _ in xrange(count)))
    assert len(iarr) == count

def test_list(count):
    L = [0]*count
    assert len(L) == count

if __name__ == '__main__':
    import timeit
    c = 100000
    n = 10
    print timeit.Timer("test(c)", "from __main__ import c, test_zerofill as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_generator as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_list as test").repeat(number=n)

Results:

(array in blocks) [0.022809982299804688, 0.014942169189453125, 0.014089107513427734]
(array with generator) [1.1884641647338867, 1.1728270053863525, 1.1622772216796875]
(list) [0.023866891860961914, 0.035660028457641602, 0.023386955261230469]

Setting an image for a UIButton in code

Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.

If you want to set both (your image and title) use the following code:

btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Found a similar way to fix this issue (at least it did for me).

  1. First check where the CLI php.ini is located:

    php -i | grep "php.ini"

  2. In my case I ended up with : Configuration File (php.ini) Path => /etc

  3. Then cd .. all the way back and cd into /etc, do ls in my case php.ini didn't show up, only a php.ini.default

  4. Now, copy the php.ini.default file named as php.ini:

    sudo cp php.ini.default php.ini

  5. In order to edit, change the permissions of the file:

    sudo chmod ug+w php.ini

    sudo chgrp staff php.ini

  6. Open directory and edit the php.ini file:

    open .

    Tip: If you are not able to edit the php.ini due to some permissions issue then copy 'php.ini.default' and paste it on your desktop and rename it to 'php.ini' then open it and edit it following step 7. Then move (copy+paste) it in /etc folder. Issue will be resolved.

  7. Search for [Date] and make sure the following line is in the correct format:

    date.timezone = "Europe/Amsterdam"

I hope this could help you out.

Slide right to left?

or you can use

$('#myDiv').toggle("slide:right");

Best way to move files between S3 buckets?

For me the following command just worked:

aws s3 mv s3://bucket/data s3://bucket/old_data --recursive

How to make an HTML back link?

This solution has the benefit of showing the URL of the linked-to page on hover, as most browsers do by default, instead of history.go(-1) or similar:

<script>
    document.write('<a href="' + document.referrer + '">Go Back</a>');
</script>

Converting pixels to dp

In case you developing a performance critical application, please consider the following optimized class:

public final class DimensionUtils {

    private static boolean isInitialised = false;
    private static float pixelsPerOneDp;

    // Suppress default constructor for noninstantiability.
    private DimensionUtils() {
        throw new AssertionError();
    }

    private static void initialise(View view) {
        pixelsPerOneDp = view.getResources().getDisplayMetrics().densityDpi / 160f;
        isInitialised = true;
    }

    public static float pxToDp(View view, float px) {
        if (!isInitialised) {
            initialise(view);
        }

        return px / pixelsPerOneDp;
    }

    public static float dpToPx(View view, float dp) {
        if (!isInitialised) {
            initialise(view);
        }

        return dp * pixelsPerOneDp;
    }
}

Remove property for all objects in array

With ES6, you may deconstruct each object to create new one without named attributes:

const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

Android: How to create a Dialog without a title?

Use this

    Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.image_show_dialog_layout);

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");